blob: 70118d288906be66a1fc9675074b7c5df4cd9d1b [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'",
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000767 Py_Type(p)->tp_name);
Tim Peters855fe882002-12-22 03:43:39 +0000768 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'",
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000858 name, Py_Type(u)->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) {
Guido van Rossumfd53fd62007-08-24 04:05:13 +0000950 if (!PyUnicode_Check(result)) {
Guido van Rossume3d1d412007-05-23 21:24:35 +0000951 PyErr_Format(PyExc_TypeError, "tzinfo.tzname() must "
952 "return None or a string, not '%s'",
Martin v. Löwis5d7428b2007-07-21 18:47:48 +0000953 Py_Type(result)->tp_name);
Guido van Rossume3d1d412007-05-23 21:24:35 +0000954 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{
Neal Norwitzaea70e02007-08-12 04:32:26 +00001134 PyObject *temp;
Guido van Rossumd8595fe2007-05-23 21:36:49 +00001135 PyObject *tzinfo = get_tzinfo_member(object);
Guido van Rossumfd53fd62007-08-24 04:05:13 +00001136 PyObject *Zreplacement = PyBytes_FromStringAndSize("", 0);
Guido van Rossumd8595fe2007-05-23 21:36:49 +00001137 if (Zreplacement == NULL)
1138 return NULL;
Neal Norwitzaea70e02007-08-12 04:32:26 +00001139 if (tzinfo == Py_None || tzinfo == NULL)
1140 return Zreplacement;
1141
1142 assert(tzinfoarg != NULL);
1143 temp = call_tzname(tzinfo, tzinfoarg);
1144 if (temp == NULL)
1145 goto Error;
1146 if (temp == Py_None) {
1147 Py_DECREF(temp);
1148 return Zreplacement;
1149 }
1150
1151 assert(PyUnicode_Check(temp));
1152 /* Since the tzname is getting stuffed into the
1153 * format, we have to double any % signs so that
1154 * strftime doesn't treat them as format codes.
1155 */
1156 Py_DECREF(Zreplacement);
1157 Zreplacement = PyObject_CallMethod(temp, "replace", "ss", "%", "%%");
1158 Py_DECREF(temp);
1159 if (Zreplacement == NULL)
1160 return NULL;
1161 if (PyUnicode_Check(Zreplacement)) {
Guido van Rossumfd53fd62007-08-24 04:05:13 +00001162 PyObject *tmp = PyUnicode_AsUTF8String(Zreplacement);
Neal Norwitz908c8712007-08-27 04:58:38 +00001163 Py_DECREF(Zreplacement);
Guido van Rossumfd53fd62007-08-24 04:05:13 +00001164 if (tmp == NULL)
Neal Norwitzaea70e02007-08-12 04:32:26 +00001165 return NULL;
Guido van Rossumfd53fd62007-08-24 04:05:13 +00001166 Zreplacement = tmp;
Neal Norwitzaea70e02007-08-12 04:32:26 +00001167 }
Guido van Rossumfd53fd62007-08-24 04:05:13 +00001168 if (!PyBytes_Check(Zreplacement)) {
Neal Norwitzaea70e02007-08-12 04:32:26 +00001169 PyErr_SetString(PyExc_TypeError,
1170 "tzname.replace() did not return a string");
1171 goto Error;
Guido van Rossumd8595fe2007-05-23 21:36:49 +00001172 }
1173 return Zreplacement;
1174
1175 Error:
1176 Py_DECREF(Zreplacement);
1177 return NULL;
1178}
1179
Tim Peters2a799bf2002-12-16 20:18:38 +00001180/* I sure don't want to reproduce the strftime code from the time module,
1181 * so this imports the module and calls it. All the hair is due to
1182 * giving special meanings to the %z and %Z format codes via a preprocessing
1183 * step on the format string.
Tim Petersbad8ff02002-12-30 20:52:32 +00001184 * tzinfoarg is the argument to pass to the object's tzinfo method, if
1185 * needed.
Tim Peters2a799bf2002-12-16 20:18:38 +00001186 */
1187static PyObject *
Tim Petersbad8ff02002-12-30 20:52:32 +00001188wrap_strftime(PyObject *object, PyObject *format, PyObject *timetuple,
1189 PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +00001190{
1191 PyObject *result = NULL; /* guilty until proved innocent */
1192
1193 PyObject *zreplacement = NULL; /* py string, replacement for %z */
1194 PyObject *Zreplacement = NULL; /* py string, replacement for %Z */
1195
Guido van Rossumbce56a62007-05-10 18:04:33 +00001196 const char *pin;/* pointer to next char in input format */
1197 Py_ssize_t flen;/* length of input format */
Tim Peters2a799bf2002-12-16 20:18:38 +00001198 char ch; /* next char in input format */
1199
1200 PyObject *newfmt = NULL; /* py string, the output format */
1201 char *pnew; /* pointer to available byte in output format */
Thomas Wouters89f507f2006-12-13 04:49:30 +00001202 int totalnew; /* number bytes total in output format buffer,
Tim Peters2a799bf2002-12-16 20:18:38 +00001203 exclusive of trailing \0 */
Thomas Wouters89f507f2006-12-13 04:49:30 +00001204 int usednew; /* number bytes used so far in output format buffer */
Tim Peters2a799bf2002-12-16 20:18:38 +00001205
Guido van Rossumbce56a62007-05-10 18:04:33 +00001206 const char *ptoappend;/* pointer to string to append to output buffer */
Tim Peters2a799bf2002-12-16 20:18:38 +00001207 int ntoappend; /* # of bytes to append to output buffer */
1208
Tim Peters2a799bf2002-12-16 20:18:38 +00001209 assert(object && format && timetuple);
Guido van Rossumfd53fd62007-08-24 04:05:13 +00001210 assert(PyUnicode_Check(format));
Neal Norwitz908c8712007-08-27 04:58:38 +00001211 /* Convert the input format to a C string and size */
1212 pin = PyUnicode_AsString(format);
1213 if (!pin)
1214 return NULL;
1215 flen = PyUnicode_GetSize(format);
Tim Peters2a799bf2002-12-16 20:18:38 +00001216
Tim Petersd6844152002-12-22 20:58:42 +00001217 /* Give up if the year is before 1900.
1218 * Python strftime() plays games with the year, and different
1219 * games depending on whether envar PYTHON2K is set. This makes
1220 * years before 1900 a nightmare, even if the platform strftime
1221 * supports them (and not all do).
1222 * We could get a lot farther here by avoiding Python's strftime
1223 * wrapper and calling the C strftime() directly, but that isn't
1224 * an option in the Python implementation of this module.
1225 */
1226 {
1227 long year;
1228 PyObject *pyyear = PySequence_GetItem(timetuple, 0);
1229 if (pyyear == NULL) return NULL;
1230 assert(PyInt_Check(pyyear));
1231 year = PyInt_AsLong(pyyear);
1232 Py_DECREF(pyyear);
1233 if (year < 1900) {
1234 PyErr_Format(PyExc_ValueError, "year=%ld is before "
1235 "1900; the datetime strftime() "
1236 "methods require year >= 1900",
1237 year);
1238 return NULL;
1239 }
1240 }
1241
Tim Peters2a799bf2002-12-16 20:18:38 +00001242 /* Scan the input format, looking for %z and %Z escapes, building
Tim Peters328fff72002-12-20 01:31:27 +00001243 * a new format. Since computing the replacements for those codes
1244 * is expensive, don't unless they're actually used.
Tim Peters2a799bf2002-12-16 20:18:38 +00001245 */
Guido van Rossumbce56a62007-05-10 18:04:33 +00001246 totalnew = flen + 1; /* realistic if no %z/%Z */
Guido van Rossumfd53fd62007-08-24 04:05:13 +00001247 newfmt = PyBytes_FromStringAndSize(NULL, totalnew);
Tim Peters2a799bf2002-12-16 20:18:38 +00001248 if (newfmt == NULL) goto Done;
Guido van Rossumfd53fd62007-08-24 04:05:13 +00001249 pnew = PyBytes_AsString(newfmt);
Tim Peters2a799bf2002-12-16 20:18:38 +00001250 usednew = 0;
1251
Tim Peters2a799bf2002-12-16 20:18:38 +00001252 while ((ch = *pin++) != '\0') {
1253 if (ch != '%') {
Tim Peters328fff72002-12-20 01:31:27 +00001254 ptoappend = pin - 1;
Tim Peters2a799bf2002-12-16 20:18:38 +00001255 ntoappend = 1;
1256 }
1257 else if ((ch = *pin++) == '\0') {
1258 /* There's a lone trailing %; doesn't make sense. */
1259 PyErr_SetString(PyExc_ValueError, "strftime format "
1260 "ends with raw %");
1261 goto Done;
1262 }
1263 /* A % has been seen and ch is the character after it. */
1264 else if (ch == 'z') {
1265 if (zreplacement == NULL) {
1266 /* format utcoffset */
Tim Peters328fff72002-12-20 01:31:27 +00001267 char buf[100];
Tim Peters2a799bf2002-12-16 20:18:38 +00001268 PyObject *tzinfo = get_tzinfo_member(object);
Guido van Rossumfd53fd62007-08-24 04:05:13 +00001269 zreplacement = PyBytes_FromStringAndSize("", 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00001270 if (zreplacement == NULL) goto Done;
1271 if (tzinfo != Py_None && tzinfo != NULL) {
Tim Petersbad8ff02002-12-30 20:52:32 +00001272 assert(tzinfoarg != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +00001273 if (format_utcoffset(buf,
Tim Peters328fff72002-12-20 01:31:27 +00001274 sizeof(buf),
Tim Peters2a799bf2002-12-16 20:18:38 +00001275 "",
1276 tzinfo,
Tim Petersbad8ff02002-12-30 20:52:32 +00001277 tzinfoarg) < 0)
Tim Peters2a799bf2002-12-16 20:18:38 +00001278 goto Done;
1279 Py_DECREF(zreplacement);
Guido van Rossumfd53fd62007-08-24 04:05:13 +00001280 zreplacement =
1281 PyBytes_FromStringAndSize(buf,
1282 strlen(buf));
1283 if (zreplacement == NULL)
1284 goto Done;
Tim Peters2a799bf2002-12-16 20:18:38 +00001285 }
1286 }
1287 assert(zreplacement != NULL);
Guido van Rossumfd53fd62007-08-24 04:05:13 +00001288 ptoappend = PyBytes_AS_STRING(zreplacement);
1289 ntoappend = PyBytes_GET_SIZE(zreplacement);
Tim Peters2a799bf2002-12-16 20:18:38 +00001290 }
1291 else if (ch == 'Z') {
1292 /* format tzname */
1293 if (Zreplacement == NULL) {
Guido van Rossumd8595fe2007-05-23 21:36:49 +00001294 Zreplacement = make_Zreplacement(object,
1295 tzinfoarg);
1296 if (Zreplacement == NULL)
1297 goto Done;
Tim Peters2a799bf2002-12-16 20:18:38 +00001298 }
1299 assert(Zreplacement != NULL);
Guido van Rossumfd53fd62007-08-24 04:05:13 +00001300 assert(PyBytes_Check(Zreplacement));
1301 ptoappend = PyBytes_AS_STRING(Zreplacement);
1302 ntoappend = PyBytes_GET_SIZE(Zreplacement);
Tim Peters2a799bf2002-12-16 20:18:38 +00001303 }
1304 else {
Tim Peters328fff72002-12-20 01:31:27 +00001305 /* percent followed by neither z nor Z */
1306 ptoappend = pin - 2;
Tim Peters2a799bf2002-12-16 20:18:38 +00001307 ntoappend = 2;
1308 }
1309
1310 /* Append the ntoappend chars starting at ptoappend to
1311 * the new format.
1312 */
Tim Peters2a799bf2002-12-16 20:18:38 +00001313 if (ntoappend == 0)
1314 continue;
Guido van Rossumfd53fd62007-08-24 04:05:13 +00001315 assert(ptoappend != NULL);
1316 assert(ntoappend > 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00001317 while (usednew + ntoappend > totalnew) {
1318 int bigger = totalnew << 1;
1319 if ((bigger >> 1) != totalnew) { /* overflow */
1320 PyErr_NoMemory();
1321 goto Done;
1322 }
Guido van Rossumfd53fd62007-08-24 04:05:13 +00001323 if (PyBytes_Resize(newfmt, bigger) < 0)
Tim Peters2a799bf2002-12-16 20:18:38 +00001324 goto Done;
1325 totalnew = bigger;
Guido van Rossumfd53fd62007-08-24 04:05:13 +00001326 pnew = PyBytes_AsString(newfmt) + usednew;
Tim Peters2a799bf2002-12-16 20:18:38 +00001327 }
1328 memcpy(pnew, ptoappend, ntoappend);
1329 pnew += ntoappend;
1330 usednew += ntoappend;
1331 assert(usednew <= totalnew);
1332 } /* end while() */
1333
Guido van Rossumfd53fd62007-08-24 04:05:13 +00001334 if (PyBytes_Resize(newfmt, usednew) < 0)
Tim Peters2a799bf2002-12-16 20:18:38 +00001335 goto Done;
1336 {
Neal Norwitz908c8712007-08-27 04:58:38 +00001337 PyObject *format;
Tim Peters2a799bf2002-12-16 20:18:38 +00001338 PyObject *time = PyImport_ImportModule("time");
1339 if (time == NULL)
1340 goto Done;
Neal Norwitz908c8712007-08-27 04:58:38 +00001341 format = PyUnicode_FromString(PyBytes_AS_STRING(newfmt));
1342 if (format != NULL) {
1343 result = PyObject_CallMethod(time, "strftime", "OO",
1344 format, timetuple);
1345 Py_DECREF(format);
1346 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001347 Py_DECREF(time);
1348 }
1349 Done:
1350 Py_XDECREF(zreplacement);
1351 Py_XDECREF(Zreplacement);
1352 Py_XDECREF(newfmt);
1353 return result;
1354}
1355
Tim Peters2a799bf2002-12-16 20:18:38 +00001356/* ---------------------------------------------------------------------------
1357 * Wrap functions from the time module. These aren't directly available
1358 * from C. Perhaps they should be.
1359 */
1360
1361/* Call time.time() and return its result (a Python float). */
1362static PyObject *
Guido van Rossumbd43e912002-12-16 20:34:55 +00001363time_time(void)
Tim Peters2a799bf2002-12-16 20:18:38 +00001364{
1365 PyObject *result = NULL;
1366 PyObject *time = PyImport_ImportModule("time");
1367
1368 if (time != NULL) {
1369 result = PyObject_CallMethod(time, "time", "()");
1370 Py_DECREF(time);
1371 }
1372 return result;
1373}
1374
1375/* Build a time.struct_time. The weekday and day number are automatically
1376 * computed from the y,m,d args.
1377 */
1378static PyObject *
1379build_struct_time(int y, int m, int d, int hh, int mm, int ss, int dstflag)
1380{
1381 PyObject *time;
1382 PyObject *result = NULL;
1383
1384 time = PyImport_ImportModule("time");
1385 if (time != NULL) {
1386 result = PyObject_CallMethod(time, "struct_time",
1387 "((iiiiiiiii))",
1388 y, m, d,
1389 hh, mm, ss,
1390 weekday(y, m, d),
1391 days_before_month(y, m) + d,
1392 dstflag);
1393 Py_DECREF(time);
1394 }
1395 return result;
1396}
1397
1398/* ---------------------------------------------------------------------------
1399 * Miscellaneous helpers.
1400 */
1401
Guido van Rossum19960592006-08-24 17:29:38 +00001402/* For various reasons, we need to use tp_richcompare instead of tp_compare.
Tim Peters2a799bf2002-12-16 20:18:38 +00001403 * The comparisons here all most naturally compute a cmp()-like result.
1404 * This little helper turns that into a bool result for rich comparisons.
1405 */
1406static PyObject *
1407diff_to_bool(int diff, int op)
1408{
1409 PyObject *result;
1410 int istrue;
1411
1412 switch (op) {
1413 case Py_EQ: istrue = diff == 0; break;
1414 case Py_NE: istrue = diff != 0; break;
1415 case Py_LE: istrue = diff <= 0; break;
1416 case Py_GE: istrue = diff >= 0; break;
1417 case Py_LT: istrue = diff < 0; break;
1418 case Py_GT: istrue = diff > 0; break;
1419 default:
1420 assert(! "op unknown");
1421 istrue = 0; /* To shut up compiler */
1422 }
1423 result = istrue ? Py_True : Py_False;
1424 Py_INCREF(result);
1425 return result;
1426}
1427
Tim Peters07534a62003-02-07 22:50:28 +00001428/* Raises a "can't compare" TypeError and returns NULL. */
1429static PyObject *
1430cmperror(PyObject *a, PyObject *b)
1431{
1432 PyErr_Format(PyExc_TypeError,
1433 "can't compare %s to %s",
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001434 Py_Type(a)->tp_name, Py_Type(b)->tp_name);
Tim Peters07534a62003-02-07 22:50:28 +00001435 return NULL;
1436}
1437
Tim Peters2a799bf2002-12-16 20:18:38 +00001438/* ---------------------------------------------------------------------------
Tim Peters2a799bf2002-12-16 20:18:38 +00001439 * Cached Python objects; these are set by the module init function.
1440 */
1441
1442/* Conversion factors. */
1443static PyObject *us_per_us = NULL; /* 1 */
1444static PyObject *us_per_ms = NULL; /* 1000 */
1445static PyObject *us_per_second = NULL; /* 1000000 */
1446static PyObject *us_per_minute = NULL; /* 1e6 * 60 as Python int */
1447static PyObject *us_per_hour = NULL; /* 1e6 * 3600 as Python long */
1448static PyObject *us_per_day = NULL; /* 1e6 * 3600 * 24 as Python long */
1449static PyObject *us_per_week = NULL; /* 1e6*3600*24*7 as Python long */
1450static PyObject *seconds_per_day = NULL; /* 3600*24 as Python int */
1451
Tim Peters2a799bf2002-12-16 20:18:38 +00001452/* ---------------------------------------------------------------------------
1453 * Class implementations.
1454 */
1455
1456/*
1457 * PyDateTime_Delta implementation.
1458 */
1459
1460/* Convert a timedelta to a number of us,
1461 * (24*3600*self.days + self.seconds)*1000000 + self.microseconds
1462 * as a Python int or long.
1463 * Doing mixed-radix arithmetic by hand instead is excruciating in C,
1464 * due to ubiquitous overflow possibilities.
1465 */
1466static PyObject *
1467delta_to_microseconds(PyDateTime_Delta *self)
1468{
1469 PyObject *x1 = NULL;
1470 PyObject *x2 = NULL;
1471 PyObject *x3 = NULL;
1472 PyObject *result = NULL;
1473
1474 x1 = PyInt_FromLong(GET_TD_DAYS(self));
1475 if (x1 == NULL)
1476 goto Done;
1477 x2 = PyNumber_Multiply(x1, seconds_per_day); /* days in seconds */
1478 if (x2 == NULL)
1479 goto Done;
1480 Py_DECREF(x1);
1481 x1 = NULL;
1482
1483 /* x2 has days in seconds */
1484 x1 = PyInt_FromLong(GET_TD_SECONDS(self)); /* seconds */
1485 if (x1 == NULL)
1486 goto Done;
1487 x3 = PyNumber_Add(x1, x2); /* days and seconds in seconds */
1488 if (x3 == NULL)
1489 goto Done;
1490 Py_DECREF(x1);
1491 Py_DECREF(x2);
1492 x1 = x2 = NULL;
1493
1494 /* x3 has days+seconds in seconds */
1495 x1 = PyNumber_Multiply(x3, us_per_second); /* us */
1496 if (x1 == NULL)
1497 goto Done;
1498 Py_DECREF(x3);
1499 x3 = NULL;
1500
1501 /* x1 has days+seconds in us */
1502 x2 = PyInt_FromLong(GET_TD_MICROSECONDS(self));
1503 if (x2 == NULL)
1504 goto Done;
1505 result = PyNumber_Add(x1, x2);
1506
1507Done:
1508 Py_XDECREF(x1);
1509 Py_XDECREF(x2);
1510 Py_XDECREF(x3);
1511 return result;
1512}
1513
1514/* Convert a number of us (as a Python int or long) to a timedelta.
1515 */
1516static PyObject *
Tim Petersb0c854d2003-05-17 15:57:00 +00001517microseconds_to_delta_ex(PyObject *pyus, PyTypeObject *type)
Tim Peters2a799bf2002-12-16 20:18:38 +00001518{
1519 int us;
1520 int s;
1521 int d;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001522 long temp;
Tim Peters2a799bf2002-12-16 20:18:38 +00001523
1524 PyObject *tuple = NULL;
1525 PyObject *num = NULL;
1526 PyObject *result = NULL;
1527
1528 tuple = PyNumber_Divmod(pyus, us_per_second);
1529 if (tuple == NULL)
1530 goto Done;
1531
1532 num = PyTuple_GetItem(tuple, 1); /* us */
1533 if (num == NULL)
1534 goto Done;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001535 temp = PyLong_AsLong(num);
Tim Peters2a799bf2002-12-16 20:18:38 +00001536 num = NULL;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001537 if (temp == -1 && PyErr_Occurred())
1538 goto Done;
1539 assert(0 <= temp && temp < 1000000);
1540 us = (int)temp;
Tim Peters2a799bf2002-12-16 20:18:38 +00001541 if (us < 0) {
1542 /* The divisor was positive, so this must be an error. */
1543 assert(PyErr_Occurred());
1544 goto Done;
1545 }
1546
1547 num = PyTuple_GetItem(tuple, 0); /* leftover seconds */
1548 if (num == NULL)
1549 goto Done;
1550 Py_INCREF(num);
1551 Py_DECREF(tuple);
1552
1553 tuple = PyNumber_Divmod(num, seconds_per_day);
1554 if (tuple == NULL)
1555 goto Done;
1556 Py_DECREF(num);
1557
1558 num = PyTuple_GetItem(tuple, 1); /* seconds */
1559 if (num == NULL)
1560 goto Done;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001561 temp = PyLong_AsLong(num);
Tim Peters2a799bf2002-12-16 20:18:38 +00001562 num = NULL;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001563 if (temp == -1 && PyErr_Occurred())
1564 goto Done;
1565 assert(0 <= temp && temp < 24*3600);
1566 s = (int)temp;
1567
Tim Peters2a799bf2002-12-16 20:18:38 +00001568 if (s < 0) {
1569 /* The divisor was positive, so this must be an error. */
1570 assert(PyErr_Occurred());
1571 goto Done;
1572 }
1573
1574 num = PyTuple_GetItem(tuple, 0); /* leftover days */
1575 if (num == NULL)
1576 goto Done;
1577 Py_INCREF(num);
Tim Peters0b0f41c2002-12-19 01:44:38 +00001578 temp = PyLong_AsLong(num);
1579 if (temp == -1 && PyErr_Occurred())
Tim Peters2a799bf2002-12-16 20:18:38 +00001580 goto Done;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001581 d = (int)temp;
1582 if ((long)d != temp) {
1583 PyErr_SetString(PyExc_OverflowError, "normalized days too "
1584 "large to fit in a C int");
1585 goto Done;
1586 }
Tim Petersb0c854d2003-05-17 15:57:00 +00001587 result = new_delta_ex(d, s, us, 0, type);
Tim Peters2a799bf2002-12-16 20:18:38 +00001588
1589Done:
1590 Py_XDECREF(tuple);
1591 Py_XDECREF(num);
1592 return result;
1593}
1594
Tim Petersb0c854d2003-05-17 15:57:00 +00001595#define microseconds_to_delta(pymicros) \
1596 microseconds_to_delta_ex(pymicros, &PyDateTime_DeltaType)
1597
Tim Peters2a799bf2002-12-16 20:18:38 +00001598static PyObject *
1599multiply_int_timedelta(PyObject *intobj, PyDateTime_Delta *delta)
1600{
1601 PyObject *pyus_in;
1602 PyObject *pyus_out;
1603 PyObject *result;
1604
1605 pyus_in = delta_to_microseconds(delta);
1606 if (pyus_in == NULL)
1607 return NULL;
1608
1609 pyus_out = PyNumber_Multiply(pyus_in, intobj);
1610 Py_DECREF(pyus_in);
1611 if (pyus_out == NULL)
1612 return NULL;
1613
1614 result = microseconds_to_delta(pyus_out);
1615 Py_DECREF(pyus_out);
1616 return result;
1617}
1618
1619static PyObject *
1620divide_timedelta_int(PyDateTime_Delta *delta, PyObject *intobj)
1621{
1622 PyObject *pyus_in;
1623 PyObject *pyus_out;
1624 PyObject *result;
1625
1626 pyus_in = delta_to_microseconds(delta);
1627 if (pyus_in == NULL)
1628 return NULL;
1629
1630 pyus_out = PyNumber_FloorDivide(pyus_in, intobj);
1631 Py_DECREF(pyus_in);
1632 if (pyus_out == NULL)
1633 return NULL;
1634
1635 result = microseconds_to_delta(pyus_out);
1636 Py_DECREF(pyus_out);
1637 return result;
1638}
1639
1640static PyObject *
1641delta_add(PyObject *left, PyObject *right)
1642{
1643 PyObject *result = Py_NotImplemented;
1644
1645 if (PyDelta_Check(left) && PyDelta_Check(right)) {
1646 /* delta + delta */
1647 /* The C-level additions can't overflow because of the
1648 * invariant bounds.
1649 */
1650 int days = GET_TD_DAYS(left) + GET_TD_DAYS(right);
1651 int seconds = GET_TD_SECONDS(left) + GET_TD_SECONDS(right);
1652 int microseconds = GET_TD_MICROSECONDS(left) +
1653 GET_TD_MICROSECONDS(right);
1654 result = new_delta(days, seconds, microseconds, 1);
1655 }
1656
1657 if (result == Py_NotImplemented)
1658 Py_INCREF(result);
1659 return result;
1660}
1661
1662static PyObject *
1663delta_negative(PyDateTime_Delta *self)
1664{
1665 return new_delta(-GET_TD_DAYS(self),
1666 -GET_TD_SECONDS(self),
1667 -GET_TD_MICROSECONDS(self),
1668 1);
1669}
1670
1671static PyObject *
1672delta_positive(PyDateTime_Delta *self)
1673{
1674 /* Could optimize this (by returning self) if this isn't a
1675 * subclass -- but who uses unary + ? Approximately nobody.
1676 */
1677 return new_delta(GET_TD_DAYS(self),
1678 GET_TD_SECONDS(self),
1679 GET_TD_MICROSECONDS(self),
1680 0);
1681}
1682
1683static PyObject *
1684delta_abs(PyDateTime_Delta *self)
1685{
1686 PyObject *result;
1687
1688 assert(GET_TD_MICROSECONDS(self) >= 0);
1689 assert(GET_TD_SECONDS(self) >= 0);
1690
1691 if (GET_TD_DAYS(self) < 0)
1692 result = delta_negative(self);
1693 else
1694 result = delta_positive(self);
1695
1696 return result;
1697}
1698
1699static PyObject *
1700delta_subtract(PyObject *left, PyObject *right)
1701{
1702 PyObject *result = Py_NotImplemented;
1703
1704 if (PyDelta_Check(left) && PyDelta_Check(right)) {
1705 /* delta - delta */
1706 PyObject *minus_right = PyNumber_Negative(right);
1707 if (minus_right) {
1708 result = delta_add(left, minus_right);
1709 Py_DECREF(minus_right);
1710 }
1711 else
1712 result = NULL;
1713 }
1714
1715 if (result == Py_NotImplemented)
1716 Py_INCREF(result);
1717 return result;
1718}
1719
Tim Peters2a799bf2002-12-16 20:18:38 +00001720static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00001721delta_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters2a799bf2002-12-16 20:18:38 +00001722{
Tim Petersaa7d8492003-02-08 03:28:59 +00001723 if (PyDelta_Check(other)) {
Guido van Rossum19960592006-08-24 17:29:38 +00001724 int diff = GET_TD_DAYS(self) - GET_TD_DAYS(other);
Tim Peters07534a62003-02-07 22:50:28 +00001725 if (diff == 0) {
1726 diff = GET_TD_SECONDS(self) - GET_TD_SECONDS(other);
1727 if (diff == 0)
1728 diff = GET_TD_MICROSECONDS(self) -
1729 GET_TD_MICROSECONDS(other);
1730 }
Guido van Rossum19960592006-08-24 17:29:38 +00001731 return diff_to_bool(diff, op);
Tim Peters2a799bf2002-12-16 20:18:38 +00001732 }
Guido van Rossum19960592006-08-24 17:29:38 +00001733 else {
1734 Py_INCREF(Py_NotImplemented);
1735 return Py_NotImplemented;
1736 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001737}
1738
1739static PyObject *delta_getstate(PyDateTime_Delta *self);
1740
1741static long
1742delta_hash(PyDateTime_Delta *self)
1743{
1744 if (self->hashcode == -1) {
1745 PyObject *temp = delta_getstate(self);
1746 if (temp != NULL) {
1747 self->hashcode = PyObject_Hash(temp);
1748 Py_DECREF(temp);
1749 }
1750 }
1751 return self->hashcode;
1752}
1753
1754static PyObject *
1755delta_multiply(PyObject *left, PyObject *right)
1756{
1757 PyObject *result = Py_NotImplemented;
1758
1759 if (PyDelta_Check(left)) {
1760 /* delta * ??? */
1761 if (PyInt_Check(right) || PyLong_Check(right))
1762 result = multiply_int_timedelta(right,
1763 (PyDateTime_Delta *) left);
1764 }
1765 else if (PyInt_Check(left) || PyLong_Check(left))
1766 result = multiply_int_timedelta(left,
1767 (PyDateTime_Delta *) right);
1768
1769 if (result == Py_NotImplemented)
1770 Py_INCREF(result);
1771 return result;
1772}
1773
1774static PyObject *
1775delta_divide(PyObject *left, PyObject *right)
1776{
1777 PyObject *result = Py_NotImplemented;
1778
1779 if (PyDelta_Check(left)) {
1780 /* delta * ??? */
1781 if (PyInt_Check(right) || PyLong_Check(right))
1782 result = divide_timedelta_int(
1783 (PyDateTime_Delta *)left,
1784 right);
1785 }
1786
1787 if (result == Py_NotImplemented)
1788 Py_INCREF(result);
1789 return result;
1790}
1791
1792/* Fold in the value of the tag ("seconds", "weeks", etc) component of a
1793 * timedelta constructor. sofar is the # of microseconds accounted for
1794 * so far, and there are factor microseconds per current unit, the number
1795 * of which is given by num. num * factor is added to sofar in a
1796 * numerically careful way, and that's the result. Any fractional
1797 * microseconds left over (this can happen if num is a float type) are
1798 * added into *leftover.
1799 * Note that there are many ways this can give an error (NULL) return.
1800 */
1801static PyObject *
1802accum(const char* tag, PyObject *sofar, PyObject *num, PyObject *factor,
1803 double *leftover)
1804{
1805 PyObject *prod;
1806 PyObject *sum;
1807
1808 assert(num != NULL);
1809
1810 if (PyInt_Check(num) || PyLong_Check(num)) {
1811 prod = PyNumber_Multiply(num, factor);
1812 if (prod == NULL)
1813 return NULL;
1814 sum = PyNumber_Add(sofar, prod);
1815 Py_DECREF(prod);
1816 return sum;
1817 }
1818
1819 if (PyFloat_Check(num)) {
1820 double dnum;
1821 double fracpart;
1822 double intpart;
1823 PyObject *x;
1824 PyObject *y;
1825
1826 /* The Plan: decompose num into an integer part and a
1827 * fractional part, num = intpart + fracpart.
1828 * Then num * factor ==
1829 * intpart * factor + fracpart * factor
1830 * and the LHS can be computed exactly in long arithmetic.
1831 * The RHS is again broken into an int part and frac part.
1832 * and the frac part is added into *leftover.
1833 */
1834 dnum = PyFloat_AsDouble(num);
1835 if (dnum == -1.0 && PyErr_Occurred())
1836 return NULL;
1837 fracpart = modf(dnum, &intpart);
1838 x = PyLong_FromDouble(intpart);
1839 if (x == NULL)
1840 return NULL;
1841
1842 prod = PyNumber_Multiply(x, factor);
1843 Py_DECREF(x);
1844 if (prod == NULL)
1845 return NULL;
1846
1847 sum = PyNumber_Add(sofar, prod);
1848 Py_DECREF(prod);
1849 if (sum == NULL)
1850 return NULL;
1851
1852 if (fracpart == 0.0)
1853 return sum;
1854 /* So far we've lost no information. Dealing with the
1855 * fractional part requires float arithmetic, and may
1856 * lose a little info.
1857 */
1858 assert(PyInt_Check(factor) || PyLong_Check(factor));
Guido van Rossumddefaf32007-01-14 03:31:43 +00001859 dnum = PyLong_AsDouble(factor);
Tim Peters2a799bf2002-12-16 20:18:38 +00001860
1861 dnum *= fracpart;
1862 fracpart = modf(dnum, &intpart);
1863 x = PyLong_FromDouble(intpart);
1864 if (x == NULL) {
1865 Py_DECREF(sum);
1866 return NULL;
1867 }
1868
1869 y = PyNumber_Add(sum, x);
1870 Py_DECREF(sum);
1871 Py_DECREF(x);
1872 *leftover += fracpart;
1873 return y;
1874 }
1875
1876 PyErr_Format(PyExc_TypeError,
1877 "unsupported type for timedelta %s component: %s",
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001878 tag, Py_Type(num)->tp_name);
Tim Peters2a799bf2002-12-16 20:18:38 +00001879 return NULL;
1880}
1881
1882static PyObject *
1883delta_new(PyTypeObject *type, PyObject *args, PyObject *kw)
1884{
1885 PyObject *self = NULL;
1886
1887 /* Argument objects. */
1888 PyObject *day = NULL;
1889 PyObject *second = NULL;
1890 PyObject *us = NULL;
1891 PyObject *ms = NULL;
1892 PyObject *minute = NULL;
1893 PyObject *hour = NULL;
1894 PyObject *week = NULL;
1895
1896 PyObject *x = NULL; /* running sum of microseconds */
1897 PyObject *y = NULL; /* temp sum of microseconds */
1898 double leftover_us = 0.0;
1899
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00001900 static char *keywords[] = {
Tim Peters2a799bf2002-12-16 20:18:38 +00001901 "days", "seconds", "microseconds", "milliseconds",
1902 "minutes", "hours", "weeks", NULL
1903 };
1904
1905 if (PyArg_ParseTupleAndKeywords(args, kw, "|OOOOOOO:__new__",
1906 keywords,
1907 &day, &second, &us,
1908 &ms, &minute, &hour, &week) == 0)
1909 goto Done;
1910
1911 x = PyInt_FromLong(0);
1912 if (x == NULL)
1913 goto Done;
1914
1915#define CLEANUP \
1916 Py_DECREF(x); \
1917 x = y; \
1918 if (x == NULL) \
1919 goto Done
1920
1921 if (us) {
1922 y = accum("microseconds", x, us, us_per_us, &leftover_us);
1923 CLEANUP;
1924 }
1925 if (ms) {
1926 y = accum("milliseconds", x, ms, us_per_ms, &leftover_us);
1927 CLEANUP;
1928 }
1929 if (second) {
1930 y = accum("seconds", x, second, us_per_second, &leftover_us);
1931 CLEANUP;
1932 }
1933 if (minute) {
1934 y = accum("minutes", x, minute, us_per_minute, &leftover_us);
1935 CLEANUP;
1936 }
1937 if (hour) {
1938 y = accum("hours", x, hour, us_per_hour, &leftover_us);
1939 CLEANUP;
1940 }
1941 if (day) {
1942 y = accum("days", x, day, us_per_day, &leftover_us);
1943 CLEANUP;
1944 }
1945 if (week) {
1946 y = accum("weeks", x, week, us_per_week, &leftover_us);
1947 CLEANUP;
1948 }
1949 if (leftover_us) {
1950 /* Round to nearest whole # of us, and add into x. */
Tim Peters5d644dd2003-01-02 16:32:54 +00001951 PyObject *temp = PyLong_FromLong(round_to_long(leftover_us));
Tim Peters2a799bf2002-12-16 20:18:38 +00001952 if (temp == NULL) {
1953 Py_DECREF(x);
1954 goto Done;
1955 }
1956 y = PyNumber_Add(x, temp);
1957 Py_DECREF(temp);
1958 CLEANUP;
1959 }
1960
Tim Petersb0c854d2003-05-17 15:57:00 +00001961 self = microseconds_to_delta_ex(x, type);
Tim Peters2a799bf2002-12-16 20:18:38 +00001962 Py_DECREF(x);
1963Done:
1964 return self;
1965
1966#undef CLEANUP
1967}
1968
1969static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00001970delta_bool(PyDateTime_Delta *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00001971{
1972 return (GET_TD_DAYS(self) != 0
1973 || GET_TD_SECONDS(self) != 0
1974 || GET_TD_MICROSECONDS(self) != 0);
1975}
1976
1977static PyObject *
1978delta_repr(PyDateTime_Delta *self)
1979{
1980 if (GET_TD_MICROSECONDS(self) != 0)
Walter Dörwald1ab83302007-05-18 17:15:44 +00001981 return PyUnicode_FromFormat("%s(%d, %d, %d)",
Martin v. Löwis5d7428b2007-07-21 18:47:48 +00001982 Py_Type(self)->tp_name,
Walter Dörwald7569dfe2007-05-19 21:49:49 +00001983 GET_TD_DAYS(self),
1984 GET_TD_SECONDS(self),
1985 GET_TD_MICROSECONDS(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00001986 if (GET_TD_SECONDS(self) != 0)
Walter Dörwald1ab83302007-05-18 17:15:44 +00001987 return PyUnicode_FromFormat("%s(%d, %d)",
Martin v. Löwis5d7428b2007-07-21 18:47:48 +00001988 Py_Type(self)->tp_name,
Walter Dörwald7569dfe2007-05-19 21:49:49 +00001989 GET_TD_DAYS(self),
1990 GET_TD_SECONDS(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00001991
Walter Dörwald1ab83302007-05-18 17:15:44 +00001992 return PyUnicode_FromFormat("%s(%d)",
Martin v. Löwis5d7428b2007-07-21 18:47:48 +00001993 Py_Type(self)->tp_name,
Walter Dörwald7569dfe2007-05-19 21:49:49 +00001994 GET_TD_DAYS(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00001995}
1996
1997static PyObject *
1998delta_str(PyDateTime_Delta *self)
1999{
Tim Peters2a799bf2002-12-16 20:18:38 +00002000 int us = GET_TD_MICROSECONDS(self);
Walter Dörwaldbaf853c2007-05-31 18:42:47 +00002001 int seconds = GET_TD_SECONDS(self);
2002 int minutes = divmod(seconds, 60, &seconds);
2003 int hours = divmod(minutes, 60, &minutes);
2004 int days = GET_TD_DAYS(self);
Tim Peters2a799bf2002-12-16 20:18:38 +00002005
2006 if (days) {
Walter Dörwaldbaf853c2007-05-31 18:42:47 +00002007 if (us)
2008 return PyUnicode_FromFormat("%d day%s, %d:%02d:%02d.%06d",
2009 days, (days == 1 || days == -1) ? "" : "s",
2010 hours, minutes, seconds, us);
2011 else
2012 return PyUnicode_FromFormat("%d day%s, %d:%02d:%02d",
2013 days, (days == 1 || days == -1) ? "" : "s",
2014 hours, minutes, seconds);
2015 } else {
2016 if (us)
2017 return PyUnicode_FromFormat("%d:%02d:%02d.%06d",
2018 hours, minutes, seconds, us);
2019 else
2020 return PyUnicode_FromFormat("%d:%02d:%02d",
2021 hours, minutes, seconds);
Tim Peters2a799bf2002-12-16 20:18:38 +00002022 }
2023
Tim Peters2a799bf2002-12-16 20:18:38 +00002024}
2025
Tim Peters371935f2003-02-01 01:52:50 +00002026/* Pickle support, a simple use of __reduce__. */
2027
Tim Petersb57f8f02003-02-01 02:54:15 +00002028/* __getstate__ isn't exposed */
Tim Peters2a799bf2002-12-16 20:18:38 +00002029static PyObject *
2030delta_getstate(PyDateTime_Delta *self)
2031{
2032 return Py_BuildValue("iii", GET_TD_DAYS(self),
2033 GET_TD_SECONDS(self),
2034 GET_TD_MICROSECONDS(self));
2035}
2036
Tim Peters2a799bf2002-12-16 20:18:38 +00002037static PyObject *
2038delta_reduce(PyDateTime_Delta* self)
2039{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002040 return Py_BuildValue("ON", Py_Type(self), delta_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002041}
2042
2043#define OFFSET(field) offsetof(PyDateTime_Delta, field)
2044
2045static PyMemberDef delta_members[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002046
Neal Norwitzdfb80862002-12-19 02:30:56 +00002047 {"days", T_INT, OFFSET(days), READONLY,
Tim Peters2a799bf2002-12-16 20:18:38 +00002048 PyDoc_STR("Number of days.")},
2049
Neal Norwitzdfb80862002-12-19 02:30:56 +00002050 {"seconds", T_INT, OFFSET(seconds), READONLY,
Tim Peters2a799bf2002-12-16 20:18:38 +00002051 PyDoc_STR("Number of seconds (>= 0 and less than 1 day).")},
2052
Neal Norwitzdfb80862002-12-19 02:30:56 +00002053 {"microseconds", T_INT, OFFSET(microseconds), READONLY,
Tim Peters2a799bf2002-12-16 20:18:38 +00002054 PyDoc_STR("Number of microseconds (>= 0 and less than 1 second).")},
2055 {NULL}
2056};
2057
2058static PyMethodDef delta_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002059 {"__reduce__", (PyCFunction)delta_reduce, METH_NOARGS,
2060 PyDoc_STR("__reduce__() -> (cls, state)")},
2061
Tim Peters2a799bf2002-12-16 20:18:38 +00002062 {NULL, NULL},
2063};
2064
2065static char delta_doc[] =
2066PyDoc_STR("Difference between two datetime values.");
2067
2068static PyNumberMethods delta_as_number = {
2069 delta_add, /* nb_add */
2070 delta_subtract, /* nb_subtract */
2071 delta_multiply, /* nb_multiply */
Tim Peters2a799bf2002-12-16 20:18:38 +00002072 0, /* nb_remainder */
2073 0, /* nb_divmod */
2074 0, /* nb_power */
2075 (unaryfunc)delta_negative, /* nb_negative */
2076 (unaryfunc)delta_positive, /* nb_positive */
2077 (unaryfunc)delta_abs, /* nb_absolute */
Jack Diederich4dafcc42006-11-28 19:15:13 +00002078 (inquiry)delta_bool, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00002079 0, /*nb_invert*/
2080 0, /*nb_lshift*/
2081 0, /*nb_rshift*/
2082 0, /*nb_and*/
2083 0, /*nb_xor*/
2084 0, /*nb_or*/
2085 0, /*nb_coerce*/
2086 0, /*nb_int*/
2087 0, /*nb_long*/
2088 0, /*nb_float*/
2089 0, /*nb_oct*/
2090 0, /*nb_hex*/
2091 0, /*nb_inplace_add*/
2092 0, /*nb_inplace_subtract*/
2093 0, /*nb_inplace_multiply*/
Tim Peters2a799bf2002-12-16 20:18:38 +00002094 0, /*nb_inplace_remainder*/
2095 0, /*nb_inplace_power*/
2096 0, /*nb_inplace_lshift*/
2097 0, /*nb_inplace_rshift*/
2098 0, /*nb_inplace_and*/
2099 0, /*nb_inplace_xor*/
2100 0, /*nb_inplace_or*/
2101 delta_divide, /* nb_floor_divide */
2102 0, /* nb_true_divide */
2103 0, /* nb_inplace_floor_divide */
2104 0, /* nb_inplace_true_divide */
2105};
2106
2107static PyTypeObject PyDateTime_DeltaType = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002108 PyVarObject_HEAD_INIT(NULL, 0)
Tim Peters2a799bf2002-12-16 20:18:38 +00002109 "datetime.timedelta", /* tp_name */
2110 sizeof(PyDateTime_Delta), /* tp_basicsize */
2111 0, /* tp_itemsize */
2112 0, /* tp_dealloc */
2113 0, /* tp_print */
2114 0, /* tp_getattr */
2115 0, /* tp_setattr */
2116 0, /* tp_compare */
2117 (reprfunc)delta_repr, /* tp_repr */
2118 &delta_as_number, /* tp_as_number */
2119 0, /* tp_as_sequence */
2120 0, /* tp_as_mapping */
2121 (hashfunc)delta_hash, /* tp_hash */
2122 0, /* tp_call */
2123 (reprfunc)delta_str, /* tp_str */
2124 PyObject_GenericGetAttr, /* tp_getattro */
2125 0, /* tp_setattro */
2126 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00002127 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters2a799bf2002-12-16 20:18:38 +00002128 delta_doc, /* tp_doc */
2129 0, /* tp_traverse */
2130 0, /* tp_clear */
Guido van Rossum19960592006-08-24 17:29:38 +00002131 delta_richcompare, /* tp_richcompare */
Tim Peters2a799bf2002-12-16 20:18:38 +00002132 0, /* tp_weaklistoffset */
2133 0, /* tp_iter */
2134 0, /* tp_iternext */
2135 delta_methods, /* tp_methods */
2136 delta_members, /* tp_members */
2137 0, /* tp_getset */
2138 0, /* tp_base */
2139 0, /* tp_dict */
2140 0, /* tp_descr_get */
2141 0, /* tp_descr_set */
2142 0, /* tp_dictoffset */
2143 0, /* tp_init */
2144 0, /* tp_alloc */
2145 delta_new, /* tp_new */
Tim Peters4c530132003-05-16 22:44:06 +00002146 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00002147};
2148
2149/*
2150 * PyDateTime_Date implementation.
2151 */
2152
2153/* Accessor properties. */
2154
2155static PyObject *
2156date_year(PyDateTime_Date *self, void *unused)
2157{
2158 return PyInt_FromLong(GET_YEAR(self));
2159}
2160
2161static PyObject *
2162date_month(PyDateTime_Date *self, void *unused)
2163{
2164 return PyInt_FromLong(GET_MONTH(self));
2165}
2166
2167static PyObject *
2168date_day(PyDateTime_Date *self, void *unused)
2169{
2170 return PyInt_FromLong(GET_DAY(self));
2171}
2172
2173static PyGetSetDef date_getset[] = {
2174 {"year", (getter)date_year},
2175 {"month", (getter)date_month},
2176 {"day", (getter)date_day},
2177 {NULL}
2178};
2179
2180/* Constructors. */
2181
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00002182static char *date_kws[] = {"year", "month", "day", NULL};
Tim Peters12bf3392002-12-24 05:41:27 +00002183
Tim Peters2a799bf2002-12-16 20:18:38 +00002184static PyObject *
2185date_new(PyTypeObject *type, PyObject *args, PyObject *kw)
2186{
2187 PyObject *self = NULL;
Tim Peters70533e22003-02-01 04:40:04 +00002188 PyObject *state;
Tim Peters2a799bf2002-12-16 20:18:38 +00002189 int year;
2190 int month;
2191 int day;
2192
Guido van Rossum177e41a2003-01-30 22:06:23 +00002193 /* Check for invocation from pickle with __getstate__ state */
2194 if (PyTuple_GET_SIZE(args) == 1 &&
Martin v. Löwis10a60b32007-07-18 02:28:27 +00002195 PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) &&
2196 PyBytes_GET_SIZE(state) == _PyDateTime_DATE_DATASIZE &&
2197 MONTH_IS_SANE(PyBytes_AS_STRING(state)[2]))
Guido van Rossum177e41a2003-01-30 22:06:23 +00002198 {
Tim Peters70533e22003-02-01 04:40:04 +00002199 PyDateTime_Date *me;
2200
Tim Peters604c0132004-06-07 23:04:33 +00002201 me = (PyDateTime_Date *) (type->tp_alloc(type, 0));
Tim Peters70533e22003-02-01 04:40:04 +00002202 if (me != NULL) {
Martin v. Löwis10a60b32007-07-18 02:28:27 +00002203 char *pdata = PyBytes_AS_STRING(state);
Tim Peters70533e22003-02-01 04:40:04 +00002204 memcpy(me->data, pdata, _PyDateTime_DATE_DATASIZE);
2205 me->hashcode = -1;
Guido van Rossum177e41a2003-01-30 22:06:23 +00002206 }
Tim Peters70533e22003-02-01 04:40:04 +00002207 return (PyObject *)me;
Guido van Rossum177e41a2003-01-30 22:06:23 +00002208 }
2209
Tim Peters12bf3392002-12-24 05:41:27 +00002210 if (PyArg_ParseTupleAndKeywords(args, kw, "iii", date_kws,
Tim Peters2a799bf2002-12-16 20:18:38 +00002211 &year, &month, &day)) {
2212 if (check_date_args(year, month, day) < 0)
2213 return NULL;
Guido van Rossum8b7a9a32003-04-14 22:01:58 +00002214 self = new_date_ex(year, month, day, type);
Tim Peters2a799bf2002-12-16 20:18:38 +00002215 }
2216 return self;
2217}
2218
2219/* Return new date from localtime(t). */
2220static PyObject *
Tim Peters1b6f7a92004-06-20 02:50:16 +00002221date_local_from_time_t(PyObject *cls, double ts)
Tim Peters2a799bf2002-12-16 20:18:38 +00002222{
2223 struct tm *tm;
Tim Peters1b6f7a92004-06-20 02:50:16 +00002224 time_t t;
Tim Peters2a799bf2002-12-16 20:18:38 +00002225 PyObject *result = NULL;
2226
Tim Peters1b6f7a92004-06-20 02:50:16 +00002227 t = _PyTime_DoubleToTimet(ts);
2228 if (t == (time_t)-1 && PyErr_Occurred())
2229 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002230 tm = localtime(&t);
2231 if (tm)
2232 result = PyObject_CallFunction(cls, "iii",
2233 tm->tm_year + 1900,
2234 tm->tm_mon + 1,
2235 tm->tm_mday);
2236 else
2237 PyErr_SetString(PyExc_ValueError,
2238 "timestamp out of range for "
2239 "platform localtime() function");
2240 return result;
2241}
2242
2243/* Return new date from current time.
2244 * We say this is equivalent to fromtimestamp(time.time()), and the
2245 * only way to be sure of that is to *call* time.time(). That's not
2246 * generally the same as calling C's time.
2247 */
2248static PyObject *
2249date_today(PyObject *cls, PyObject *dummy)
2250{
2251 PyObject *time;
2252 PyObject *result;
2253
2254 time = time_time();
2255 if (time == NULL)
2256 return NULL;
2257
2258 /* Note well: today() is a class method, so this may not call
2259 * date.fromtimestamp. For example, it may call
2260 * datetime.fromtimestamp. That's why we need all the accuracy
2261 * time.time() delivers; if someone were gonzo about optimization,
2262 * date.today() could get away with plain C time().
2263 */
2264 result = PyObject_CallMethod(cls, "fromtimestamp", "O", time);
2265 Py_DECREF(time);
2266 return result;
2267}
2268
2269/* Return new date from given timestamp (Python timestamp -- a double). */
2270static PyObject *
2271date_fromtimestamp(PyObject *cls, PyObject *args)
2272{
2273 double timestamp;
2274 PyObject *result = NULL;
2275
2276 if (PyArg_ParseTuple(args, "d:fromtimestamp", &timestamp))
Tim Peters1b6f7a92004-06-20 02:50:16 +00002277 result = date_local_from_time_t(cls, timestamp);
Tim Peters2a799bf2002-12-16 20:18:38 +00002278 return result;
2279}
2280
2281/* Return new date from proleptic Gregorian ordinal. Raises ValueError if
2282 * the ordinal is out of range.
2283 */
2284static PyObject *
2285date_fromordinal(PyObject *cls, PyObject *args)
2286{
2287 PyObject *result = NULL;
2288 int ordinal;
2289
2290 if (PyArg_ParseTuple(args, "i:fromordinal", &ordinal)) {
2291 int year;
2292 int month;
2293 int day;
2294
2295 if (ordinal < 1)
2296 PyErr_SetString(PyExc_ValueError, "ordinal must be "
2297 ">= 1");
2298 else {
2299 ord_to_ymd(ordinal, &year, &month, &day);
2300 result = PyObject_CallFunction(cls, "iii",
2301 year, month, day);
2302 }
2303 }
2304 return result;
2305}
2306
2307/*
2308 * Date arithmetic.
2309 */
2310
2311/* date + timedelta -> date. If arg negate is true, subtract the timedelta
2312 * instead.
2313 */
2314static PyObject *
2315add_date_timedelta(PyDateTime_Date *date, PyDateTime_Delta *delta, int negate)
2316{
2317 PyObject *result = NULL;
2318 int year = GET_YEAR(date);
2319 int month = GET_MONTH(date);
2320 int deltadays = GET_TD_DAYS(delta);
2321 /* C-level overflow is impossible because |deltadays| < 1e9. */
2322 int day = GET_DAY(date) + (negate ? -deltadays : deltadays);
2323
2324 if (normalize_date(&year, &month, &day) >= 0)
2325 result = new_date(year, month, day);
2326 return result;
2327}
2328
2329static PyObject *
2330date_add(PyObject *left, PyObject *right)
2331{
2332 if (PyDateTime_Check(left) || PyDateTime_Check(right)) {
2333 Py_INCREF(Py_NotImplemented);
2334 return Py_NotImplemented;
2335 }
Tim Petersaa7d8492003-02-08 03:28:59 +00002336 if (PyDate_Check(left)) {
Tim Peters2a799bf2002-12-16 20:18:38 +00002337 /* date + ??? */
2338 if (PyDelta_Check(right))
2339 /* date + delta */
2340 return add_date_timedelta((PyDateTime_Date *) left,
2341 (PyDateTime_Delta *) right,
2342 0);
2343 }
2344 else {
2345 /* ??? + date
2346 * 'right' must be one of us, or we wouldn't have been called
2347 */
2348 if (PyDelta_Check(left))
2349 /* delta + date */
2350 return add_date_timedelta((PyDateTime_Date *) right,
2351 (PyDateTime_Delta *) left,
2352 0);
2353 }
2354 Py_INCREF(Py_NotImplemented);
2355 return Py_NotImplemented;
2356}
2357
2358static PyObject *
2359date_subtract(PyObject *left, PyObject *right)
2360{
2361 if (PyDateTime_Check(left) || PyDateTime_Check(right)) {
2362 Py_INCREF(Py_NotImplemented);
2363 return Py_NotImplemented;
2364 }
Tim Petersaa7d8492003-02-08 03:28:59 +00002365 if (PyDate_Check(left)) {
2366 if (PyDate_Check(right)) {
Tim Peters2a799bf2002-12-16 20:18:38 +00002367 /* date - date */
2368 int left_ord = ymd_to_ord(GET_YEAR(left),
2369 GET_MONTH(left),
2370 GET_DAY(left));
2371 int right_ord = ymd_to_ord(GET_YEAR(right),
2372 GET_MONTH(right),
2373 GET_DAY(right));
2374 return new_delta(left_ord - right_ord, 0, 0, 0);
2375 }
2376 if (PyDelta_Check(right)) {
2377 /* date - delta */
2378 return add_date_timedelta((PyDateTime_Date *) left,
2379 (PyDateTime_Delta *) right,
2380 1);
2381 }
2382 }
2383 Py_INCREF(Py_NotImplemented);
2384 return Py_NotImplemented;
2385}
2386
2387
2388/* Various ways to turn a date into a string. */
2389
2390static PyObject *
2391date_repr(PyDateTime_Date *self)
2392{
Walter Dörwald7569dfe2007-05-19 21:49:49 +00002393 return PyUnicode_FromFormat("%s(%d, %d, %d)",
Martin v. Löwis5d7428b2007-07-21 18:47:48 +00002394 Py_Type(self)->tp_name,
Walter Dörwald7569dfe2007-05-19 21:49:49 +00002395 GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002396}
2397
2398static PyObject *
2399date_isoformat(PyDateTime_Date *self)
2400{
Walter Dörwaldbafa1372007-05-31 17:50:48 +00002401 return PyUnicode_FromFormat("%04d-%02d-%02d",
2402 GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002403}
2404
Tim Peterse2df5ff2003-05-02 18:39:55 +00002405/* str() calls the appropriate isoformat() method. */
Tim Peters2a799bf2002-12-16 20:18:38 +00002406static PyObject *
2407date_str(PyDateTime_Date *self)
2408{
2409 return PyObject_CallMethod((PyObject *)self, "isoformat", "()");
2410}
2411
2412
2413static PyObject *
2414date_ctime(PyDateTime_Date *self)
2415{
2416 return format_ctime(self, 0, 0, 0);
2417}
2418
2419static PyObject *
2420date_strftime(PyDateTime_Date *self, PyObject *args, PyObject *kw)
2421{
2422 /* This method can be inherited, and needs to call the
2423 * timetuple() method appropriate to self's class.
2424 */
2425 PyObject *result;
2426 PyObject *format;
2427 PyObject *tuple;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00002428 static char *keywords[] = {"format", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00002429
Guido van Rossumfd53fd62007-08-24 04:05:13 +00002430 if (! PyArg_ParseTupleAndKeywords(args, kw, "U:strftime", keywords,
Guido van Rossumbce56a62007-05-10 18:04:33 +00002431 &format))
Tim Peters2a799bf2002-12-16 20:18:38 +00002432 return NULL;
2433
2434 tuple = PyObject_CallMethod((PyObject *)self, "timetuple", "()");
2435 if (tuple == NULL)
2436 return NULL;
Tim Petersbad8ff02002-12-30 20:52:32 +00002437 result = wrap_strftime((PyObject *)self, format, tuple,
2438 (PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00002439 Py_DECREF(tuple);
2440 return result;
2441}
2442
2443/* ISO methods. */
2444
2445static PyObject *
2446date_isoweekday(PyDateTime_Date *self)
2447{
2448 int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
2449
2450 return PyInt_FromLong(dow + 1);
2451}
2452
2453static PyObject *
2454date_isocalendar(PyDateTime_Date *self)
2455{
2456 int year = GET_YEAR(self);
2457 int week1_monday = iso_week1_monday(year);
2458 int today = ymd_to_ord(year, GET_MONTH(self), GET_DAY(self));
2459 int week;
2460 int day;
2461
2462 week = divmod(today - week1_monday, 7, &day);
2463 if (week < 0) {
2464 --year;
2465 week1_monday = iso_week1_monday(year);
2466 week = divmod(today - week1_monday, 7, &day);
2467 }
2468 else if (week >= 52 && today >= iso_week1_monday(year + 1)) {
2469 ++year;
2470 week = 0;
2471 }
2472 return Py_BuildValue("iii", year, week + 1, day + 1);
2473}
2474
2475/* Miscellaneous methods. */
2476
Tim Peters2a799bf2002-12-16 20:18:38 +00002477static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00002478date_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters2a799bf2002-12-16 20:18:38 +00002479{
Guido van Rossum19960592006-08-24 17:29:38 +00002480 if (PyDate_Check(other)) {
2481 int diff = memcmp(((PyDateTime_Date *)self)->data,
2482 ((PyDateTime_Date *)other)->data,
2483 _PyDateTime_DATE_DATASIZE);
2484 return diff_to_bool(diff, op);
2485 }
2486 else {
Tim Peters07534a62003-02-07 22:50:28 +00002487 Py_INCREF(Py_NotImplemented);
2488 return Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00002489 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002490}
2491
2492static PyObject *
2493date_timetuple(PyDateTime_Date *self)
2494{
2495 return build_struct_time(GET_YEAR(self),
2496 GET_MONTH(self),
2497 GET_DAY(self),
2498 0, 0, 0, -1);
2499}
2500
Tim Peters12bf3392002-12-24 05:41:27 +00002501static PyObject *
2502date_replace(PyDateTime_Date *self, PyObject *args, PyObject *kw)
2503{
2504 PyObject *clone;
2505 PyObject *tuple;
2506 int year = GET_YEAR(self);
2507 int month = GET_MONTH(self);
2508 int day = GET_DAY(self);
2509
2510 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iii:replace", date_kws,
2511 &year, &month, &day))
2512 return NULL;
2513 tuple = Py_BuildValue("iii", year, month, day);
2514 if (tuple == NULL)
2515 return NULL;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002516 clone = date_new(Py_Type(self), tuple, NULL);
Tim Peters12bf3392002-12-24 05:41:27 +00002517 Py_DECREF(tuple);
2518 return clone;
2519}
2520
Guido van Rossumfd53fd62007-08-24 04:05:13 +00002521/*
2522 Borrowed from stringobject.c, originally it was string_hash()
2523*/
2524static long
2525generic_hash(unsigned char *data, int len)
2526{
2527 register unsigned char *p;
2528 register long x;
2529
2530 p = (unsigned char *) data;
2531 x = *p << 7;
2532 while (--len >= 0)
2533 x = (1000003*x) ^ *p++;
2534 x ^= len;
2535 if (x == -1)
2536 x = -2;
2537
2538 return x;
2539}
2540
2541
2542static PyObject *date_getstate(PyDateTime_Date *self);
Tim Peters2a799bf2002-12-16 20:18:38 +00002543
2544static long
2545date_hash(PyDateTime_Date *self)
2546{
Guido van Rossumfd53fd62007-08-24 04:05:13 +00002547 if (self->hashcode == -1)
2548 self->hashcode = generic_hash(
2549 (unsigned char *)self->data, _PyDateTime_DATE_DATASIZE);
2550
Tim Peters2a799bf2002-12-16 20:18:38 +00002551 return self->hashcode;
2552}
2553
2554static PyObject *
2555date_toordinal(PyDateTime_Date *self)
2556{
2557 return PyInt_FromLong(ymd_to_ord(GET_YEAR(self), GET_MONTH(self),
2558 GET_DAY(self)));
2559}
2560
2561static PyObject *
2562date_weekday(PyDateTime_Date *self)
2563{
2564 int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
2565
2566 return PyInt_FromLong(dow);
2567}
2568
Tim Peters371935f2003-02-01 01:52:50 +00002569/* Pickle support, a simple use of __reduce__. */
Tim Peters2a799bf2002-12-16 20:18:38 +00002570
Tim Petersb57f8f02003-02-01 02:54:15 +00002571/* __getstate__ isn't exposed */
Tim Peters2a799bf2002-12-16 20:18:38 +00002572static PyObject *
Guido van Rossumfd53fd62007-08-24 04:05:13 +00002573date_getstate(PyDateTime_Date *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00002574{
Martin v. Löwis10a60b32007-07-18 02:28:27 +00002575 PyObject* field;
Guido van Rossumfd53fd62007-08-24 04:05:13 +00002576 field = PyBytes_FromStringAndSize(
2577 (char*)self->data, _PyDateTime_DATE_DATASIZE);
Martin v. Löwis10a60b32007-07-18 02:28:27 +00002578 return Py_BuildValue("(N)", field);
Tim Peters2a799bf2002-12-16 20:18:38 +00002579}
2580
2581static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00002582date_reduce(PyDateTime_Date *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00002583{
Guido van Rossumfd53fd62007-08-24 04:05:13 +00002584 return Py_BuildValue("(ON)", Py_Type(self), date_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002585}
2586
2587static PyMethodDef date_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002588
Tim Peters2a799bf2002-12-16 20:18:38 +00002589 /* Class methods: */
Guido van Rossum177e41a2003-01-30 22:06:23 +00002590
Tim Peters2a799bf2002-12-16 20:18:38 +00002591 {"fromtimestamp", (PyCFunction)date_fromtimestamp, METH_VARARGS |
2592 METH_CLASS,
2593 PyDoc_STR("timestamp -> local date from a POSIX timestamp (like "
2594 "time.time()).")},
2595
2596 {"fromordinal", (PyCFunction)date_fromordinal, METH_VARARGS |
2597 METH_CLASS,
2598 PyDoc_STR("int -> date corresponding to a proleptic Gregorian "
2599 "ordinal.")},
2600
2601 {"today", (PyCFunction)date_today, METH_NOARGS | METH_CLASS,
2602 PyDoc_STR("Current date or datetime: same as "
2603 "self.__class__.fromtimestamp(time.time()).")},
2604
2605 /* Instance methods: */
2606
2607 {"ctime", (PyCFunction)date_ctime, METH_NOARGS,
2608 PyDoc_STR("Return ctime() style string.")},
2609
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002610 {"strftime", (PyCFunction)date_strftime, METH_VARARGS | METH_KEYWORDS,
Tim Peters2a799bf2002-12-16 20:18:38 +00002611 PyDoc_STR("format -> strftime() style string.")},
2612
2613 {"timetuple", (PyCFunction)date_timetuple, METH_NOARGS,
2614 PyDoc_STR("Return time tuple, compatible with time.localtime().")},
2615
2616 {"isocalendar", (PyCFunction)date_isocalendar, METH_NOARGS,
2617 PyDoc_STR("Return a 3-tuple containing ISO year, week number, and "
2618 "weekday.")},
2619
2620 {"isoformat", (PyCFunction)date_isoformat, METH_NOARGS,
2621 PyDoc_STR("Return string in ISO 8601 format, YYYY-MM-DD.")},
2622
2623 {"isoweekday", (PyCFunction)date_isoweekday, METH_NOARGS,
2624 PyDoc_STR("Return the day of the week represented by the date.\n"
2625 "Monday == 1 ... Sunday == 7")},
2626
2627 {"toordinal", (PyCFunction)date_toordinal, METH_NOARGS,
2628 PyDoc_STR("Return proleptic Gregorian ordinal. January 1 of year "
2629 "1 is day 1.")},
2630
2631 {"weekday", (PyCFunction)date_weekday, METH_NOARGS,
2632 PyDoc_STR("Return the day of the week represented by the date.\n"
2633 "Monday == 0 ... Sunday == 6")},
2634
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002635 {"replace", (PyCFunction)date_replace, METH_VARARGS | METH_KEYWORDS,
Tim Peters12bf3392002-12-24 05:41:27 +00002636 PyDoc_STR("Return date with new specified fields.")},
2637
Guido van Rossum177e41a2003-01-30 22:06:23 +00002638 {"__reduce__", (PyCFunction)date_reduce, METH_NOARGS,
2639 PyDoc_STR("__reduce__() -> (cls, state)")},
2640
Tim Peters2a799bf2002-12-16 20:18:38 +00002641 {NULL, NULL}
2642};
2643
2644static char date_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00002645PyDoc_STR("date(year, month, day) --> date object");
Tim Peters2a799bf2002-12-16 20:18:38 +00002646
2647static PyNumberMethods date_as_number = {
2648 date_add, /* nb_add */
2649 date_subtract, /* nb_subtract */
2650 0, /* nb_multiply */
Tim Peters2a799bf2002-12-16 20:18:38 +00002651 0, /* nb_remainder */
2652 0, /* nb_divmod */
2653 0, /* nb_power */
2654 0, /* nb_negative */
2655 0, /* nb_positive */
2656 0, /* nb_absolute */
Jack Diederich4dafcc42006-11-28 19:15:13 +00002657 0, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00002658};
2659
2660static PyTypeObject PyDateTime_DateType = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002661 PyVarObject_HEAD_INIT(NULL, 0)
Tim Peters2a799bf2002-12-16 20:18:38 +00002662 "datetime.date", /* tp_name */
2663 sizeof(PyDateTime_Date), /* tp_basicsize */
2664 0, /* tp_itemsize */
Guido van Rossum8b7a9a32003-04-14 22:01:58 +00002665 0, /* tp_dealloc */
Tim Peters2a799bf2002-12-16 20:18:38 +00002666 0, /* tp_print */
2667 0, /* tp_getattr */
2668 0, /* tp_setattr */
2669 0, /* tp_compare */
2670 (reprfunc)date_repr, /* tp_repr */
2671 &date_as_number, /* tp_as_number */
2672 0, /* tp_as_sequence */
2673 0, /* tp_as_mapping */
2674 (hashfunc)date_hash, /* tp_hash */
2675 0, /* tp_call */
2676 (reprfunc)date_str, /* tp_str */
2677 PyObject_GenericGetAttr, /* tp_getattro */
2678 0, /* tp_setattro */
2679 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00002680 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters2a799bf2002-12-16 20:18:38 +00002681 date_doc, /* tp_doc */
2682 0, /* tp_traverse */
2683 0, /* tp_clear */
Guido van Rossum19960592006-08-24 17:29:38 +00002684 date_richcompare, /* tp_richcompare */
Tim Peters2a799bf2002-12-16 20:18:38 +00002685 0, /* tp_weaklistoffset */
2686 0, /* tp_iter */
2687 0, /* tp_iternext */
2688 date_methods, /* tp_methods */
2689 0, /* tp_members */
2690 date_getset, /* tp_getset */
2691 0, /* tp_base */
2692 0, /* tp_dict */
2693 0, /* tp_descr_get */
2694 0, /* tp_descr_set */
2695 0, /* tp_dictoffset */
2696 0, /* tp_init */
2697 0, /* tp_alloc */
2698 date_new, /* tp_new */
Tim Peters4c530132003-05-16 22:44:06 +00002699 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00002700};
2701
2702/*
Tim Peters2a799bf2002-12-16 20:18:38 +00002703 * PyDateTime_TZInfo implementation.
2704 */
2705
2706/* This is a pure abstract base class, so doesn't do anything beyond
2707 * raising NotImplemented exceptions. Real tzinfo classes need
2708 * to derive from this. This is mostly for clarity, and for efficiency in
Tim Petersa9bc1682003-01-11 03:39:11 +00002709 * datetime and time constructors (their tzinfo arguments need to
Tim Peters2a799bf2002-12-16 20:18:38 +00002710 * be subclasses of this tzinfo class, which is easy and quick to check).
2711 *
2712 * Note: For reasons having to do with pickling of subclasses, we have
2713 * to allow tzinfo objects to be instantiated. This wasn't an issue
2714 * in the Python implementation (__init__() could raise NotImplementedError
2715 * there without ill effect), but doing so in the C implementation hit a
2716 * brick wall.
2717 */
2718
2719static PyObject *
2720tzinfo_nogo(const char* methodname)
2721{
2722 PyErr_Format(PyExc_NotImplementedError,
2723 "a tzinfo subclass must implement %s()",
2724 methodname);
2725 return NULL;
2726}
2727
2728/* Methods. A subclass must implement these. */
2729
Tim Peters52dcce22003-01-23 16:36:11 +00002730static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002731tzinfo_tzname(PyDateTime_TZInfo *self, PyObject *dt)
2732{
2733 return tzinfo_nogo("tzname");
2734}
2735
Tim Peters52dcce22003-01-23 16:36:11 +00002736static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002737tzinfo_utcoffset(PyDateTime_TZInfo *self, PyObject *dt)
2738{
2739 return tzinfo_nogo("utcoffset");
2740}
2741
Tim Peters52dcce22003-01-23 16:36:11 +00002742static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002743tzinfo_dst(PyDateTime_TZInfo *self, PyObject *dt)
2744{
2745 return tzinfo_nogo("dst");
2746}
2747
Tim Peters52dcce22003-01-23 16:36:11 +00002748static PyObject *
2749tzinfo_fromutc(PyDateTime_TZInfo *self, PyDateTime_DateTime *dt)
2750{
2751 int y, m, d, hh, mm, ss, us;
2752
2753 PyObject *result;
2754 int off, dst;
2755 int none;
2756 int delta;
2757
2758 if (! PyDateTime_Check(dt)) {
2759 PyErr_SetString(PyExc_TypeError,
2760 "fromutc: argument must be a datetime");
2761 return NULL;
2762 }
2763 if (! HASTZINFO(dt) || dt->tzinfo != (PyObject *)self) {
2764 PyErr_SetString(PyExc_ValueError, "fromutc: dt.tzinfo "
2765 "is not self");
2766 return NULL;
2767 }
2768
2769 off = call_utcoffset(dt->tzinfo, (PyObject *)dt, &none);
2770 if (off == -1 && PyErr_Occurred())
2771 return NULL;
2772 if (none) {
2773 PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
2774 "utcoffset() result required");
2775 return NULL;
2776 }
2777
2778 dst = call_dst(dt->tzinfo, (PyObject *)dt, &none);
2779 if (dst == -1 && PyErr_Occurred())
2780 return NULL;
2781 if (none) {
2782 PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
2783 "dst() result required");
2784 return NULL;
2785 }
2786
2787 y = GET_YEAR(dt);
2788 m = GET_MONTH(dt);
2789 d = GET_DAY(dt);
2790 hh = DATE_GET_HOUR(dt);
2791 mm = DATE_GET_MINUTE(dt);
2792 ss = DATE_GET_SECOND(dt);
2793 us = DATE_GET_MICROSECOND(dt);
2794
2795 delta = off - dst;
2796 mm += delta;
2797 if ((mm < 0 || mm >= 60) &&
2798 normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
Tim Petersb1049e82003-01-23 17:20:36 +00002799 return NULL;
Tim Peters52dcce22003-01-23 16:36:11 +00002800 result = new_datetime(y, m, d, hh, mm, ss, us, dt->tzinfo);
2801 if (result == NULL)
2802 return result;
2803
2804 dst = call_dst(dt->tzinfo, result, &none);
2805 if (dst == -1 && PyErr_Occurred())
2806 goto Fail;
2807 if (none)
2808 goto Inconsistent;
2809 if (dst == 0)
2810 return result;
2811
2812 mm += dst;
2813 if ((mm < 0 || mm >= 60) &&
2814 normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
2815 goto Fail;
2816 Py_DECREF(result);
2817 result = new_datetime(y, m, d, hh, mm, ss, us, dt->tzinfo);
2818 return result;
2819
2820Inconsistent:
2821 PyErr_SetString(PyExc_ValueError, "fromutc: tz.dst() gave"
2822 "inconsistent results; cannot convert");
2823
2824 /* fall thru to failure */
2825Fail:
2826 Py_DECREF(result);
2827 return NULL;
2828}
2829
Tim Peters2a799bf2002-12-16 20:18:38 +00002830/*
2831 * Pickle support. This is solely so that tzinfo subclasses can use
Guido van Rossum177e41a2003-01-30 22:06:23 +00002832 * pickling -- tzinfo itself is supposed to be uninstantiable.
Tim Peters2a799bf2002-12-16 20:18:38 +00002833 */
2834
Guido van Rossum177e41a2003-01-30 22:06:23 +00002835static PyObject *
2836tzinfo_reduce(PyObject *self)
2837{
2838 PyObject *args, *state, *tmp;
2839 PyObject *getinitargs, *getstate;
Tim Peters2a799bf2002-12-16 20:18:38 +00002840
Guido van Rossum177e41a2003-01-30 22:06:23 +00002841 tmp = PyTuple_New(0);
2842 if (tmp == NULL)
2843 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002844
Guido van Rossum177e41a2003-01-30 22:06:23 +00002845 getinitargs = PyObject_GetAttrString(self, "__getinitargs__");
2846 if (getinitargs != NULL) {
2847 args = PyObject_CallObject(getinitargs, tmp);
2848 Py_DECREF(getinitargs);
2849 if (args == NULL) {
2850 Py_DECREF(tmp);
2851 return NULL;
2852 }
2853 }
2854 else {
2855 PyErr_Clear();
2856 args = tmp;
2857 Py_INCREF(args);
2858 }
2859
2860 getstate = PyObject_GetAttrString(self, "__getstate__");
2861 if (getstate != NULL) {
2862 state = PyObject_CallObject(getstate, tmp);
2863 Py_DECREF(getstate);
2864 if (state == NULL) {
2865 Py_DECREF(args);
2866 Py_DECREF(tmp);
2867 return NULL;
2868 }
2869 }
2870 else {
2871 PyObject **dictptr;
2872 PyErr_Clear();
2873 state = Py_None;
2874 dictptr = _PyObject_GetDictPtr(self);
2875 if (dictptr && *dictptr && PyDict_Size(*dictptr))
2876 state = *dictptr;
2877 Py_INCREF(state);
2878 }
2879
2880 Py_DECREF(tmp);
2881
2882 if (state == Py_None) {
2883 Py_DECREF(state);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002884 return Py_BuildValue("(ON)", Py_Type(self), args);
Guido van Rossum177e41a2003-01-30 22:06:23 +00002885 }
2886 else
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002887 return Py_BuildValue("(ONN)", Py_Type(self), args, state);
Guido van Rossum177e41a2003-01-30 22:06:23 +00002888}
Tim Peters2a799bf2002-12-16 20:18:38 +00002889
2890static PyMethodDef tzinfo_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002891
Tim Peters2a799bf2002-12-16 20:18:38 +00002892 {"tzname", (PyCFunction)tzinfo_tzname, METH_O,
2893 PyDoc_STR("datetime -> string name of time zone.")},
2894
2895 {"utcoffset", (PyCFunction)tzinfo_utcoffset, METH_O,
2896 PyDoc_STR("datetime -> minutes east of UTC (negative for "
2897 "west of UTC).")},
2898
2899 {"dst", (PyCFunction)tzinfo_dst, METH_O,
2900 PyDoc_STR("datetime -> DST offset in minutes east of UTC.")},
2901
Tim Peters52dcce22003-01-23 16:36:11 +00002902 {"fromutc", (PyCFunction)tzinfo_fromutc, METH_O,
2903 PyDoc_STR("datetime in UTC -> datetime in local time.")},
2904
Guido van Rossum177e41a2003-01-30 22:06:23 +00002905 {"__reduce__", (PyCFunction)tzinfo_reduce, METH_NOARGS,
2906 PyDoc_STR("-> (cls, state)")},
2907
Tim Peters2a799bf2002-12-16 20:18:38 +00002908 {NULL, NULL}
2909};
2910
2911static char tzinfo_doc[] =
2912PyDoc_STR("Abstract base class for time zone info objects.");
2913
Neal Norwitz227b5332006-03-22 09:28:35 +00002914static PyTypeObject PyDateTime_TZInfoType = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002915 PyVarObject_HEAD_INIT(NULL, 0)
Tim Peters2a799bf2002-12-16 20:18:38 +00002916 "datetime.tzinfo", /* tp_name */
2917 sizeof(PyDateTime_TZInfo), /* tp_basicsize */
2918 0, /* tp_itemsize */
2919 0, /* tp_dealloc */
2920 0, /* tp_print */
2921 0, /* tp_getattr */
2922 0, /* tp_setattr */
2923 0, /* tp_compare */
2924 0, /* tp_repr */
2925 0, /* tp_as_number */
2926 0, /* tp_as_sequence */
2927 0, /* tp_as_mapping */
2928 0, /* tp_hash */
2929 0, /* tp_call */
2930 0, /* tp_str */
2931 PyObject_GenericGetAttr, /* tp_getattro */
2932 0, /* tp_setattro */
2933 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00002934 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters2a799bf2002-12-16 20:18:38 +00002935 tzinfo_doc, /* tp_doc */
2936 0, /* tp_traverse */
2937 0, /* tp_clear */
2938 0, /* tp_richcompare */
2939 0, /* tp_weaklistoffset */
2940 0, /* tp_iter */
2941 0, /* tp_iternext */
2942 tzinfo_methods, /* tp_methods */
2943 0, /* tp_members */
2944 0, /* tp_getset */
2945 0, /* tp_base */
2946 0, /* tp_dict */
2947 0, /* tp_descr_get */
2948 0, /* tp_descr_set */
2949 0, /* tp_dictoffset */
2950 0, /* tp_init */
2951 0, /* tp_alloc */
2952 PyType_GenericNew, /* tp_new */
2953 0, /* tp_free */
2954};
2955
2956/*
Tim Peters37f39822003-01-10 03:49:02 +00002957 * PyDateTime_Time implementation.
Tim Peters2a799bf2002-12-16 20:18:38 +00002958 */
2959
Tim Peters37f39822003-01-10 03:49:02 +00002960/* Accessor properties.
Tim Peters2a799bf2002-12-16 20:18:38 +00002961 */
2962
2963static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00002964time_hour(PyDateTime_Time *self, void *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00002965{
Tim Peters37f39822003-01-10 03:49:02 +00002966 return PyInt_FromLong(TIME_GET_HOUR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002967}
2968
Tim Peters37f39822003-01-10 03:49:02 +00002969static PyObject *
2970time_minute(PyDateTime_Time *self, void *unused)
2971{
2972 return PyInt_FromLong(TIME_GET_MINUTE(self));
2973}
2974
2975/* The name time_second conflicted with some platform header file. */
2976static PyObject *
2977py_time_second(PyDateTime_Time *self, void *unused)
2978{
2979 return PyInt_FromLong(TIME_GET_SECOND(self));
2980}
2981
2982static PyObject *
2983time_microsecond(PyDateTime_Time *self, void *unused)
2984{
2985 return PyInt_FromLong(TIME_GET_MICROSECOND(self));
2986}
2987
2988static PyObject *
2989time_tzinfo(PyDateTime_Time *self, void *unused)
2990{
Tim Petersa032d2e2003-01-11 00:15:54 +00002991 PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
Tim Peters37f39822003-01-10 03:49:02 +00002992 Py_INCREF(result);
2993 return result;
2994}
2995
2996static PyGetSetDef time_getset[] = {
2997 {"hour", (getter)time_hour},
2998 {"minute", (getter)time_minute},
2999 {"second", (getter)py_time_second},
3000 {"microsecond", (getter)time_microsecond},
3001 {"tzinfo", (getter)time_tzinfo},
Tim Peters2a799bf2002-12-16 20:18:38 +00003002 {NULL}
3003};
3004
3005/*
3006 * Constructors.
3007 */
3008
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003009static char *time_kws[] = {"hour", "minute", "second", "microsecond",
Tim Peters37f39822003-01-10 03:49:02 +00003010 "tzinfo", NULL};
Tim Peters12bf3392002-12-24 05:41:27 +00003011
Tim Peters2a799bf2002-12-16 20:18:38 +00003012static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003013time_new(PyTypeObject *type, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003014{
3015 PyObject *self = NULL;
Tim Peters70533e22003-02-01 04:40:04 +00003016 PyObject *state;
Tim Peters2a799bf2002-12-16 20:18:38 +00003017 int hour = 0;
3018 int minute = 0;
3019 int second = 0;
3020 int usecond = 0;
3021 PyObject *tzinfo = Py_None;
3022
Guido van Rossum177e41a2003-01-30 22:06:23 +00003023 /* Check for invocation from pickle with __getstate__ state */
3024 if (PyTuple_GET_SIZE(args) >= 1 &&
3025 PyTuple_GET_SIZE(args) <= 2 &&
Martin v. Löwis10a60b32007-07-18 02:28:27 +00003026 PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) &&
3027 PyBytes_GET_SIZE(state) == _PyDateTime_TIME_DATASIZE &&
3028 ((unsigned char) (PyBytes_AS_STRING(state)[0])) < 24)
Guido van Rossum177e41a2003-01-30 22:06:23 +00003029 {
Tim Peters70533e22003-02-01 04:40:04 +00003030 PyDateTime_Time *me;
3031 char aware;
3032
3033 if (PyTuple_GET_SIZE(args) == 2) {
Guido van Rossum177e41a2003-01-30 22:06:23 +00003034 tzinfo = PyTuple_GET_ITEM(args, 1);
Tim Peters70533e22003-02-01 04:40:04 +00003035 if (check_tzinfo_subclass(tzinfo) < 0) {
3036 PyErr_SetString(PyExc_TypeError, "bad "
3037 "tzinfo state arg");
3038 return NULL;
Guido van Rossum177e41a2003-01-30 22:06:23 +00003039 }
3040 }
Tim Peters70533e22003-02-01 04:40:04 +00003041 aware = (char)(tzinfo != Py_None);
Tim Peters604c0132004-06-07 23:04:33 +00003042 me = (PyDateTime_Time *) (type->tp_alloc(type, aware));
Tim Peters70533e22003-02-01 04:40:04 +00003043 if (me != NULL) {
Martin v. Löwis10a60b32007-07-18 02:28:27 +00003044 char *pdata = PyBytes_AS_STRING(state);
Tim Peters70533e22003-02-01 04:40:04 +00003045
3046 memcpy(me->data, pdata, _PyDateTime_TIME_DATASIZE);
3047 me->hashcode = -1;
3048 me->hastzinfo = aware;
3049 if (aware) {
3050 Py_INCREF(tzinfo);
3051 me->tzinfo = tzinfo;
3052 }
3053 }
3054 return (PyObject *)me;
Guido van Rossum177e41a2003-01-30 22:06:23 +00003055 }
3056
Tim Peters37f39822003-01-10 03:49:02 +00003057 if (PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO", time_kws,
Tim Peters2a799bf2002-12-16 20:18:38 +00003058 &hour, &minute, &second, &usecond,
3059 &tzinfo)) {
3060 if (check_time_args(hour, minute, second, usecond) < 0)
3061 return NULL;
3062 if (check_tzinfo_subclass(tzinfo) < 0)
3063 return NULL;
Tim Petersa98924a2003-05-17 05:55:19 +00003064 self = new_time_ex(hour, minute, second, usecond, tzinfo,
3065 type);
Tim Peters2a799bf2002-12-16 20:18:38 +00003066 }
3067 return self;
3068}
3069
3070/*
3071 * Destructor.
3072 */
3073
3074static void
Tim Peters37f39822003-01-10 03:49:02 +00003075time_dealloc(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003076{
Tim Petersa032d2e2003-01-11 00:15:54 +00003077 if (HASTZINFO(self)) {
Tim Peters37f39822003-01-10 03:49:02 +00003078 Py_XDECREF(self->tzinfo);
Neal Norwitz8e914d92003-01-10 15:29:16 +00003079 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003080 Py_Type(self)->tp_free((PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00003081}
3082
3083/*
Tim Peters855fe882002-12-22 03:43:39 +00003084 * Indirect access to tzinfo methods.
Tim Peters2a799bf2002-12-16 20:18:38 +00003085 */
3086
Tim Peters2a799bf2002-12-16 20:18:38 +00003087/* These are all METH_NOARGS, so don't need to check the arglist. */
3088static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003089time_utcoffset(PyDateTime_Time *self, PyObject *unused) {
Tim Petersa032d2e2003-01-11 00:15:54 +00003090 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
Tim Peters37f39822003-01-10 03:49:02 +00003091 "utcoffset", Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00003092}
3093
3094static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003095time_dst(PyDateTime_Time *self, PyObject *unused) {
Tim Petersa032d2e2003-01-11 00:15:54 +00003096 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
Tim Peters37f39822003-01-10 03:49:02 +00003097 "dst", Py_None);
Tim Peters855fe882002-12-22 03:43:39 +00003098}
3099
3100static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003101time_tzname(PyDateTime_Time *self, PyObject *unused) {
Tim Petersa032d2e2003-01-11 00:15:54 +00003102 return call_tzname(HASTZINFO(self) ? self->tzinfo : Py_None,
Tim Peters37f39822003-01-10 03:49:02 +00003103 Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00003104}
3105
3106/*
Tim Peters37f39822003-01-10 03:49:02 +00003107 * Various ways to turn a time into a string.
Tim Peters2a799bf2002-12-16 20:18:38 +00003108 */
3109
3110static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003111time_repr(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003112{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003113 const char *type_name = Py_Type(self)->tp_name;
Tim Peters37f39822003-01-10 03:49:02 +00003114 int h = TIME_GET_HOUR(self);
3115 int m = TIME_GET_MINUTE(self);
3116 int s = TIME_GET_SECOND(self);
3117 int us = TIME_GET_MICROSECOND(self);
3118 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00003119
Tim Peters37f39822003-01-10 03:49:02 +00003120 if (us)
Walter Dörwald7569dfe2007-05-19 21:49:49 +00003121 result = PyUnicode_FromFormat("%s(%d, %d, %d, %d)",
3122 type_name, h, m, s, us);
Tim Peters37f39822003-01-10 03:49:02 +00003123 else if (s)
Walter Dörwald7569dfe2007-05-19 21:49:49 +00003124 result = PyUnicode_FromFormat("%s(%d, %d, %d)",
3125 type_name, h, m, s);
Tim Peters37f39822003-01-10 03:49:02 +00003126 else
Walter Dörwald7569dfe2007-05-19 21:49:49 +00003127 result = PyUnicode_FromFormat("%s(%d, %d)", type_name, h, m);
Tim Petersa032d2e2003-01-11 00:15:54 +00003128 if (result != NULL && HASTZINFO(self))
Tim Peters37f39822003-01-10 03:49:02 +00003129 result = append_keyword_tzinfo(result, self->tzinfo);
3130 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00003131}
3132
Tim Peters37f39822003-01-10 03:49:02 +00003133static PyObject *
3134time_str(PyDateTime_Time *self)
3135{
3136 return PyObject_CallMethod((PyObject *)self, "isoformat", "()");
3137}
Tim Peters2a799bf2002-12-16 20:18:38 +00003138
3139static PyObject *
Thomas Wouterscf297e42007-02-23 15:07:44 +00003140time_isoformat(PyDateTime_Time *self, PyObject *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00003141{
3142 char buf[100];
Tim Peters37f39822003-01-10 03:49:02 +00003143 PyObject *result;
Walter Dörwaldbafa1372007-05-31 17:50:48 +00003144 int us = TIME_GET_MICROSECOND(self);;
Tim Peters2a799bf2002-12-16 20:18:38 +00003145
Walter Dörwaldbafa1372007-05-31 17:50:48 +00003146 if (us)
3147 result = PyUnicode_FromFormat("%02d:%02d:%02d.%06d",
3148 TIME_GET_HOUR(self),
3149 TIME_GET_MINUTE(self),
3150 TIME_GET_SECOND(self),
3151 us);
3152 else
3153 result = PyUnicode_FromFormat("%02d:%02d:%02d",
3154 TIME_GET_HOUR(self),
3155 TIME_GET_MINUTE(self),
3156 TIME_GET_SECOND(self));
Tim Peters37f39822003-01-10 03:49:02 +00003157
Tim Petersa032d2e2003-01-11 00:15:54 +00003158 if (result == NULL || ! HASTZINFO(self) || self->tzinfo == Py_None)
Tim Peters2a799bf2002-12-16 20:18:38 +00003159 return result;
3160
3161 /* We need to append the UTC offset. */
3162 if (format_utcoffset(buf, sizeof(buf), ":", self->tzinfo,
Tim Petersbad8ff02002-12-30 20:52:32 +00003163 Py_None) < 0) {
Tim Peters2a799bf2002-12-16 20:18:38 +00003164 Py_DECREF(result);
3165 return NULL;
3166 }
Walter Dörwaldbafa1372007-05-31 17:50:48 +00003167 PyUnicode_AppendAndDel(&result, PyUnicode_FromString(buf));
Tim Peters2a799bf2002-12-16 20:18:38 +00003168 return result;
3169}
3170
Tim Peters37f39822003-01-10 03:49:02 +00003171static PyObject *
3172time_strftime(PyDateTime_Time *self, PyObject *args, PyObject *kw)
3173{
3174 PyObject *result;
3175 PyObject *format;
3176 PyObject *tuple;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003177 static char *keywords[] = {"format", NULL};
Tim Peters37f39822003-01-10 03:49:02 +00003178
Guido van Rossumbce56a62007-05-10 18:04:33 +00003179 if (! PyArg_ParseTupleAndKeywords(args, kw, "S:strftime", keywords,
3180 &format))
Tim Peters37f39822003-01-10 03:49:02 +00003181 return NULL;
3182
3183 /* Python's strftime does insane things with the year part of the
3184 * timetuple. The year is forced to (the otherwise nonsensical)
3185 * 1900 to worm around that.
3186 */
3187 tuple = Py_BuildValue("iiiiiiiii",
Brett Cannond1080a32004-03-02 04:38:10 +00003188 1900, 1, 1, /* year, month, day */
Tim Peters37f39822003-01-10 03:49:02 +00003189 TIME_GET_HOUR(self),
3190 TIME_GET_MINUTE(self),
3191 TIME_GET_SECOND(self),
Brett Cannond1080a32004-03-02 04:38:10 +00003192 0, 1, -1); /* weekday, daynum, dst */
Tim Peters37f39822003-01-10 03:49:02 +00003193 if (tuple == NULL)
3194 return NULL;
3195 assert(PyTuple_Size(tuple) == 9);
3196 result = wrap_strftime((PyObject *)self, format, tuple, Py_None);
3197 Py_DECREF(tuple);
3198 return result;
3199}
Tim Peters2a799bf2002-12-16 20:18:38 +00003200
3201/*
3202 * Miscellaneous methods.
3203 */
3204
Tim Peters37f39822003-01-10 03:49:02 +00003205static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00003206time_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters37f39822003-01-10 03:49:02 +00003207{
3208 int diff;
3209 naivety n1, n2;
3210 int offset1, offset2;
3211
3212 if (! PyTime_Check(other)) {
Guido van Rossum19960592006-08-24 17:29:38 +00003213 Py_INCREF(Py_NotImplemented);
3214 return Py_NotImplemented;
Tim Peters37f39822003-01-10 03:49:02 +00003215 }
Guido van Rossum19960592006-08-24 17:29:38 +00003216 if (classify_two_utcoffsets(self, &offset1, &n1, Py_None,
3217 other, &offset2, &n2, Py_None) < 0)
Tim Peters37f39822003-01-10 03:49:02 +00003218 return NULL;
3219 assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
3220 /* If they're both naive, or both aware and have the same offsets,
3221 * we get off cheap. Note that if they're both naive, offset1 ==
3222 * offset2 == 0 at this point.
3223 */
3224 if (n1 == n2 && offset1 == offset2) {
Guido van Rossum19960592006-08-24 17:29:38 +00003225 diff = memcmp(((PyDateTime_Time *)self)->data,
3226 ((PyDateTime_Time *)other)->data,
Tim Peters37f39822003-01-10 03:49:02 +00003227 _PyDateTime_TIME_DATASIZE);
3228 return diff_to_bool(diff, op);
3229 }
3230
3231 if (n1 == OFFSET_AWARE && n2 == OFFSET_AWARE) {
3232 assert(offset1 != offset2); /* else last "if" handled it */
3233 /* Convert everything except microseconds to seconds. These
3234 * can't overflow (no more than the # of seconds in 2 days).
3235 */
3236 offset1 = TIME_GET_HOUR(self) * 3600 +
3237 (TIME_GET_MINUTE(self) - offset1) * 60 +
3238 TIME_GET_SECOND(self);
3239 offset2 = TIME_GET_HOUR(other) * 3600 +
3240 (TIME_GET_MINUTE(other) - offset2) * 60 +
3241 TIME_GET_SECOND(other);
3242 diff = offset1 - offset2;
3243 if (diff == 0)
3244 diff = TIME_GET_MICROSECOND(self) -
3245 TIME_GET_MICROSECOND(other);
3246 return diff_to_bool(diff, op);
3247 }
3248
3249 assert(n1 != n2);
3250 PyErr_SetString(PyExc_TypeError,
3251 "can't compare offset-naive and "
3252 "offset-aware times");
3253 return NULL;
3254}
3255
3256static long
3257time_hash(PyDateTime_Time *self)
3258{
3259 if (self->hashcode == -1) {
3260 naivety n;
3261 int offset;
3262 PyObject *temp;
3263
3264 n = classify_utcoffset((PyObject *)self, Py_None, &offset);
3265 assert(n != OFFSET_UNKNOWN);
3266 if (n == OFFSET_ERROR)
3267 return -1;
3268
3269 /* Reduce this to a hash of another object. */
Guido van Rossumfd53fd62007-08-24 04:05:13 +00003270 if (offset == 0) {
3271 self->hashcode = generic_hash(
3272 (unsigned char *)self->data, _PyDateTime_TIME_DATASIZE);
3273 return self->hashcode;
3274 }
Tim Peters37f39822003-01-10 03:49:02 +00003275 else {
3276 int hour;
3277 int minute;
3278
3279 assert(n == OFFSET_AWARE);
Tim Petersa032d2e2003-01-11 00:15:54 +00003280 assert(HASTZINFO(self));
Tim Peters37f39822003-01-10 03:49:02 +00003281 hour = divmod(TIME_GET_HOUR(self) * 60 +
3282 TIME_GET_MINUTE(self) - offset,
3283 60,
3284 &minute);
3285 if (0 <= hour && hour < 24)
3286 temp = new_time(hour, minute,
3287 TIME_GET_SECOND(self),
3288 TIME_GET_MICROSECOND(self),
3289 Py_None);
3290 else
3291 temp = Py_BuildValue("iiii",
3292 hour, minute,
3293 TIME_GET_SECOND(self),
3294 TIME_GET_MICROSECOND(self));
3295 }
3296 if (temp != NULL) {
3297 self->hashcode = PyObject_Hash(temp);
3298 Py_DECREF(temp);
3299 }
3300 }
3301 return self->hashcode;
3302}
Tim Peters2a799bf2002-12-16 20:18:38 +00003303
Tim Peters12bf3392002-12-24 05:41:27 +00003304static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003305time_replace(PyDateTime_Time *self, PyObject *args, PyObject *kw)
Tim Peters12bf3392002-12-24 05:41:27 +00003306{
3307 PyObject *clone;
3308 PyObject *tuple;
3309 int hh = TIME_GET_HOUR(self);
3310 int mm = TIME_GET_MINUTE(self);
3311 int ss = TIME_GET_SECOND(self);
3312 int us = TIME_GET_MICROSECOND(self);
Tim Petersa032d2e2003-01-11 00:15:54 +00003313 PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
Tim Peters12bf3392002-12-24 05:41:27 +00003314
3315 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO:replace",
Tim Peters37f39822003-01-10 03:49:02 +00003316 time_kws,
Tim Peters12bf3392002-12-24 05:41:27 +00003317 &hh, &mm, &ss, &us, &tzinfo))
3318 return NULL;
3319 tuple = Py_BuildValue("iiiiO", hh, mm, ss, us, tzinfo);
3320 if (tuple == NULL)
3321 return NULL;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003322 clone = time_new(Py_Type(self), tuple, NULL);
Tim Peters12bf3392002-12-24 05:41:27 +00003323 Py_DECREF(tuple);
3324 return clone;
3325}
3326
Tim Peters2a799bf2002-12-16 20:18:38 +00003327static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00003328time_bool(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003329{
3330 int offset;
3331 int none;
3332
3333 if (TIME_GET_SECOND(self) || TIME_GET_MICROSECOND(self)) {
3334 /* Since utcoffset is in whole minutes, nothing can
3335 * alter the conclusion that this is nonzero.
3336 */
3337 return 1;
3338 }
3339 offset = 0;
Tim Petersa032d2e2003-01-11 00:15:54 +00003340 if (HASTZINFO(self) && self->tzinfo != Py_None) {
Tim Petersbad8ff02002-12-30 20:52:32 +00003341 offset = call_utcoffset(self->tzinfo, Py_None, &none);
Tim Peters2a799bf2002-12-16 20:18:38 +00003342 if (offset == -1 && PyErr_Occurred())
3343 return -1;
3344 }
3345 return (TIME_GET_MINUTE(self) - offset + TIME_GET_HOUR(self)*60) != 0;
3346}
3347
Tim Peters371935f2003-02-01 01:52:50 +00003348/* Pickle support, a simple use of __reduce__. */
Tim Peters2a799bf2002-12-16 20:18:38 +00003349
Tim Peters33e0f382003-01-10 02:05:14 +00003350/* Let basestate be the non-tzinfo data string.
Tim Peters2a799bf2002-12-16 20:18:38 +00003351 * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
3352 * So it's a tuple in any (non-error) case.
Tim Petersb57f8f02003-02-01 02:54:15 +00003353 * __getstate__ isn't exposed.
Tim Peters2a799bf2002-12-16 20:18:38 +00003354 */
3355static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003356time_getstate(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003357{
3358 PyObject *basestate;
3359 PyObject *result = NULL;
3360
Martin v. Löwis10a60b32007-07-18 02:28:27 +00003361 basestate = PyBytes_FromStringAndSize((char *)self->data,
Tim Peters33e0f382003-01-10 02:05:14 +00003362 _PyDateTime_TIME_DATASIZE);
Tim Peters2a799bf2002-12-16 20:18:38 +00003363 if (basestate != NULL) {
Tim Petersa032d2e2003-01-11 00:15:54 +00003364 if (! HASTZINFO(self) || self->tzinfo == Py_None)
Raymond Hettinger8ae46892003-10-12 19:09:37 +00003365 result = PyTuple_Pack(1, basestate);
Tim Peters2a799bf2002-12-16 20:18:38 +00003366 else
Raymond Hettinger8ae46892003-10-12 19:09:37 +00003367 result = PyTuple_Pack(2, basestate, self->tzinfo);
Tim Peters2a799bf2002-12-16 20:18:38 +00003368 Py_DECREF(basestate);
3369 }
3370 return result;
3371}
3372
3373static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00003374time_reduce(PyDateTime_Time *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00003375{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003376 return Py_BuildValue("(ON)", Py_Type(self), time_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00003377}
3378
Tim Peters37f39822003-01-10 03:49:02 +00003379static PyMethodDef time_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00003380
Thomas Wouterscf297e42007-02-23 15:07:44 +00003381 {"isoformat", (PyCFunction)time_isoformat, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00003382 PyDoc_STR("Return string in ISO 8601 format, HH:MM:SS[.mmmmmm]"
3383 "[+HH:MM].")},
3384
Guido van Rossumd59da4b2007-05-22 18:11:13 +00003385 {"strftime", (PyCFunction)time_strftime, METH_VARARGS | METH_KEYWORDS,
Tim Peters37f39822003-01-10 03:49:02 +00003386 PyDoc_STR("format -> strftime() style string.")},
3387
3388 {"utcoffset", (PyCFunction)time_utcoffset, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00003389 PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
3390
Tim Peters37f39822003-01-10 03:49:02 +00003391 {"tzname", (PyCFunction)time_tzname, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00003392 PyDoc_STR("Return self.tzinfo.tzname(self).")},
3393
Tim Peters37f39822003-01-10 03:49:02 +00003394 {"dst", (PyCFunction)time_dst, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00003395 PyDoc_STR("Return self.tzinfo.dst(self).")},
3396
Guido van Rossumd59da4b2007-05-22 18:11:13 +00003397 {"replace", (PyCFunction)time_replace, METH_VARARGS | METH_KEYWORDS,
Tim Peters37f39822003-01-10 03:49:02 +00003398 PyDoc_STR("Return time with new specified fields.")},
Tim Peters12bf3392002-12-24 05:41:27 +00003399
Guido van Rossum177e41a2003-01-30 22:06:23 +00003400 {"__reduce__", (PyCFunction)time_reduce, METH_NOARGS,
3401 PyDoc_STR("__reduce__() -> (cls, state)")},
3402
Tim Peters2a799bf2002-12-16 20:18:38 +00003403 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00003404};
3405
Tim Peters37f39822003-01-10 03:49:02 +00003406static char time_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00003407PyDoc_STR("time([hour[, minute[, second[, microsecond[, tzinfo]]]]]) --> a time object\n\
3408\n\
3409All arguments are optional. tzinfo may be None, or an instance of\n\
3410a tzinfo subclass. The remaining arguments may be ints or longs.\n");
Tim Peters2a799bf2002-12-16 20:18:38 +00003411
Tim Peters37f39822003-01-10 03:49:02 +00003412static PyNumberMethods time_as_number = {
Tim Peters2a799bf2002-12-16 20:18:38 +00003413 0, /* nb_add */
3414 0, /* nb_subtract */
3415 0, /* nb_multiply */
Tim Peters2a799bf2002-12-16 20:18:38 +00003416 0, /* nb_remainder */
3417 0, /* nb_divmod */
3418 0, /* nb_power */
3419 0, /* nb_negative */
3420 0, /* nb_positive */
3421 0, /* nb_absolute */
Jack Diederich4dafcc42006-11-28 19:15:13 +00003422 (inquiry)time_bool, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00003423};
3424
Neal Norwitz227b5332006-03-22 09:28:35 +00003425static PyTypeObject PyDateTime_TimeType = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003426 PyVarObject_HEAD_INIT(NULL, 0)
Tim Peters0bf60bd2003-01-08 20:40:01 +00003427 "datetime.time", /* tp_name */
Tim Peters37f39822003-01-10 03:49:02 +00003428 sizeof(PyDateTime_Time), /* tp_basicsize */
Tim Peters2a799bf2002-12-16 20:18:38 +00003429 0, /* tp_itemsize */
Tim Peters37f39822003-01-10 03:49:02 +00003430 (destructor)time_dealloc, /* tp_dealloc */
Tim Peters2a799bf2002-12-16 20:18:38 +00003431 0, /* tp_print */
3432 0, /* tp_getattr */
3433 0, /* tp_setattr */
3434 0, /* tp_compare */
Tim Peters37f39822003-01-10 03:49:02 +00003435 (reprfunc)time_repr, /* tp_repr */
3436 &time_as_number, /* tp_as_number */
Tim Peters2a799bf2002-12-16 20:18:38 +00003437 0, /* tp_as_sequence */
3438 0, /* tp_as_mapping */
Tim Peters37f39822003-01-10 03:49:02 +00003439 (hashfunc)time_hash, /* tp_hash */
Tim Peters2a799bf2002-12-16 20:18:38 +00003440 0, /* tp_call */
Tim Peters37f39822003-01-10 03:49:02 +00003441 (reprfunc)time_str, /* tp_str */
Tim Peters2a799bf2002-12-16 20:18:38 +00003442 PyObject_GenericGetAttr, /* tp_getattro */
3443 0, /* tp_setattro */
3444 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00003445 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters37f39822003-01-10 03:49:02 +00003446 time_doc, /* tp_doc */
Tim Peters2a799bf2002-12-16 20:18:38 +00003447 0, /* tp_traverse */
3448 0, /* tp_clear */
Guido van Rossum19960592006-08-24 17:29:38 +00003449 time_richcompare, /* tp_richcompare */
Tim Peters2a799bf2002-12-16 20:18:38 +00003450 0, /* tp_weaklistoffset */
3451 0, /* tp_iter */
3452 0, /* tp_iternext */
Tim Peters37f39822003-01-10 03:49:02 +00003453 time_methods, /* tp_methods */
Tim Peters2a799bf2002-12-16 20:18:38 +00003454 0, /* tp_members */
Tim Peters37f39822003-01-10 03:49:02 +00003455 time_getset, /* tp_getset */
3456 0, /* tp_base */
Tim Peters2a799bf2002-12-16 20:18:38 +00003457 0, /* tp_dict */
3458 0, /* tp_descr_get */
3459 0, /* tp_descr_set */
3460 0, /* tp_dictoffset */
3461 0, /* tp_init */
Tim Petersa98924a2003-05-17 05:55:19 +00003462 time_alloc, /* tp_alloc */
Tim Peters37f39822003-01-10 03:49:02 +00003463 time_new, /* tp_new */
Tim Peters4c530132003-05-16 22:44:06 +00003464 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00003465};
3466
3467/*
Tim Petersa9bc1682003-01-11 03:39:11 +00003468 * PyDateTime_DateTime implementation.
Tim Peters2a799bf2002-12-16 20:18:38 +00003469 */
3470
Tim Petersa9bc1682003-01-11 03:39:11 +00003471/* Accessor properties. Properties for day, month, and year are inherited
3472 * from date.
Tim Peters2a799bf2002-12-16 20:18:38 +00003473 */
3474
3475static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003476datetime_hour(PyDateTime_DateTime *self, void *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00003477{
Tim Petersa9bc1682003-01-11 03:39:11 +00003478 return PyInt_FromLong(DATE_GET_HOUR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00003479}
3480
Tim Petersa9bc1682003-01-11 03:39:11 +00003481static PyObject *
3482datetime_minute(PyDateTime_DateTime *self, void *unused)
3483{
3484 return PyInt_FromLong(DATE_GET_MINUTE(self));
3485}
3486
3487static PyObject *
3488datetime_second(PyDateTime_DateTime *self, void *unused)
3489{
3490 return PyInt_FromLong(DATE_GET_SECOND(self));
3491}
3492
3493static PyObject *
3494datetime_microsecond(PyDateTime_DateTime *self, void *unused)
3495{
3496 return PyInt_FromLong(DATE_GET_MICROSECOND(self));
3497}
3498
3499static PyObject *
3500datetime_tzinfo(PyDateTime_DateTime *self, void *unused)
3501{
3502 PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
3503 Py_INCREF(result);
3504 return result;
3505}
3506
3507static PyGetSetDef datetime_getset[] = {
3508 {"hour", (getter)datetime_hour},
3509 {"minute", (getter)datetime_minute},
3510 {"second", (getter)datetime_second},
3511 {"microsecond", (getter)datetime_microsecond},
3512 {"tzinfo", (getter)datetime_tzinfo},
Tim Peters2a799bf2002-12-16 20:18:38 +00003513 {NULL}
3514};
3515
3516/*
3517 * Constructors.
Tim Peters2a799bf2002-12-16 20:18:38 +00003518 */
3519
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003520static char *datetime_kws[] = {
Tim Peters12bf3392002-12-24 05:41:27 +00003521 "year", "month", "day", "hour", "minute", "second",
3522 "microsecond", "tzinfo", NULL
3523};
3524
Tim Peters2a799bf2002-12-16 20:18:38 +00003525static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003526datetime_new(PyTypeObject *type, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003527{
3528 PyObject *self = NULL;
Tim Peters70533e22003-02-01 04:40:04 +00003529 PyObject *state;
Tim Peters2a799bf2002-12-16 20:18:38 +00003530 int year;
3531 int month;
3532 int day;
3533 int hour = 0;
3534 int minute = 0;
3535 int second = 0;
3536 int usecond = 0;
3537 PyObject *tzinfo = Py_None;
3538
Guido van Rossum177e41a2003-01-30 22:06:23 +00003539 /* Check for invocation from pickle with __getstate__ state */
3540 if (PyTuple_GET_SIZE(args) >= 1 &&
3541 PyTuple_GET_SIZE(args) <= 2 &&
Martin v. Löwis10a60b32007-07-18 02:28:27 +00003542 PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) &&
3543 PyBytes_GET_SIZE(state) == _PyDateTime_DATETIME_DATASIZE &&
3544 MONTH_IS_SANE(PyBytes_AS_STRING(state)[2]))
Guido van Rossum177e41a2003-01-30 22:06:23 +00003545 {
Tim Peters70533e22003-02-01 04:40:04 +00003546 PyDateTime_DateTime *me;
3547 char aware;
3548
3549 if (PyTuple_GET_SIZE(args) == 2) {
Guido van Rossum177e41a2003-01-30 22:06:23 +00003550 tzinfo = PyTuple_GET_ITEM(args, 1);
Tim Peters70533e22003-02-01 04:40:04 +00003551 if (check_tzinfo_subclass(tzinfo) < 0) {
3552 PyErr_SetString(PyExc_TypeError, "bad "
3553 "tzinfo state arg");
3554 return NULL;
Guido van Rossum177e41a2003-01-30 22:06:23 +00003555 }
3556 }
Tim Peters70533e22003-02-01 04:40:04 +00003557 aware = (char)(tzinfo != Py_None);
Tim Peters604c0132004-06-07 23:04:33 +00003558 me = (PyDateTime_DateTime *) (type->tp_alloc(type , aware));
Tim Peters70533e22003-02-01 04:40:04 +00003559 if (me != NULL) {
Martin v. Löwis10a60b32007-07-18 02:28:27 +00003560 char *pdata = PyBytes_AS_STRING(state);
Tim Peters70533e22003-02-01 04:40:04 +00003561
3562 memcpy(me->data, pdata, _PyDateTime_DATETIME_DATASIZE);
3563 me->hashcode = -1;
3564 me->hastzinfo = aware;
3565 if (aware) {
3566 Py_INCREF(tzinfo);
3567 me->tzinfo = tzinfo;
3568 }
3569 }
3570 return (PyObject *)me;
Guido van Rossum177e41a2003-01-30 22:06:23 +00003571 }
3572
Tim Petersa9bc1682003-01-11 03:39:11 +00003573 if (PyArg_ParseTupleAndKeywords(args, kw, "iii|iiiiO", datetime_kws,
Tim Peters2a799bf2002-12-16 20:18:38 +00003574 &year, &month, &day, &hour, &minute,
3575 &second, &usecond, &tzinfo)) {
3576 if (check_date_args(year, month, day) < 0)
3577 return NULL;
3578 if (check_time_args(hour, minute, second, usecond) < 0)
3579 return NULL;
3580 if (check_tzinfo_subclass(tzinfo) < 0)
3581 return NULL;
Tim Petersa98924a2003-05-17 05:55:19 +00003582 self = new_datetime_ex(year, month, day,
3583 hour, minute, second, usecond,
3584 tzinfo, type);
Tim Peters2a799bf2002-12-16 20:18:38 +00003585 }
3586 return self;
3587}
3588
Tim Petersa9bc1682003-01-11 03:39:11 +00003589/* TM_FUNC is the shared type of localtime() and gmtime(). */
3590typedef struct tm *(*TM_FUNC)(const time_t *timer);
3591
3592/* Internal helper.
3593 * Build datetime from a time_t and a distinct count of microseconds.
3594 * Pass localtime or gmtime for f, to control the interpretation of timet.
3595 */
3596static PyObject *
3597datetime_from_timet_and_us(PyObject *cls, TM_FUNC f, time_t timet, int us,
3598 PyObject *tzinfo)
3599{
3600 struct tm *tm;
3601 PyObject *result = NULL;
3602
3603 tm = f(&timet);
3604 if (tm) {
3605 /* The platform localtime/gmtime may insert leap seconds,
3606 * indicated by tm->tm_sec > 59. We don't care about them,
3607 * except to the extent that passing them on to the datetime
3608 * constructor would raise ValueError for a reason that
3609 * made no sense to the user.
3610 */
3611 if (tm->tm_sec > 59)
3612 tm->tm_sec = 59;
3613 result = PyObject_CallFunction(cls, "iiiiiiiO",
3614 tm->tm_year + 1900,
3615 tm->tm_mon + 1,
3616 tm->tm_mday,
3617 tm->tm_hour,
3618 tm->tm_min,
3619 tm->tm_sec,
3620 us,
3621 tzinfo);
3622 }
3623 else
3624 PyErr_SetString(PyExc_ValueError,
3625 "timestamp out of range for "
3626 "platform localtime()/gmtime() function");
3627 return result;
3628}
3629
3630/* Internal helper.
3631 * Build datetime from a Python timestamp. Pass localtime or gmtime for f,
3632 * to control the interpretation of the timestamp. Since a double doesn't
3633 * have enough bits to cover a datetime's full range of precision, it's
3634 * better to call datetime_from_timet_and_us provided you have a way
3635 * to get that much precision (e.g., C time() isn't good enough).
3636 */
3637static PyObject *
3638datetime_from_timestamp(PyObject *cls, TM_FUNC f, double timestamp,
3639 PyObject *tzinfo)
3640{
Tim Peters1b6f7a92004-06-20 02:50:16 +00003641 time_t timet;
3642 double fraction;
3643 int us;
Tim Petersa9bc1682003-01-11 03:39:11 +00003644
Tim Peters1b6f7a92004-06-20 02:50:16 +00003645 timet = _PyTime_DoubleToTimet(timestamp);
3646 if (timet == (time_t)-1 && PyErr_Occurred())
3647 return NULL;
3648 fraction = timestamp - (double)timet;
3649 us = (int)round_to_long(fraction * 1e6);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003650 if (us < 0) {
3651 /* Truncation towards zero is not what we wanted
3652 for negative numbers (Python's mod semantics) */
3653 timet -= 1;
3654 us += 1000000;
3655 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00003656 /* If timestamp is less than one microsecond smaller than a
3657 * full second, round up. Otherwise, ValueErrors are raised
3658 * for some floats. */
3659 if (us == 1000000) {
3660 timet += 1;
3661 us = 0;
3662 }
Tim Petersa9bc1682003-01-11 03:39:11 +00003663 return datetime_from_timet_and_us(cls, f, timet, us, tzinfo);
3664}
3665
3666/* Internal helper.
3667 * Build most accurate possible datetime for current time. Pass localtime or
3668 * gmtime for f as appropriate.
3669 */
3670static PyObject *
3671datetime_best_possible(PyObject *cls, TM_FUNC f, PyObject *tzinfo)
3672{
3673#ifdef HAVE_GETTIMEOFDAY
3674 struct timeval t;
3675
3676#ifdef GETTIMEOFDAY_NO_TZ
3677 gettimeofday(&t);
3678#else
3679 gettimeofday(&t, (struct timezone *)NULL);
3680#endif
3681 return datetime_from_timet_and_us(cls, f, t.tv_sec, (int)t.tv_usec,
3682 tzinfo);
3683
3684#else /* ! HAVE_GETTIMEOFDAY */
3685 /* No flavor of gettimeofday exists on this platform. Python's
3686 * time.time() does a lot of other platform tricks to get the
3687 * best time it can on the platform, and we're not going to do
3688 * better than that (if we could, the better code would belong
3689 * in time.time()!) We're limited by the precision of a double,
3690 * though.
3691 */
3692 PyObject *time;
3693 double dtime;
3694
3695 time = time_time();
3696 if (time == NULL)
3697 return NULL;
3698 dtime = PyFloat_AsDouble(time);
3699 Py_DECREF(time);
3700 if (dtime == -1.0 && PyErr_Occurred())
3701 return NULL;
3702 return datetime_from_timestamp(cls, f, dtime, tzinfo);
3703#endif /* ! HAVE_GETTIMEOFDAY */
3704}
3705
Tim Peters2a799bf2002-12-16 20:18:38 +00003706/* Return best possible local time -- this isn't constrained by the
3707 * precision of a timestamp.
3708 */
3709static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003710datetime_now(PyObject *cls, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003711{
Tim Peters10cadce2003-01-23 19:58:02 +00003712 PyObject *self;
Tim Peters2a799bf2002-12-16 20:18:38 +00003713 PyObject *tzinfo = Py_None;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003714 static char *keywords[] = {"tz", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00003715
Tim Peters10cadce2003-01-23 19:58:02 +00003716 if (! PyArg_ParseTupleAndKeywords(args, kw, "|O:now", keywords,
3717 &tzinfo))
3718 return NULL;
3719 if (check_tzinfo_subclass(tzinfo) < 0)
3720 return NULL;
3721
3722 self = datetime_best_possible(cls,
3723 tzinfo == Py_None ? localtime : gmtime,
3724 tzinfo);
3725 if (self != NULL && tzinfo != Py_None) {
3726 /* Convert UTC to tzinfo's zone. */
3727 PyObject *temp = self;
Tim Peters2a44a8d2003-01-23 20:53:10 +00003728 self = PyObject_CallMethod(tzinfo, "fromutc", "O", self);
Tim Peters10cadce2003-01-23 19:58:02 +00003729 Py_DECREF(temp);
Tim Peters2a799bf2002-12-16 20:18:38 +00003730 }
3731 return self;
3732}
3733
Tim Petersa9bc1682003-01-11 03:39:11 +00003734/* Return best possible UTC time -- this isn't constrained by the
3735 * precision of a timestamp.
3736 */
3737static PyObject *
3738datetime_utcnow(PyObject *cls, PyObject *dummy)
3739{
3740 return datetime_best_possible(cls, gmtime, Py_None);
3741}
3742
Tim Peters2a799bf2002-12-16 20:18:38 +00003743/* Return new local datetime from timestamp (Python timestamp -- a double). */
3744static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003745datetime_fromtimestamp(PyObject *cls, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003746{
Tim Peters2a44a8d2003-01-23 20:53:10 +00003747 PyObject *self;
Tim Peters2a799bf2002-12-16 20:18:38 +00003748 double timestamp;
3749 PyObject *tzinfo = Py_None;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003750 static char *keywords[] = {"timestamp", "tz", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00003751
Tim Peters2a44a8d2003-01-23 20:53:10 +00003752 if (! PyArg_ParseTupleAndKeywords(args, kw, "d|O:fromtimestamp",
3753 keywords, &timestamp, &tzinfo))
3754 return NULL;
3755 if (check_tzinfo_subclass(tzinfo) < 0)
3756 return NULL;
3757
3758 self = datetime_from_timestamp(cls,
3759 tzinfo == Py_None ? localtime : gmtime,
3760 timestamp,
3761 tzinfo);
3762 if (self != NULL && tzinfo != Py_None) {
3763 /* Convert UTC to tzinfo's zone. */
3764 PyObject *temp = self;
3765 self = PyObject_CallMethod(tzinfo, "fromutc", "O", self);
3766 Py_DECREF(temp);
Tim Peters2a799bf2002-12-16 20:18:38 +00003767 }
3768 return self;
3769}
3770
Tim Petersa9bc1682003-01-11 03:39:11 +00003771/* Return new UTC datetime from timestamp (Python timestamp -- a double). */
3772static PyObject *
3773datetime_utcfromtimestamp(PyObject *cls, PyObject *args)
3774{
3775 double timestamp;
3776 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00003777
Tim Petersa9bc1682003-01-11 03:39:11 +00003778 if (PyArg_ParseTuple(args, "d:utcfromtimestamp", &timestamp))
3779 result = datetime_from_timestamp(cls, gmtime, timestamp,
3780 Py_None);
3781 return result;
3782}
3783
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003784/* Return new datetime from time.strptime(). */
3785static PyObject *
3786datetime_strptime(PyObject *cls, PyObject *args)
3787{
3788 PyObject *result = NULL, *obj, *module;
3789 const char *string, *format;
3790
Guido van Rossumfd53fd62007-08-24 04:05:13 +00003791 if (!PyArg_ParseTuple(args, "uu:strptime", &string, &format))
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003792 return NULL;
3793
3794 if ((module = PyImport_ImportModule("time")) == NULL)
3795 return NULL;
Guido van Rossumfd53fd62007-08-24 04:05:13 +00003796 obj = PyObject_CallMethod(module, "strptime", "uu", string, format);
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003797 Py_DECREF(module);
3798
3799 if (obj != NULL) {
3800 int i, good_timetuple = 1;
3801 long int ia[6];
3802 if (PySequence_Check(obj) && PySequence_Size(obj) >= 6)
3803 for (i=0; i < 6; i++) {
3804 PyObject *p = PySequence_GetItem(obj, i);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003805 if (p == NULL) {
3806 Py_DECREF(obj);
3807 return NULL;
3808 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00003809 if (PyInt_CheckExact(p))
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003810 ia[i] = PyInt_AsLong(p);
3811 else
3812 good_timetuple = 0;
3813 Py_DECREF(p);
3814 }
3815 else
3816 good_timetuple = 0;
3817 if (good_timetuple)
3818 result = PyObject_CallFunction(cls, "iiiiii",
3819 ia[0], ia[1], ia[2], ia[3], ia[4], ia[5]);
3820 else
3821 PyErr_SetString(PyExc_ValueError,
3822 "unexpected value from time.strptime");
3823 Py_DECREF(obj);
3824 }
3825 return result;
3826}
3827
Tim Petersa9bc1682003-01-11 03:39:11 +00003828/* Return new datetime from date/datetime and time arguments. */
3829static PyObject *
3830datetime_combine(PyObject *cls, PyObject *args, PyObject *kw)
3831{
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003832 static char *keywords[] = {"date", "time", NULL};
Tim Petersa9bc1682003-01-11 03:39:11 +00003833 PyObject *date;
3834 PyObject *time;
3835 PyObject *result = NULL;
3836
3837 if (PyArg_ParseTupleAndKeywords(args, kw, "O!O!:combine", keywords,
3838 &PyDateTime_DateType, &date,
3839 &PyDateTime_TimeType, &time)) {
3840 PyObject *tzinfo = Py_None;
3841
3842 if (HASTZINFO(time))
3843 tzinfo = ((PyDateTime_Time *)time)->tzinfo;
3844 result = PyObject_CallFunction(cls, "iiiiiiiO",
3845 GET_YEAR(date),
3846 GET_MONTH(date),
3847 GET_DAY(date),
3848 TIME_GET_HOUR(time),
3849 TIME_GET_MINUTE(time),
3850 TIME_GET_SECOND(time),
3851 TIME_GET_MICROSECOND(time),
3852 tzinfo);
3853 }
3854 return result;
3855}
Tim Peters2a799bf2002-12-16 20:18:38 +00003856
3857/*
3858 * Destructor.
3859 */
3860
3861static void
Tim Petersa9bc1682003-01-11 03:39:11 +00003862datetime_dealloc(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003863{
Tim Petersa9bc1682003-01-11 03:39:11 +00003864 if (HASTZINFO(self)) {
3865 Py_XDECREF(self->tzinfo);
3866 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003867 Py_Type(self)->tp_free((PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00003868}
3869
3870/*
3871 * Indirect access to tzinfo methods.
3872 */
3873
Tim Peters2a799bf2002-12-16 20:18:38 +00003874/* These are all METH_NOARGS, so don't need to check the arglist. */
3875static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003876datetime_utcoffset(PyDateTime_DateTime *self, PyObject *unused) {
3877 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
3878 "utcoffset", (PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00003879}
3880
3881static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003882datetime_dst(PyDateTime_DateTime *self, PyObject *unused) {
3883 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
3884 "dst", (PyObject *)self);
Tim Peters855fe882002-12-22 03:43:39 +00003885}
3886
3887static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003888datetime_tzname(PyDateTime_DateTime *self, PyObject *unused) {
3889 return call_tzname(HASTZINFO(self) ? self->tzinfo : Py_None,
3890 (PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00003891}
3892
3893/*
Tim Petersa9bc1682003-01-11 03:39:11 +00003894 * datetime arithmetic.
Tim Peters2a799bf2002-12-16 20:18:38 +00003895 */
3896
Tim Petersa9bc1682003-01-11 03:39:11 +00003897/* factor must be 1 (to add) or -1 (to subtract). The result inherits
3898 * the tzinfo state of date.
Tim Peters2a799bf2002-12-16 20:18:38 +00003899 */
3900static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003901add_datetime_timedelta(PyDateTime_DateTime *date, PyDateTime_Delta *delta,
3902 int factor)
Tim Peters2a799bf2002-12-16 20:18:38 +00003903{
Tim Petersa9bc1682003-01-11 03:39:11 +00003904 /* Note that the C-level additions can't overflow, because of
3905 * invariant bounds on the member values.
3906 */
3907 int year = GET_YEAR(date);
3908 int month = GET_MONTH(date);
3909 int day = GET_DAY(date) + GET_TD_DAYS(delta) * factor;
3910 int hour = DATE_GET_HOUR(date);
3911 int minute = DATE_GET_MINUTE(date);
3912 int second = DATE_GET_SECOND(date) + GET_TD_SECONDS(delta) * factor;
3913 int microsecond = DATE_GET_MICROSECOND(date) +
3914 GET_TD_MICROSECONDS(delta) * factor;
Tim Peters2a799bf2002-12-16 20:18:38 +00003915
Tim Petersa9bc1682003-01-11 03:39:11 +00003916 assert(factor == 1 || factor == -1);
3917 if (normalize_datetime(&year, &month, &day,
3918 &hour, &minute, &second, &microsecond) < 0)
3919 return NULL;
3920 else
3921 return new_datetime(year, month, day,
3922 hour, minute, second, microsecond,
3923 HASTZINFO(date) ? date->tzinfo : Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00003924}
3925
3926static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003927datetime_add(PyObject *left, PyObject *right)
Tim Peters2a799bf2002-12-16 20:18:38 +00003928{
Tim Petersa9bc1682003-01-11 03:39:11 +00003929 if (PyDateTime_Check(left)) {
3930 /* datetime + ??? */
3931 if (PyDelta_Check(right))
3932 /* datetime + delta */
3933 return add_datetime_timedelta(
3934 (PyDateTime_DateTime *)left,
3935 (PyDateTime_Delta *)right,
3936 1);
3937 }
3938 else if (PyDelta_Check(left)) {
3939 /* delta + datetime */
3940 return add_datetime_timedelta((PyDateTime_DateTime *) right,
3941 (PyDateTime_Delta *) left,
3942 1);
3943 }
3944 Py_INCREF(Py_NotImplemented);
3945 return Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00003946}
3947
3948static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003949datetime_subtract(PyObject *left, PyObject *right)
Tim Peters2a799bf2002-12-16 20:18:38 +00003950{
3951 PyObject *result = Py_NotImplemented;
3952
3953 if (PyDateTime_Check(left)) {
3954 /* datetime - ??? */
3955 if (PyDateTime_Check(right)) {
3956 /* datetime - datetime */
3957 naivety n1, n2;
3958 int offset1, offset2;
Tim Petersa9bc1682003-01-11 03:39:11 +00003959 int delta_d, delta_s, delta_us;
Tim Peters2a799bf2002-12-16 20:18:38 +00003960
Tim Peterse39a80c2002-12-30 21:28:52 +00003961 if (classify_two_utcoffsets(left, &offset1, &n1, left,
3962 right, &offset2, &n2,
3963 right) < 0)
Tim Peters00237032002-12-27 02:21:51 +00003964 return NULL;
Tim Peters8702d5f2002-12-27 02:26:16 +00003965 assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
Tim Peters2a799bf2002-12-16 20:18:38 +00003966 if (n1 != n2) {
3967 PyErr_SetString(PyExc_TypeError,
3968 "can't subtract offset-naive and "
3969 "offset-aware datetimes");
3970 return NULL;
3971 }
Tim Petersa9bc1682003-01-11 03:39:11 +00003972 delta_d = ymd_to_ord(GET_YEAR(left),
3973 GET_MONTH(left),
3974 GET_DAY(left)) -
3975 ymd_to_ord(GET_YEAR(right),
3976 GET_MONTH(right),
3977 GET_DAY(right));
3978 /* These can't overflow, since the values are
3979 * normalized. At most this gives the number of
3980 * seconds in one day.
3981 */
3982 delta_s = (DATE_GET_HOUR(left) -
3983 DATE_GET_HOUR(right)) * 3600 +
3984 (DATE_GET_MINUTE(left) -
3985 DATE_GET_MINUTE(right)) * 60 +
3986 (DATE_GET_SECOND(left) -
3987 DATE_GET_SECOND(right));
3988 delta_us = DATE_GET_MICROSECOND(left) -
3989 DATE_GET_MICROSECOND(right);
Tim Peters2a799bf2002-12-16 20:18:38 +00003990 /* (left - offset1) - (right - offset2) =
3991 * (left - right) + (offset2 - offset1)
3992 */
Tim Petersa9bc1682003-01-11 03:39:11 +00003993 delta_s += (offset2 - offset1) * 60;
3994 result = new_delta(delta_d, delta_s, delta_us, 1);
Tim Peters2a799bf2002-12-16 20:18:38 +00003995 }
3996 else if (PyDelta_Check(right)) {
Tim Petersa9bc1682003-01-11 03:39:11 +00003997 /* datetime - delta */
3998 result = add_datetime_timedelta(
Tim Peters2a799bf2002-12-16 20:18:38 +00003999 (PyDateTime_DateTime *)left,
Tim Petersa9bc1682003-01-11 03:39:11 +00004000 (PyDateTime_Delta *)right,
4001 -1);
Tim Peters2a799bf2002-12-16 20:18:38 +00004002 }
4003 }
4004
4005 if (result == Py_NotImplemented)
4006 Py_INCREF(result);
4007 return result;
4008}
4009
4010/* Various ways to turn a datetime into a string. */
4011
4012static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004013datetime_repr(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004014{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004015 const char *type_name = Py_Type(self)->tp_name;
Tim Petersa9bc1682003-01-11 03:39:11 +00004016 PyObject *baserepr;
Tim Peters2a799bf2002-12-16 20:18:38 +00004017
Tim Petersa9bc1682003-01-11 03:39:11 +00004018 if (DATE_GET_MICROSECOND(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, %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 DATE_GET_MICROSECOND(self));
4026 }
4027 else if (DATE_GET_SECOND(self)) {
Walter Dörwald7569dfe2007-05-19 21:49:49 +00004028 baserepr = PyUnicode_FromFormat(
Tim Petersa9bc1682003-01-11 03:39:11 +00004029 "%s(%d, %d, %d, %d, %d, %d)",
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004030 type_name,
Tim Petersa9bc1682003-01-11 03:39:11 +00004031 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4032 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4033 DATE_GET_SECOND(self));
4034 }
4035 else {
Walter Dörwald7569dfe2007-05-19 21:49:49 +00004036 baserepr = PyUnicode_FromFormat(
Tim Petersa9bc1682003-01-11 03:39:11 +00004037 "%s(%d, %d, %d, %d, %d)",
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004038 type_name,
Tim Petersa9bc1682003-01-11 03:39:11 +00004039 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4040 DATE_GET_HOUR(self), DATE_GET_MINUTE(self));
4041 }
Tim Petersa9bc1682003-01-11 03:39:11 +00004042 if (baserepr == NULL || ! HASTZINFO(self))
4043 return baserepr;
Tim Peters2a799bf2002-12-16 20:18:38 +00004044 return append_keyword_tzinfo(baserepr, self->tzinfo);
4045}
4046
Tim Petersa9bc1682003-01-11 03:39:11 +00004047static PyObject *
4048datetime_str(PyDateTime_DateTime *self)
4049{
4050 return PyObject_CallMethod((PyObject *)self, "isoformat", "(s)", " ");
4051}
Tim Peters2a799bf2002-12-16 20:18:38 +00004052
4053static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004054datetime_isoformat(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00004055{
Walter Dörwaldbc1f8862007-06-20 11:02:38 +00004056 int sep = 'T';
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00004057 static char *keywords[] = {"sep", NULL};
Tim Petersa9bc1682003-01-11 03:39:11 +00004058 char buffer[100];
Tim Petersa9bc1682003-01-11 03:39:11 +00004059 PyObject *result;
Walter Dörwaldbafa1372007-05-31 17:50:48 +00004060 int us = DATE_GET_MICROSECOND(self);
Tim Peters2a799bf2002-12-16 20:18:38 +00004061
Walter Dörwaldd0941302007-07-01 21:58:22 +00004062 if (!PyArg_ParseTupleAndKeywords(args, kw, "|C:isoformat", keywords, &sep))
Tim Petersa9bc1682003-01-11 03:39:11 +00004063 return NULL;
Walter Dörwaldbafa1372007-05-31 17:50:48 +00004064 if (us)
4065 result = PyUnicode_FromFormat("%04d-%02d-%02d%c%02d:%02d:%02d.%06d",
4066 GET_YEAR(self), GET_MONTH(self),
4067 GET_DAY(self), (int)sep,
4068 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4069 DATE_GET_SECOND(self), us);
4070 else
4071 result = PyUnicode_FromFormat("%04d-%02d-%02d%c%02d:%02d:%02d",
4072 GET_YEAR(self), GET_MONTH(self),
4073 GET_DAY(self), (int)sep,
4074 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4075 DATE_GET_SECOND(self));
4076
4077 if (!result || !HASTZINFO(self))
Tim Peters2a799bf2002-12-16 20:18:38 +00004078 return result;
4079
4080 /* We need to append the UTC offset. */
Tim Petersa9bc1682003-01-11 03:39:11 +00004081 if (format_utcoffset(buffer, sizeof(buffer), ":", self->tzinfo,
Tim Peters2a799bf2002-12-16 20:18:38 +00004082 (PyObject *)self) < 0) {
4083 Py_DECREF(result);
4084 return NULL;
4085 }
Walter Dörwaldbafa1372007-05-31 17:50:48 +00004086 PyUnicode_AppendAndDel(&result, PyUnicode_FromString(buffer));
Tim Peters2a799bf2002-12-16 20:18:38 +00004087 return result;
4088}
4089
Tim Petersa9bc1682003-01-11 03:39:11 +00004090static PyObject *
4091datetime_ctime(PyDateTime_DateTime *self)
4092{
4093 return format_ctime((PyDateTime_Date *)self,
4094 DATE_GET_HOUR(self),
4095 DATE_GET_MINUTE(self),
4096 DATE_GET_SECOND(self));
4097}
4098
Tim Peters2a799bf2002-12-16 20:18:38 +00004099/* Miscellaneous methods. */
4100
Tim Petersa9bc1682003-01-11 03:39:11 +00004101static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00004102datetime_richcompare(PyObject *self, PyObject *other, int op)
Tim Petersa9bc1682003-01-11 03:39:11 +00004103{
4104 int diff;
4105 naivety n1, n2;
4106 int offset1, offset2;
4107
4108 if (! PyDateTime_Check(other)) {
Guido van Rossum19960592006-08-24 17:29:38 +00004109 if (PyDate_Check(other)) {
4110 /* Prevent invocation of date_richcompare. We want to
4111 return NotImplemented here to give the other object
4112 a chance. But since DateTime is a subclass of
4113 Date, if the other object is a Date, it would
4114 compute an ordering based on the date part alone,
4115 and we don't want that. So force unequal or
4116 uncomparable here in that case. */
4117 if (op == Py_EQ)
4118 Py_RETURN_FALSE;
4119 if (op == Py_NE)
4120 Py_RETURN_TRUE;
4121 return cmperror(self, other);
Tim Peters8d81a012003-01-24 22:36:34 +00004122 }
Guido van Rossum19960592006-08-24 17:29:38 +00004123 Py_INCREF(Py_NotImplemented);
4124 return Py_NotImplemented;
Tim Petersa9bc1682003-01-11 03:39:11 +00004125 }
4126
Guido van Rossum19960592006-08-24 17:29:38 +00004127 if (classify_two_utcoffsets(self, &offset1, &n1, self,
4128 other, &offset2, &n2, other) < 0)
Tim Petersa9bc1682003-01-11 03:39:11 +00004129 return NULL;
4130 assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
4131 /* If they're both naive, or both aware and have the same offsets,
4132 * we get off cheap. Note that if they're both naive, offset1 ==
4133 * offset2 == 0 at this point.
4134 */
4135 if (n1 == n2 && offset1 == offset2) {
Guido van Rossum19960592006-08-24 17:29:38 +00004136 diff = memcmp(((PyDateTime_DateTime *)self)->data,
4137 ((PyDateTime_DateTime *)other)->data,
Tim Petersa9bc1682003-01-11 03:39:11 +00004138 _PyDateTime_DATETIME_DATASIZE);
4139 return diff_to_bool(diff, op);
4140 }
4141
4142 if (n1 == OFFSET_AWARE && n2 == OFFSET_AWARE) {
4143 PyDateTime_Delta *delta;
4144
4145 assert(offset1 != offset2); /* else last "if" handled it */
4146 delta = (PyDateTime_Delta *)datetime_subtract((PyObject *)self,
4147 other);
4148 if (delta == NULL)
4149 return NULL;
4150 diff = GET_TD_DAYS(delta);
4151 if (diff == 0)
4152 diff = GET_TD_SECONDS(delta) |
4153 GET_TD_MICROSECONDS(delta);
4154 Py_DECREF(delta);
4155 return diff_to_bool(diff, op);
4156 }
4157
4158 assert(n1 != n2);
4159 PyErr_SetString(PyExc_TypeError,
4160 "can't compare offset-naive and "
4161 "offset-aware datetimes");
4162 return NULL;
4163}
4164
4165static long
4166datetime_hash(PyDateTime_DateTime *self)
4167{
4168 if (self->hashcode == -1) {
4169 naivety n;
4170 int offset;
4171 PyObject *temp;
4172
4173 n = classify_utcoffset((PyObject *)self, (PyObject *)self,
4174 &offset);
4175 assert(n != OFFSET_UNKNOWN);
4176 if (n == OFFSET_ERROR)
4177 return -1;
4178
4179 /* Reduce this to a hash of another object. */
Guido van Rossumfd53fd62007-08-24 04:05:13 +00004180 if (n == OFFSET_NAIVE) {
4181 self->hashcode = generic_hash(
4182 (unsigned char *)self->data, _PyDateTime_DATETIME_DATASIZE);
4183 return self->hashcode;
4184 }
Tim Petersa9bc1682003-01-11 03:39:11 +00004185 else {
4186 int days;
4187 int seconds;
4188
4189 assert(n == OFFSET_AWARE);
4190 assert(HASTZINFO(self));
4191 days = ymd_to_ord(GET_YEAR(self),
4192 GET_MONTH(self),
4193 GET_DAY(self));
4194 seconds = DATE_GET_HOUR(self) * 3600 +
4195 (DATE_GET_MINUTE(self) - offset) * 60 +
4196 DATE_GET_SECOND(self);
4197 temp = new_delta(days,
4198 seconds,
4199 DATE_GET_MICROSECOND(self),
4200 1);
4201 }
4202 if (temp != NULL) {
4203 self->hashcode = PyObject_Hash(temp);
4204 Py_DECREF(temp);
4205 }
4206 }
4207 return self->hashcode;
4208}
Tim Peters2a799bf2002-12-16 20:18:38 +00004209
4210static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004211datetime_replace(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters12bf3392002-12-24 05:41:27 +00004212{
4213 PyObject *clone;
4214 PyObject *tuple;
4215 int y = GET_YEAR(self);
4216 int m = GET_MONTH(self);
4217 int d = GET_DAY(self);
4218 int hh = DATE_GET_HOUR(self);
4219 int mm = DATE_GET_MINUTE(self);
4220 int ss = DATE_GET_SECOND(self);
4221 int us = DATE_GET_MICROSECOND(self);
Tim Petersa9bc1682003-01-11 03:39:11 +00004222 PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
Tim Peters12bf3392002-12-24 05:41:27 +00004223
4224 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiiiiO:replace",
Tim Petersa9bc1682003-01-11 03:39:11 +00004225 datetime_kws,
Tim Peters12bf3392002-12-24 05:41:27 +00004226 &y, &m, &d, &hh, &mm, &ss, &us,
4227 &tzinfo))
4228 return NULL;
4229 tuple = Py_BuildValue("iiiiiiiO", y, m, d, hh, mm, ss, us, tzinfo);
4230 if (tuple == NULL)
4231 return NULL;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004232 clone = datetime_new(Py_Type(self), tuple, NULL);
Tim Peters12bf3392002-12-24 05:41:27 +00004233 Py_DECREF(tuple);
4234 return clone;
4235}
4236
4237static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004238datetime_astimezone(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters80475bb2002-12-25 07:40:55 +00004239{
Tim Peters52dcce22003-01-23 16:36:11 +00004240 int y, m, d, hh, mm, ss, us;
Tim Peters521fc152002-12-31 17:36:56 +00004241 PyObject *result;
Tim Peters52dcce22003-01-23 16:36:11 +00004242 int offset, none;
Tim Peters521fc152002-12-31 17:36:56 +00004243
Tim Peters80475bb2002-12-25 07:40:55 +00004244 PyObject *tzinfo;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00004245 static char *keywords[] = {"tz", NULL};
Tim Peters80475bb2002-12-25 07:40:55 +00004246
Tim Peters52dcce22003-01-23 16:36:11 +00004247 if (! PyArg_ParseTupleAndKeywords(args, kw, "O!:astimezone", keywords,
4248 &PyDateTime_TZInfoType, &tzinfo))
Tim Peters80475bb2002-12-25 07:40:55 +00004249 return NULL;
4250
Tim Peters52dcce22003-01-23 16:36:11 +00004251 if (!HASTZINFO(self) || self->tzinfo == Py_None)
4252 goto NeedAware;
Tim Peters521fc152002-12-31 17:36:56 +00004253
Tim Peters52dcce22003-01-23 16:36:11 +00004254 /* Conversion to self's own time zone is a NOP. */
4255 if (self->tzinfo == tzinfo) {
4256 Py_INCREF(self);
4257 return (PyObject *)self;
Tim Peters710fb152003-01-02 19:35:54 +00004258 }
Tim Peters521fc152002-12-31 17:36:56 +00004259
Tim Peters52dcce22003-01-23 16:36:11 +00004260 /* Convert self to UTC. */
4261 offset = call_utcoffset(self->tzinfo, (PyObject *)self, &none);
4262 if (offset == -1 && PyErr_Occurred())
4263 return NULL;
4264 if (none)
4265 goto NeedAware;
Tim Petersf3615152003-01-01 21:51:37 +00004266
Tim Peters52dcce22003-01-23 16:36:11 +00004267 y = GET_YEAR(self);
4268 m = GET_MONTH(self);
4269 d = GET_DAY(self);
4270 hh = DATE_GET_HOUR(self);
4271 mm = DATE_GET_MINUTE(self);
4272 ss = DATE_GET_SECOND(self);
4273 us = DATE_GET_MICROSECOND(self);
4274
4275 mm -= offset;
Tim Petersf3615152003-01-01 21:51:37 +00004276 if ((mm < 0 || mm >= 60) &&
4277 normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
Tim Peters52dcce22003-01-23 16:36:11 +00004278 return NULL;
4279
4280 /* Attach new tzinfo and let fromutc() do the rest. */
4281 result = new_datetime(y, m, d, hh, mm, ss, us, tzinfo);
4282 if (result != NULL) {
4283 PyObject *temp = result;
4284
4285 result = PyObject_CallMethod(tzinfo, "fromutc", "O", temp);
4286 Py_DECREF(temp);
4287 }
Tim Petersadf64202003-01-04 06:03:15 +00004288 return result;
Tim Peters521fc152002-12-31 17:36:56 +00004289
Tim Peters52dcce22003-01-23 16:36:11 +00004290NeedAware:
4291 PyErr_SetString(PyExc_ValueError, "astimezone() cannot be applied to "
4292 "a naive datetime");
Tim Peters521fc152002-12-31 17:36:56 +00004293 return NULL;
Tim Peters80475bb2002-12-25 07:40:55 +00004294}
4295
4296static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004297datetime_timetuple(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004298{
4299 int dstflag = -1;
4300
Tim Petersa9bc1682003-01-11 03:39:11 +00004301 if (HASTZINFO(self) && self->tzinfo != Py_None) {
Tim Peters2a799bf2002-12-16 20:18:38 +00004302 int none;
4303
4304 dstflag = call_dst(self->tzinfo, (PyObject *)self, &none);
4305 if (dstflag == -1 && PyErr_Occurred())
4306 return NULL;
4307
4308 if (none)
4309 dstflag = -1;
4310 else if (dstflag != 0)
4311 dstflag = 1;
4312
4313 }
4314 return build_struct_time(GET_YEAR(self),
4315 GET_MONTH(self),
4316 GET_DAY(self),
4317 DATE_GET_HOUR(self),
4318 DATE_GET_MINUTE(self),
4319 DATE_GET_SECOND(self),
4320 dstflag);
4321}
4322
4323static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004324datetime_getdate(PyDateTime_DateTime *self)
4325{
4326 return new_date(GET_YEAR(self),
4327 GET_MONTH(self),
4328 GET_DAY(self));
4329}
4330
4331static PyObject *
4332datetime_gettime(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 Py_None);
4339}
4340
4341static PyObject *
4342datetime_gettimetz(PyDateTime_DateTime *self)
4343{
4344 return new_time(DATE_GET_HOUR(self),
4345 DATE_GET_MINUTE(self),
4346 DATE_GET_SECOND(self),
4347 DATE_GET_MICROSECOND(self),
4348 HASTZINFO(self) ? self->tzinfo : Py_None);
4349}
4350
4351static PyObject *
4352datetime_utctimetuple(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004353{
4354 int y = GET_YEAR(self);
4355 int m = GET_MONTH(self);
4356 int d = GET_DAY(self);
4357 int hh = DATE_GET_HOUR(self);
4358 int mm = DATE_GET_MINUTE(self);
4359 int ss = DATE_GET_SECOND(self);
4360 int us = 0; /* microseconds are ignored in a timetuple */
4361 int offset = 0;
4362
Tim Petersa9bc1682003-01-11 03:39:11 +00004363 if (HASTZINFO(self) && self->tzinfo != Py_None) {
Tim Peters2a799bf2002-12-16 20:18:38 +00004364 int none;
4365
4366 offset = call_utcoffset(self->tzinfo, (PyObject *)self, &none);
4367 if (offset == -1 && PyErr_Occurred())
4368 return NULL;
4369 }
4370 /* Even if offset is 0, don't call timetuple() -- tm_isdst should be
4371 * 0 in a UTC timetuple regardless of what dst() says.
4372 */
4373 if (offset) {
4374 /* Subtract offset minutes & normalize. */
4375 int stat;
4376
4377 mm -= offset;
4378 stat = normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us);
4379 if (stat < 0) {
4380 /* At the edges, it's possible we overflowed
4381 * beyond MINYEAR or MAXYEAR.
4382 */
4383 if (PyErr_ExceptionMatches(PyExc_OverflowError))
4384 PyErr_Clear();
4385 else
4386 return NULL;
4387 }
4388 }
4389 return build_struct_time(y, m, d, hh, mm, ss, 0);
4390}
4391
Tim Peters371935f2003-02-01 01:52:50 +00004392/* Pickle support, a simple use of __reduce__. */
Tim Peters33e0f382003-01-10 02:05:14 +00004393
Tim Petersa9bc1682003-01-11 03:39:11 +00004394/* Let basestate be the non-tzinfo data string.
Tim Peters2a799bf2002-12-16 20:18:38 +00004395 * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
4396 * So it's a tuple in any (non-error) case.
Tim Petersb57f8f02003-02-01 02:54:15 +00004397 * __getstate__ isn't exposed.
Tim Peters2a799bf2002-12-16 20:18:38 +00004398 */
4399static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004400datetime_getstate(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004401{
4402 PyObject *basestate;
4403 PyObject *result = NULL;
4404
Martin v. Löwis10a60b32007-07-18 02:28:27 +00004405 basestate = PyBytes_FromStringAndSize((char *)self->data,
4406 _PyDateTime_DATETIME_DATASIZE);
Tim Peters2a799bf2002-12-16 20:18:38 +00004407 if (basestate != NULL) {
Tim Petersa9bc1682003-01-11 03:39:11 +00004408 if (! HASTZINFO(self) || self->tzinfo == Py_None)
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004409 result = PyTuple_Pack(1, basestate);
Tim Peters2a799bf2002-12-16 20:18:38 +00004410 else
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004411 result = PyTuple_Pack(2, basestate, self->tzinfo);
Tim Peters2a799bf2002-12-16 20:18:38 +00004412 Py_DECREF(basestate);
4413 }
4414 return result;
4415}
4416
4417static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00004418datetime_reduce(PyDateTime_DateTime *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00004419{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004420 return Py_BuildValue("(ON)", Py_Type(self), datetime_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00004421}
4422
Tim Petersa9bc1682003-01-11 03:39:11 +00004423static PyMethodDef datetime_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00004424
Tim Peters2a799bf2002-12-16 20:18:38 +00004425 /* Class methods: */
Tim Peters2a799bf2002-12-16 20:18:38 +00004426
Tim Petersa9bc1682003-01-11 03:39:11 +00004427 {"now", (PyCFunction)datetime_now,
Guido van Rossumd59da4b2007-05-22 18:11:13 +00004428 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
Neal Norwitz2fbe5372003-01-23 21:09:05 +00004429 PyDoc_STR("[tz] -> new datetime with tz's local day and time.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004430
Tim Petersa9bc1682003-01-11 03:39:11 +00004431 {"utcnow", (PyCFunction)datetime_utcnow,
4432 METH_NOARGS | METH_CLASS,
4433 PyDoc_STR("Return a new datetime representing UTC day and time.")},
4434
4435 {"fromtimestamp", (PyCFunction)datetime_fromtimestamp,
Guido van Rossumd59da4b2007-05-22 18:11:13 +00004436 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
Tim Peters2a44a8d2003-01-23 20:53:10 +00004437 PyDoc_STR("timestamp[, tz] -> tz's local time from POSIX timestamp.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004438
Tim Petersa9bc1682003-01-11 03:39:11 +00004439 {"utcfromtimestamp", (PyCFunction)datetime_utcfromtimestamp,
4440 METH_VARARGS | METH_CLASS,
4441 PyDoc_STR("timestamp -> UTC datetime from a POSIX timestamp "
4442 "(like time.time()).")},
4443
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004444 {"strptime", (PyCFunction)datetime_strptime,
4445 METH_VARARGS | METH_CLASS,
4446 PyDoc_STR("string, format -> new datetime parsed from a string "
4447 "(like time.strptime()).")},
4448
Tim Petersa9bc1682003-01-11 03:39:11 +00004449 {"combine", (PyCFunction)datetime_combine,
4450 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
4451 PyDoc_STR("date, time -> datetime with same date and time fields")},
4452
Tim Peters2a799bf2002-12-16 20:18:38 +00004453 /* Instance methods: */
Guido van Rossum177e41a2003-01-30 22:06:23 +00004454
Tim Petersa9bc1682003-01-11 03:39:11 +00004455 {"date", (PyCFunction)datetime_getdate, METH_NOARGS,
4456 PyDoc_STR("Return date object with same year, month and day.")},
4457
4458 {"time", (PyCFunction)datetime_gettime, METH_NOARGS,
4459 PyDoc_STR("Return time object with same time but with tzinfo=None.")},
4460
4461 {"timetz", (PyCFunction)datetime_gettimetz, METH_NOARGS,
4462 PyDoc_STR("Return time object with same time and tzinfo.")},
4463
4464 {"ctime", (PyCFunction)datetime_ctime, METH_NOARGS,
4465 PyDoc_STR("Return ctime() style string.")},
4466
4467 {"timetuple", (PyCFunction)datetime_timetuple, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004468 PyDoc_STR("Return time tuple, compatible with time.localtime().")},
4469
Tim Petersa9bc1682003-01-11 03:39:11 +00004470 {"utctimetuple", (PyCFunction)datetime_utctimetuple, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004471 PyDoc_STR("Return UTC time tuple, compatible with time.localtime().")},
4472
Guido van Rossumd59da4b2007-05-22 18:11:13 +00004473 {"isoformat", (PyCFunction)datetime_isoformat, METH_VARARGS | METH_KEYWORDS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004474 PyDoc_STR("[sep] -> string in ISO 8601 format, "
4475 "YYYY-MM-DDTHH:MM:SS[.mmmmmm][+HH:MM].\n\n"
4476 "sep is used to separate the year from the time, and "
4477 "defaults to 'T'.")},
4478
Tim Petersa9bc1682003-01-11 03:39:11 +00004479 {"utcoffset", (PyCFunction)datetime_utcoffset, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004480 PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
4481
Tim Petersa9bc1682003-01-11 03:39:11 +00004482 {"tzname", (PyCFunction)datetime_tzname, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004483 PyDoc_STR("Return self.tzinfo.tzname(self).")},
4484
Tim Petersa9bc1682003-01-11 03:39:11 +00004485 {"dst", (PyCFunction)datetime_dst, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004486 PyDoc_STR("Return self.tzinfo.dst(self).")},
4487
Guido van Rossumd59da4b2007-05-22 18:11:13 +00004488 {"replace", (PyCFunction)datetime_replace, METH_VARARGS | METH_KEYWORDS,
Tim Petersa9bc1682003-01-11 03:39:11 +00004489 PyDoc_STR("Return datetime with new specified fields.")},
Tim Peters12bf3392002-12-24 05:41:27 +00004490
Guido van Rossumd59da4b2007-05-22 18:11:13 +00004491 {"astimezone", (PyCFunction)datetime_astimezone, METH_VARARGS | METH_KEYWORDS,
Tim Peters80475bb2002-12-25 07:40:55 +00004492 PyDoc_STR("tz -> convert to local time in new timezone tz\n")},
4493
Guido van Rossum177e41a2003-01-30 22:06:23 +00004494 {"__reduce__", (PyCFunction)datetime_reduce, METH_NOARGS,
4495 PyDoc_STR("__reduce__() -> (cls, state)")},
4496
Tim Peters2a799bf2002-12-16 20:18:38 +00004497 {NULL, NULL}
4498};
4499
Tim Petersa9bc1682003-01-11 03:39:11 +00004500static char datetime_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00004501PyDoc_STR("datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]])\n\
4502\n\
4503The year, month and day arguments are required. tzinfo may be None, or an\n\
4504instance of a tzinfo subclass. The remaining arguments may be ints or longs.\n");
Tim Peters2a799bf2002-12-16 20:18:38 +00004505
Tim Petersa9bc1682003-01-11 03:39:11 +00004506static PyNumberMethods datetime_as_number = {
4507 datetime_add, /* nb_add */
4508 datetime_subtract, /* nb_subtract */
Tim Peters2a799bf2002-12-16 20:18:38 +00004509 0, /* nb_multiply */
Tim Peters2a799bf2002-12-16 20:18:38 +00004510 0, /* nb_remainder */
4511 0, /* nb_divmod */
4512 0, /* nb_power */
4513 0, /* nb_negative */
4514 0, /* nb_positive */
4515 0, /* nb_absolute */
Jack Diederich4dafcc42006-11-28 19:15:13 +00004516 0, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00004517};
4518
Neal Norwitz227b5332006-03-22 09:28:35 +00004519static PyTypeObject PyDateTime_DateTimeType = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004520 PyVarObject_HEAD_INIT(NULL, 0)
Tim Peters0bf60bd2003-01-08 20:40:01 +00004521 "datetime.datetime", /* tp_name */
Tim Petersa9bc1682003-01-11 03:39:11 +00004522 sizeof(PyDateTime_DateTime), /* tp_basicsize */
Tim Peters2a799bf2002-12-16 20:18:38 +00004523 0, /* tp_itemsize */
Tim Petersa9bc1682003-01-11 03:39:11 +00004524 (destructor)datetime_dealloc, /* tp_dealloc */
Tim Peters2a799bf2002-12-16 20:18:38 +00004525 0, /* tp_print */
4526 0, /* tp_getattr */
4527 0, /* tp_setattr */
4528 0, /* tp_compare */
Tim Petersa9bc1682003-01-11 03:39:11 +00004529 (reprfunc)datetime_repr, /* tp_repr */
4530 &datetime_as_number, /* tp_as_number */
Tim Peters2a799bf2002-12-16 20:18:38 +00004531 0, /* tp_as_sequence */
4532 0, /* tp_as_mapping */
Tim Petersa9bc1682003-01-11 03:39:11 +00004533 (hashfunc)datetime_hash, /* tp_hash */
Tim Peters2a799bf2002-12-16 20:18:38 +00004534 0, /* tp_call */
Tim Petersa9bc1682003-01-11 03:39:11 +00004535 (reprfunc)datetime_str, /* tp_str */
Tim Peters2a799bf2002-12-16 20:18:38 +00004536 PyObject_GenericGetAttr, /* tp_getattro */
4537 0, /* tp_setattro */
4538 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00004539 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Petersa9bc1682003-01-11 03:39:11 +00004540 datetime_doc, /* tp_doc */
Tim Peters2a799bf2002-12-16 20:18:38 +00004541 0, /* tp_traverse */
4542 0, /* tp_clear */
Guido van Rossum19960592006-08-24 17:29:38 +00004543 datetime_richcompare, /* tp_richcompare */
Tim Peters2a799bf2002-12-16 20:18:38 +00004544 0, /* tp_weaklistoffset */
4545 0, /* tp_iter */
4546 0, /* tp_iternext */
Tim Petersa9bc1682003-01-11 03:39:11 +00004547 datetime_methods, /* tp_methods */
Tim Peters2a799bf2002-12-16 20:18:38 +00004548 0, /* tp_members */
Tim Petersa9bc1682003-01-11 03:39:11 +00004549 datetime_getset, /* tp_getset */
4550 &PyDateTime_DateType, /* tp_base */
Tim Peters2a799bf2002-12-16 20:18:38 +00004551 0, /* tp_dict */
4552 0, /* tp_descr_get */
4553 0, /* tp_descr_set */
4554 0, /* tp_dictoffset */
4555 0, /* tp_init */
Tim Petersa98924a2003-05-17 05:55:19 +00004556 datetime_alloc, /* tp_alloc */
Tim Petersa9bc1682003-01-11 03:39:11 +00004557 datetime_new, /* tp_new */
Tim Peters4c530132003-05-16 22:44:06 +00004558 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00004559};
4560
4561/* ---------------------------------------------------------------------------
4562 * Module methods and initialization.
4563 */
4564
4565static PyMethodDef module_methods[] = {
Tim Peters2a799bf2002-12-16 20:18:38 +00004566 {NULL, NULL}
4567};
4568
Tim Peters9ddf40b2004-06-20 22:41:32 +00004569/* C API. Clients get at this via PyDateTime_IMPORT, defined in
4570 * datetime.h.
4571 */
4572static PyDateTime_CAPI CAPI = {
4573 &PyDateTime_DateType,
4574 &PyDateTime_DateTimeType,
4575 &PyDateTime_TimeType,
4576 &PyDateTime_DeltaType,
4577 &PyDateTime_TZInfoType,
4578 new_date_ex,
4579 new_datetime_ex,
4580 new_time_ex,
4581 new_delta_ex,
4582 datetime_fromtimestamp,
4583 date_fromtimestamp
4584};
4585
4586
Tim Peters2a799bf2002-12-16 20:18:38 +00004587PyMODINIT_FUNC
4588initdatetime(void)
4589{
4590 PyObject *m; /* a module object */
4591 PyObject *d; /* its dict */
4592 PyObject *x;
4593
Tim Peters2a799bf2002-12-16 20:18:38 +00004594 m = Py_InitModule3("datetime", module_methods,
4595 "Fast implementation of the datetime type.");
Neal Norwitz1ac754f2006-01-19 06:09:39 +00004596 if (m == NULL)
4597 return;
Tim Peters2a799bf2002-12-16 20:18:38 +00004598
4599 if (PyType_Ready(&PyDateTime_DateType) < 0)
4600 return;
4601 if (PyType_Ready(&PyDateTime_DateTimeType) < 0)
4602 return;
4603 if (PyType_Ready(&PyDateTime_DeltaType) < 0)
4604 return;
4605 if (PyType_Ready(&PyDateTime_TimeType) < 0)
4606 return;
4607 if (PyType_Ready(&PyDateTime_TZInfoType) < 0)
4608 return;
Tim Peters2a799bf2002-12-16 20:18:38 +00004609
Tim Peters2a799bf2002-12-16 20:18:38 +00004610 /* timedelta values */
4611 d = PyDateTime_DeltaType.tp_dict;
4612
Tim Peters2a799bf2002-12-16 20:18:38 +00004613 x = new_delta(0, 0, 1, 0);
4614 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4615 return;
4616 Py_DECREF(x);
4617
4618 x = new_delta(-MAX_DELTA_DAYS, 0, 0, 0);
4619 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4620 return;
4621 Py_DECREF(x);
4622
4623 x = new_delta(MAX_DELTA_DAYS, 24*3600-1, 1000000-1, 0);
4624 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4625 return;
4626 Py_DECREF(x);
4627
4628 /* date values */
4629 d = PyDateTime_DateType.tp_dict;
4630
4631 x = new_date(1, 1, 1);
4632 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4633 return;
4634 Py_DECREF(x);
4635
4636 x = new_date(MAXYEAR, 12, 31);
4637 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4638 return;
4639 Py_DECREF(x);
4640
4641 x = new_delta(1, 0, 0, 0);
4642 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4643 return;
4644 Py_DECREF(x);
4645
Tim Peters37f39822003-01-10 03:49:02 +00004646 /* time values */
4647 d = PyDateTime_TimeType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00004648
Tim Peters37f39822003-01-10 03:49:02 +00004649 x = new_time(0, 0, 0, 0, Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004650 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4651 return;
4652 Py_DECREF(x);
4653
Tim Peters37f39822003-01-10 03:49:02 +00004654 x = new_time(23, 59, 59, 999999, Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004655 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4656 return;
4657 Py_DECREF(x);
4658
4659 x = new_delta(0, 0, 1, 0);
4660 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4661 return;
4662 Py_DECREF(x);
4663
Tim Petersa9bc1682003-01-11 03:39:11 +00004664 /* datetime values */
4665 d = PyDateTime_DateTimeType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00004666
Tim Petersa9bc1682003-01-11 03:39:11 +00004667 x = new_datetime(1, 1, 1, 0, 0, 0, 0, Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004668 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4669 return;
4670 Py_DECREF(x);
4671
Tim Petersa9bc1682003-01-11 03:39:11 +00004672 x = new_datetime(MAXYEAR, 12, 31, 23, 59, 59, 999999, Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004673 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4674 return;
4675 Py_DECREF(x);
4676
4677 x = new_delta(0, 0, 1, 0);
4678 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4679 return;
4680 Py_DECREF(x);
4681
Tim Peters2a799bf2002-12-16 20:18:38 +00004682 /* module initialization */
4683 PyModule_AddIntConstant(m, "MINYEAR", MINYEAR);
4684 PyModule_AddIntConstant(m, "MAXYEAR", MAXYEAR);
4685
4686 Py_INCREF(&PyDateTime_DateType);
4687 PyModule_AddObject(m, "date", (PyObject *) &PyDateTime_DateType);
4688
Tim Petersa9bc1682003-01-11 03:39:11 +00004689 Py_INCREF(&PyDateTime_DateTimeType);
4690 PyModule_AddObject(m, "datetime",
4691 (PyObject *)&PyDateTime_DateTimeType);
4692
4693 Py_INCREF(&PyDateTime_TimeType);
4694 PyModule_AddObject(m, "time", (PyObject *) &PyDateTime_TimeType);
4695
Tim Peters2a799bf2002-12-16 20:18:38 +00004696 Py_INCREF(&PyDateTime_DeltaType);
4697 PyModule_AddObject(m, "timedelta", (PyObject *) &PyDateTime_DeltaType);
4698
Tim Peters2a799bf2002-12-16 20:18:38 +00004699 Py_INCREF(&PyDateTime_TZInfoType);
4700 PyModule_AddObject(m, "tzinfo", (PyObject *) &PyDateTime_TZInfoType);
4701
Tim Peters9ddf40b2004-06-20 22:41:32 +00004702 x = PyCObject_FromVoidPtrAndDesc(&CAPI, (void*) DATETIME_API_MAGIC,
4703 NULL);
4704 if (x == NULL)
4705 return;
4706 PyModule_AddObject(m, "datetime_CAPI", x);
4707
Tim Peters2a799bf2002-12-16 20:18:38 +00004708 /* A 4-year cycle has an extra leap day over what we'd get from
4709 * pasting together 4 single years.
4710 */
4711 assert(DI4Y == 4 * 365 + 1);
4712 assert(DI4Y == days_before_year(4+1));
4713
4714 /* Similarly, a 400-year cycle has an extra leap day over what we'd
4715 * get from pasting together 4 100-year cycles.
4716 */
4717 assert(DI400Y == 4 * DI100Y + 1);
4718 assert(DI400Y == days_before_year(400+1));
4719
4720 /* OTOH, a 100-year cycle has one fewer leap day than we'd get from
4721 * pasting together 25 4-year cycles.
4722 */
4723 assert(DI100Y == 25 * DI4Y - 1);
4724 assert(DI100Y == days_before_year(100+1));
4725
4726 us_per_us = PyInt_FromLong(1);
4727 us_per_ms = PyInt_FromLong(1000);
4728 us_per_second = PyInt_FromLong(1000000);
4729 us_per_minute = PyInt_FromLong(60000000);
4730 seconds_per_day = PyInt_FromLong(24 * 3600);
4731 if (us_per_us == NULL || us_per_ms == NULL || us_per_second == NULL ||
4732 us_per_minute == NULL || seconds_per_day == NULL)
4733 return;
4734
4735 /* The rest are too big for 32-bit ints, but even
4736 * us_per_week fits in 40 bits, so doubles should be exact.
4737 */
4738 us_per_hour = PyLong_FromDouble(3600000000.0);
4739 us_per_day = PyLong_FromDouble(86400000000.0);
4740 us_per_week = PyLong_FromDouble(604800000000.0);
4741 if (us_per_hour == NULL || us_per_day == NULL || us_per_week == NULL)
4742 return;
4743}
Tim Petersf3615152003-01-01 21:51:37 +00004744
4745/* ---------------------------------------------------------------------------
Tim Petersa9bc1682003-01-11 03:39:11 +00004746Some time zone algebra. For a datetime x, let
Tim Petersf3615152003-01-01 21:51:37 +00004747 x.n = x stripped of its timezone -- its naive time.
4748 x.o = x.utcoffset(), and assuming that doesn't raise an exception or
4749 return None
4750 x.d = x.dst(), and assuming that doesn't raise an exception or
4751 return None
4752 x.s = x's standard offset, x.o - x.d
4753
4754Now some derived rules, where k is a duration (timedelta).
4755
47561. x.o = x.s + x.d
4757 This follows from the definition of x.s.
4758
Tim Petersc5dc4da2003-01-02 17:55:03 +000047592. If x and y have the same tzinfo member, x.s = y.s.
Tim Petersf3615152003-01-01 21:51:37 +00004760 This is actually a requirement, an assumption we need to make about
4761 sane tzinfo classes.
4762
47633. The naive UTC time corresponding to x is x.n - x.o.
4764 This is again a requirement for a sane tzinfo class.
4765
47664. (x+k).s = x.s
Tim Peters8bb5ad22003-01-24 02:44:45 +00004767 This follows from #2, and that datimetimetz+timedelta preserves tzinfo.
Tim Petersf3615152003-01-01 21:51:37 +00004768
Tim Petersc5dc4da2003-01-02 17:55:03 +000047695. (x+k).n = x.n + k
Tim Petersf3615152003-01-01 21:51:37 +00004770 Again follows from how arithmetic is defined.
4771
Tim Peters8bb5ad22003-01-24 02:44:45 +00004772Now we can explain tz.fromutc(x). Let's assume it's an interesting case
Tim Petersf3615152003-01-01 21:51:37 +00004773(meaning that the various tzinfo methods exist, and don't blow up or return
4774None when called).
4775
Tim Petersa9bc1682003-01-11 03:39:11 +00004776The function wants to return a datetime y with timezone tz, equivalent to x.
Tim Peters8bb5ad22003-01-24 02:44:45 +00004777x is already in UTC.
Tim Petersf3615152003-01-01 21:51:37 +00004778
4779By #3, we want
4780
Tim Peters8bb5ad22003-01-24 02:44:45 +00004781 y.n - y.o = x.n [1]
Tim Petersf3615152003-01-01 21:51:37 +00004782
4783The algorithm starts by attaching tz to x.n, and calling that y. So
4784x.n = y.n at the start. Then it wants to add a duration k to y, so that [1]
4785becomes true; in effect, we want to solve [2] for k:
4786
Tim Peters8bb5ad22003-01-24 02:44:45 +00004787 (y+k).n - (y+k).o = x.n [2]
Tim Petersf3615152003-01-01 21:51:37 +00004788
4789By #1, this is the same as
4790
Tim Peters8bb5ad22003-01-24 02:44:45 +00004791 (y+k).n - ((y+k).s + (y+k).d) = x.n [3]
Tim Petersf3615152003-01-01 21:51:37 +00004792
4793By #5, (y+k).n = y.n + k, which equals x.n + k because x.n=y.n at the start.
4794Substituting that into [3],
4795
Tim Peters8bb5ad22003-01-24 02:44:45 +00004796 x.n + k - (y+k).s - (y+k).d = x.n; the x.n terms cancel, leaving
4797 k - (y+k).s - (y+k).d = 0; rearranging,
4798 k = (y+k).s - (y+k).d; by #4, (y+k).s == y.s, so
4799 k = y.s - (y+k).d
Tim Petersf3615152003-01-01 21:51:37 +00004800
Tim Peters8bb5ad22003-01-24 02:44:45 +00004801On the RHS, (y+k).d can't be computed directly, but y.s can be, and we
4802approximate k by ignoring the (y+k).d term at first. Note that k can't be
4803very large, since all offset-returning methods return a duration of magnitude
4804less than 24 hours. For that reason, if y is firmly in std time, (y+k).d must
4805be 0, so ignoring it has no consequence then.
Tim Petersf3615152003-01-01 21:51:37 +00004806
4807In any case, the new value is
4808
Tim Peters8bb5ad22003-01-24 02:44:45 +00004809 z = y + y.s [4]
Tim Petersf3615152003-01-01 21:51:37 +00004810
Tim Peters8bb5ad22003-01-24 02:44:45 +00004811It's helpful to step back at look at [4] from a higher level: it's simply
4812mapping from UTC to tz's standard time.
Tim Petersc5dc4da2003-01-02 17:55:03 +00004813
4814At this point, if
4815
Tim Peters8bb5ad22003-01-24 02:44:45 +00004816 z.n - z.o = x.n [5]
Tim Petersc5dc4da2003-01-02 17:55:03 +00004817
4818we have an equivalent time, and are almost done. The insecurity here is
Tim Petersf3615152003-01-01 21:51:37 +00004819at the start of daylight time. Picture US Eastern for concreteness. The wall
4820time 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 +00004821sense then. The docs ask that an Eastern tzinfo class consider such a time to
4822be EDT (because it's "after 2"), which is a redundant spelling of 1:MM EST
4823on the day DST starts. We want to return the 1:MM EST spelling because that's
Tim Petersf3615152003-01-01 21:51:37 +00004824the only spelling that makes sense on the local wall clock.
4825
Tim Petersc5dc4da2003-01-02 17:55:03 +00004826In fact, if [5] holds at this point, we do have the standard-time spelling,
4827but that takes a bit of proof. We first prove a stronger result. What's the
4828difference between the LHS and RHS of [5]? Let
Tim Petersf3615152003-01-01 21:51:37 +00004829
Tim Peters8bb5ad22003-01-24 02:44:45 +00004830 diff = x.n - (z.n - z.o) [6]
Tim Petersf3615152003-01-01 21:51:37 +00004831
Tim Petersc5dc4da2003-01-02 17:55:03 +00004832Now
4833 z.n = by [4]
Tim Peters8bb5ad22003-01-24 02:44:45 +00004834 (y + y.s).n = by #5
4835 y.n + y.s = since y.n = x.n
4836 x.n + y.s = since z and y are have the same tzinfo member,
4837 y.s = z.s by #2
4838 x.n + z.s
Tim Petersf3615152003-01-01 21:51:37 +00004839
Tim Petersc5dc4da2003-01-02 17:55:03 +00004840Plugging that back into [6] gives
Tim Petersf3615152003-01-01 21:51:37 +00004841
Tim Petersc5dc4da2003-01-02 17:55:03 +00004842 diff =
Tim Peters8bb5ad22003-01-24 02:44:45 +00004843 x.n - ((x.n + z.s) - z.o) = expanding
4844 x.n - x.n - z.s + z.o = cancelling
4845 - z.s + z.o = by #2
Tim Petersc5dc4da2003-01-02 17:55:03 +00004846 z.d
Tim Petersf3615152003-01-01 21:51:37 +00004847
Tim Petersc5dc4da2003-01-02 17:55:03 +00004848So diff = z.d.
Tim Petersf3615152003-01-01 21:51:37 +00004849
Tim Petersc5dc4da2003-01-02 17:55:03 +00004850If [5] is true now, diff = 0, so z.d = 0 too, and we have the standard-time
Tim Peters8bb5ad22003-01-24 02:44:45 +00004851spelling we wanted in the endcase described above. We're done. Contrarily,
4852if z.d = 0, then we have a UTC equivalent, and are also done.
Tim Petersf3615152003-01-01 21:51:37 +00004853
Tim Petersc5dc4da2003-01-02 17:55:03 +00004854If [5] is not true now, diff = z.d != 0, and z.d is the offset we need to
4855add to z (in effect, z is in tz's standard time, and we need to shift the
Tim Peters8bb5ad22003-01-24 02:44:45 +00004856local clock into tz's daylight time).
Tim Petersf3615152003-01-01 21:51:37 +00004857
Tim Petersc5dc4da2003-01-02 17:55:03 +00004858Let
Tim Petersf3615152003-01-01 21:51:37 +00004859
Tim Peters4fede1a2003-01-04 00:26:59 +00004860 z' = z + z.d = z + diff [7]
Tim Petersc3bb26a2003-01-02 03:14:59 +00004861
Tim Peters4fede1a2003-01-04 00:26:59 +00004862and we can again ask whether
Tim Petersc3bb26a2003-01-02 03:14:59 +00004863
Tim Peters8bb5ad22003-01-24 02:44:45 +00004864 z'.n - z'.o = x.n [8]
Tim Petersc3bb26a2003-01-02 03:14:59 +00004865
Tim Peters8bb5ad22003-01-24 02:44:45 +00004866If so, we're done. If not, the tzinfo class is insane, according to the
4867assumptions we've made. This also requires a bit of proof. As before, let's
4868compute the difference between the LHS and RHS of [8] (and skipping some of
4869the justifications for the kinds of substitutions we've done several times
4870already):
Tim Peters4fede1a2003-01-04 00:26:59 +00004871
Tim Peters8bb5ad22003-01-24 02:44:45 +00004872 diff' = x.n - (z'.n - z'.o) = replacing z'.n via [7]
4873 x.n - (z.n + diff - z'.o) = replacing diff via [6]
4874 x.n - (z.n + x.n - (z.n - z.o) - z'.o) =
4875 x.n - z.n - x.n + z.n - z.o + z'.o = cancel x.n
4876 - z.n + z.n - z.o + z'.o = cancel z.n
Tim Peters4fede1a2003-01-04 00:26:59 +00004877 - z.o + z'.o = #1 twice
4878 -z.s - z.d + z'.s + z'.d = z and z' have same tzinfo
4879 z'.d - z.d
4880
4881So 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 +00004882we've found the UTC-equivalent so are done. In fact, we stop with [7] and
4883return z', not bothering to compute z'.d.
Tim Peters4fede1a2003-01-04 00:26:59 +00004884
Tim Peters8bb5ad22003-01-24 02:44:45 +00004885How could z.d and z'd differ? z' = z + z.d [7], so merely moving z' by
4886a dst() offset, and starting *from* a time already in DST (we know z.d != 0),
4887would have to change the result dst() returns: we start in DST, and moving
4888a little further into it takes us out of DST.
Tim Peters4fede1a2003-01-04 00:26:59 +00004889
Tim Peters8bb5ad22003-01-24 02:44:45 +00004890There isn't a sane case where this can happen. The closest it gets is at
4891the end of DST, where there's an hour in UTC with no spelling in a hybrid
4892tzinfo class. In US Eastern, that's 5:MM UTC = 0:MM EST = 1:MM EDT. During
4893that hour, on an Eastern clock 1:MM is taken as being in standard time (6:MM
4894UTC) because the docs insist on that, but 0:MM is taken as being in daylight
4895time (4:MM UTC). There is no local time mapping to 5:MM UTC. The local
4896clock jumps from 1:59 back to 1:00 again, and repeats the 1:MM hour in
4897standard time. Since that's what the local clock *does*, we want to map both
4898UTC hours 5:MM and 6:MM to 1:MM Eastern. The result is ambiguous
Tim Peters4fede1a2003-01-04 00:26:59 +00004899in local time, but so it goes -- it's the way the local clock works.
4900
Tim Peters8bb5ad22003-01-24 02:44:45 +00004901When x = 5:MM UTC is the input to this algorithm, x.o=0, y.o=-5 and y.d=0,
4902so z=0:MM. z.d=60 (minutes) then, so [5] doesn't hold and we keep going.
4903z' = 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 +00004904(correctly) concludes that z' is not UTC-equivalent to x.
4905
4906Because we know z.d said z was in daylight time (else [5] would have held and
4907we would have stopped then), and we know z.d != z'.d (else [8] would have held
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +00004908and we would have stopped then), and there are only 2 possible values dst() can
Tim Peters4fede1a2003-01-04 00:26:59 +00004909return in Eastern, it follows that z'.d must be 0 (which it is in the example,
4910but the reasoning doesn't depend on the example -- it depends on there being
4911two possible dst() outcomes, one zero and the other non-zero). Therefore
Tim Peters8bb5ad22003-01-24 02:44:45 +00004912z' must be in standard time, and is the spelling we want in this case.
4913
4914Note again that z' is not UTC-equivalent as far as the hybrid tzinfo class is
4915concerned (because it takes z' as being in standard time rather than the
4916daylight time we intend here), but returning it gives the real-life "local
4917clock repeats an hour" behavior when mapping the "unspellable" UTC hour into
4918tz.
4919
4920When the input is 6:MM, z=1:MM and z.d=0, and we stop at once, again with
4921the 1:MM standard time spelling we want.
4922
4923So how can this break? One of the assumptions must be violated. Two
4924possibilities:
4925
49261) [2] effectively says that y.s is invariant across all y belong to a given
4927 time zone. This isn't true if, for political reasons or continental drift,
4928 a region decides to change its base offset from UTC.
4929
49302) There may be versions of "double daylight" time where the tail end of
4931 the analysis gives up a step too early. I haven't thought about that
4932 enough to say.
4933
4934In any case, it's clear that the default fromutc() is strong enough to handle
4935"almost all" time zones: so long as the standard offset is invariant, it
4936doesn't matter if daylight time transition points change from year to year, or
4937if daylight time is skipped in some years; it doesn't matter how large or
4938small dst() may get within its bounds; and it doesn't even matter if some
4939perverse time zone returns a negative dst()). So a breaking case must be
4940pretty bizarre, and a tzinfo subclass can override fromutc() if it is.
Tim Petersf3615152003-01-01 21:51:37 +00004941--------------------------------------------------------------------------- */