blob: 5401068cbcc4233e5730e7a057ba49ea2b833435 [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
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +000028# error "datetime.c requires that C int have at least 32 bits"
Tim Peters2a799bf2002-12-16 20:18:38 +000029#endif
30
31#define MINYEAR 1
32#define MAXYEAR 9999
Alexander Belopolsky3efc2fd2010-05-27 22:03:53 +000033#define MAXORDINAL 3652059 /* date(9999,12,31).toordinal() */
Tim Peters2a799bf2002-12-16 20:18:38 +000034
35/* Nine decimal digits is easy to communicate, and leaves enough room
36 * so that two delta days can be added w/o fear of overflowing a signed
37 * 32-bit int, and with plenty of room left over to absorb any possible
38 * carries from adding seconds.
39 */
40#define MAX_DELTA_DAYS 999999999
41
42/* Rename the long macros in datetime.h to more reasonable short names. */
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +000043#define GET_YEAR PyDateTime_GET_YEAR
44#define GET_MONTH PyDateTime_GET_MONTH
45#define GET_DAY PyDateTime_GET_DAY
46#define DATE_GET_HOUR PyDateTime_DATE_GET_HOUR
47#define DATE_GET_MINUTE PyDateTime_DATE_GET_MINUTE
48#define DATE_GET_SECOND PyDateTime_DATE_GET_SECOND
49#define DATE_GET_MICROSECOND PyDateTime_DATE_GET_MICROSECOND
Tim Peters2a799bf2002-12-16 20:18:38 +000050
51/* Date accessors for date and datetime. */
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +000052#define SET_YEAR(o, v) (((o)->data[0] = ((v) & 0xff00) >> 8), \
53 ((o)->data[1] = ((v) & 0x00ff)))
54#define SET_MONTH(o, v) (PyDateTime_GET_MONTH(o) = (v))
55#define SET_DAY(o, v) (PyDateTime_GET_DAY(o) = (v))
Tim Peters2a799bf2002-12-16 20:18:38 +000056
57/* Date/Time accessors for datetime. */
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +000058#define DATE_SET_HOUR(o, v) (PyDateTime_DATE_GET_HOUR(o) = (v))
59#define DATE_SET_MINUTE(o, v) (PyDateTime_DATE_GET_MINUTE(o) = (v))
60#define DATE_SET_SECOND(o, v) (PyDateTime_DATE_GET_SECOND(o) = (v))
61#define DATE_SET_MICROSECOND(o, v) \
62 (((o)->data[7] = ((v) & 0xff0000) >> 16), \
63 ((o)->data[8] = ((v) & 0x00ff00) >> 8), \
64 ((o)->data[9] = ((v) & 0x0000ff)))
Tim Peters2a799bf2002-12-16 20:18:38 +000065
66/* Time accessors for time. */
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +000067#define TIME_GET_HOUR PyDateTime_TIME_GET_HOUR
68#define TIME_GET_MINUTE PyDateTime_TIME_GET_MINUTE
69#define TIME_GET_SECOND PyDateTime_TIME_GET_SECOND
70#define TIME_GET_MICROSECOND PyDateTime_TIME_GET_MICROSECOND
71#define TIME_SET_HOUR(o, v) (PyDateTime_TIME_GET_HOUR(o) = (v))
72#define TIME_SET_MINUTE(o, v) (PyDateTime_TIME_GET_MINUTE(o) = (v))
73#define TIME_SET_SECOND(o, v) (PyDateTime_TIME_GET_SECOND(o) = (v))
74#define TIME_SET_MICROSECOND(o, v) \
75 (((o)->data[3] = ((v) & 0xff0000) >> 16), \
76 ((o)->data[4] = ((v) & 0x00ff00) >> 8), \
77 ((o)->data[5] = ((v) & 0x0000ff)))
Tim Peters2a799bf2002-12-16 20:18:38 +000078
79/* Delta accessors for timedelta. */
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +000080#define GET_TD_DAYS(o) (((PyDateTime_Delta *)(o))->days)
81#define GET_TD_SECONDS(o) (((PyDateTime_Delta *)(o))->seconds)
82#define GET_TD_MICROSECONDS(o) (((PyDateTime_Delta *)(o))->microseconds)
Tim Peters2a799bf2002-12-16 20:18:38 +000083
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +000084#define SET_TD_DAYS(o, v) ((o)->days = (v))
85#define SET_TD_SECONDS(o, v) ((o)->seconds = (v))
Tim Peters2a799bf2002-12-16 20:18:38 +000086#define SET_TD_MICROSECONDS(o, v) ((o)->microseconds = (v))
87
Tim Petersa032d2e2003-01-11 00:15:54 +000088/* p is a pointer to a time or a datetime object; HASTZINFO(p) returns
89 * p->hastzinfo.
90 */
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +000091#define HASTZINFO(p) (((_PyDateTime_BaseTZInfo *)(p))->hastzinfo)
Tim Petersa032d2e2003-01-11 00:15:54 +000092
Tim Peters3f606292004-03-21 23:38:41 +000093/* M is a char or int claiming to be a valid month. The macro is equivalent
94 * to the two-sided Python test
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +000095 * 1 <= M <= 12
Tim Peters3f606292004-03-21 23:38:41 +000096 */
97#define MONTH_IS_SANE(M) ((unsigned int)(M) - 1 < 12)
98
Tim Peters2a799bf2002-12-16 20:18:38 +000099/* Forward declarations. */
100static PyTypeObject PyDateTime_DateType;
101static PyTypeObject PyDateTime_DateTimeType;
Tim Peters2a799bf2002-12-16 20:18:38 +0000102static PyTypeObject PyDateTime_DeltaType;
103static PyTypeObject PyDateTime_TimeType;
104static PyTypeObject PyDateTime_TZInfoType;
Tim Peters2a799bf2002-12-16 20:18:38 +0000105
106/* ---------------------------------------------------------------------------
107 * Math utilities.
108 */
109
110/* k = i+j overflows iff k differs in sign from both inputs,
111 * iff k^i has sign bit set and k^j has sign bit set,
112 * iff (k^i)&(k^j) has sign bit set.
113 */
114#define SIGNED_ADD_OVERFLOWED(RESULT, I, J) \
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000115 ((((RESULT) ^ (I)) & ((RESULT) ^ (J))) < 0)
Tim Peters2a799bf2002-12-16 20:18:38 +0000116
117/* Compute Python divmod(x, y), returning the quotient and storing the
118 * remainder into *r. The quotient is the floor of x/y, and that's
119 * the real point of this. C will probably truncate instead (C99
120 * requires truncation; C89 left it implementation-defined).
121 * Simplification: we *require* that y > 0 here. That's appropriate
122 * for all the uses made of it. This simplifies the code and makes
123 * the overflow case impossible (divmod(LONG_MIN, -1) is the only
124 * overflow case).
125 */
126static int
127divmod(int x, int y, int *r)
128{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000129 int quo;
Tim Peters2a799bf2002-12-16 20:18:38 +0000130
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000131 assert(y > 0);
132 quo = x / y;
133 *r = x - quo * y;
134 if (*r < 0) {
135 --quo;
136 *r += y;
137 }
138 assert(0 <= *r && *r < y);
139 return quo;
Tim Peters2a799bf2002-12-16 20:18:38 +0000140}
141
Tim Peters5d644dd2003-01-02 16:32:54 +0000142/* Round a double to the nearest long. |x| must be small enough to fit
143 * in a C long; this is not checked.
144 */
145static long
146round_to_long(double x)
147{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000148 if (x >= 0.0)
149 x = floor(x + 0.5);
150 else
151 x = ceil(x - 0.5);
152 return (long)x;
Tim Peters5d644dd2003-01-02 16:32:54 +0000153}
154
Tim Peters2a799bf2002-12-16 20:18:38 +0000155/* ---------------------------------------------------------------------------
156 * General calendrical helper functions
157 */
158
159/* For each month ordinal in 1..12, the number of days in that month,
160 * and the number of days before that month in the same year. These
161 * are correct for non-leap years only.
162 */
163static int _days_in_month[] = {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000164 0, /* unused; this vector uses 1-based indexing */
165 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
Tim Peters2a799bf2002-12-16 20:18:38 +0000166};
167
168static int _days_before_month[] = {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000169 0, /* unused; this vector uses 1-based indexing */
170 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
Tim Peters2a799bf2002-12-16 20:18:38 +0000171};
172
173/* year -> 1 if leap year, else 0. */
174static int
175is_leap(int year)
176{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000177 /* Cast year to unsigned. The result is the same either way, but
178 * C can generate faster code for unsigned mod than for signed
179 * mod (especially for % 4 -- a good compiler should just grab
180 * the last 2 bits when the LHS is unsigned).
181 */
182 const unsigned int ayear = (unsigned int)year;
183 return ayear % 4 == 0 && (ayear % 100 != 0 || ayear % 400 == 0);
Tim Peters2a799bf2002-12-16 20:18:38 +0000184}
185
186/* year, month -> number of days in that month in that year */
187static int
188days_in_month(int year, int month)
189{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000190 assert(month >= 1);
191 assert(month <= 12);
192 if (month == 2 && is_leap(year))
193 return 29;
194 else
195 return _days_in_month[month];
Tim Peters2a799bf2002-12-16 20:18:38 +0000196}
197
198/* year, month -> number of days in year preceeding first day of month */
199static int
200days_before_month(int year, int month)
201{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000202 int days;
Tim Peters2a799bf2002-12-16 20:18:38 +0000203
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000204 assert(month >= 1);
205 assert(month <= 12);
206 days = _days_before_month[month];
207 if (month > 2 && is_leap(year))
208 ++days;
209 return days;
Tim Peters2a799bf2002-12-16 20:18:38 +0000210}
211
212/* year -> number of days before January 1st of year. Remember that we
213 * start with year 1, so days_before_year(1) == 0.
214 */
215static int
216days_before_year(int year)
217{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000218 int y = year - 1;
219 /* This is incorrect if year <= 0; we really want the floor
220 * here. But so long as MINYEAR is 1, the smallest year this
221 * can see is 0 (this can happen in some normalization endcases),
222 * so we'll just special-case that.
223 */
224 assert (year >= 0);
225 if (y >= 0)
226 return y*365 + y/4 - y/100 + y/400;
227 else {
228 assert(y == -1);
229 return -366;
230 }
Tim Peters2a799bf2002-12-16 20:18:38 +0000231}
232
233/* Number of days in 4, 100, and 400 year cycles. That these have
234 * the correct values is asserted in the module init function.
235 */
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000236#define DI4Y 1461 /* days_before_year(5); days in 4 years */
237#define DI100Y 36524 /* days_before_year(101); days in 100 years */
238#define DI400Y 146097 /* days_before_year(401); days in 400 years */
Tim Peters2a799bf2002-12-16 20:18:38 +0000239
240/* ordinal -> year, month, day, considering 01-Jan-0001 as day 1. */
241static void
242ord_to_ymd(int ordinal, int *year, int *month, int *day)
243{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000244 int n, n1, n4, n100, n400, leapyear, preceding;
Tim Peters2a799bf2002-12-16 20:18:38 +0000245
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000246 /* ordinal is a 1-based index, starting at 1-Jan-1. The pattern of
247 * leap years repeats exactly every 400 years. The basic strategy is
248 * to find the closest 400-year boundary at or before ordinal, then
249 * work with the offset from that boundary to ordinal. Life is much
250 * clearer if we subtract 1 from ordinal first -- then the values
251 * of ordinal at 400-year boundaries are exactly those divisible
252 * by DI400Y:
253 *
254 * D M Y n n-1
255 * -- --- ---- ---------- ----------------
256 * 31 Dec -400 -DI400Y -DI400Y -1
257 * 1 Jan -399 -DI400Y +1 -DI400Y 400-year boundary
258 * ...
259 * 30 Dec 000 -1 -2
260 * 31 Dec 000 0 -1
261 * 1 Jan 001 1 0 400-year boundary
262 * 2 Jan 001 2 1
263 * 3 Jan 001 3 2
264 * ...
265 * 31 Dec 400 DI400Y DI400Y -1
266 * 1 Jan 401 DI400Y +1 DI400Y 400-year boundary
267 */
268 assert(ordinal >= 1);
269 --ordinal;
270 n400 = ordinal / DI400Y;
271 n = ordinal % DI400Y;
272 *year = n400 * 400 + 1;
Tim Peters2a799bf2002-12-16 20:18:38 +0000273
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000274 /* Now n is the (non-negative) offset, in days, from January 1 of
275 * year, to the desired date. Now compute how many 100-year cycles
276 * precede n.
277 * Note that it's possible for n100 to equal 4! In that case 4 full
278 * 100-year cycles precede the desired day, which implies the
279 * desired day is December 31 at the end of a 400-year cycle.
280 */
281 n100 = n / DI100Y;
282 n = n % DI100Y;
Tim Peters2a799bf2002-12-16 20:18:38 +0000283
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000284 /* Now compute how many 4-year cycles precede it. */
285 n4 = n / DI4Y;
286 n = n % DI4Y;
Tim Peters2a799bf2002-12-16 20:18:38 +0000287
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000288 /* And now how many single years. Again n1 can be 4, and again
289 * meaning that the desired day is December 31 at the end of the
290 * 4-year cycle.
291 */
292 n1 = n / 365;
293 n = n % 365;
Tim Peters2a799bf2002-12-16 20:18:38 +0000294
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000295 *year += n100 * 100 + n4 * 4 + n1;
296 if (n1 == 4 || n100 == 4) {
297 assert(n == 0);
298 *year -= 1;
299 *month = 12;
300 *day = 31;
301 return;
302 }
Tim Peters2a799bf2002-12-16 20:18:38 +0000303
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000304 /* Now the year is correct, and n is the offset from January 1. We
305 * find the month via an estimate that's either exact or one too
306 * large.
307 */
308 leapyear = n1 == 3 && (n4 != 24 || n100 == 3);
309 assert(leapyear == is_leap(*year));
310 *month = (n + 50) >> 5;
311 preceding = (_days_before_month[*month] + (*month > 2 && leapyear));
312 if (preceding > n) {
313 /* estimate is too large */
314 *month -= 1;
315 preceding -= days_in_month(*year, *month);
316 }
317 n -= preceding;
318 assert(0 <= n);
319 assert(n < days_in_month(*year, *month));
Tim Peters2a799bf2002-12-16 20:18:38 +0000320
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000321 *day = n + 1;
Tim Peters2a799bf2002-12-16 20:18:38 +0000322}
323
324/* year, month, day -> ordinal, considering 01-Jan-0001 as day 1. */
325static int
326ymd_to_ord(int year, int month, int day)
327{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000328 return days_before_year(year) + days_before_month(year, month) + day;
Tim Peters2a799bf2002-12-16 20:18:38 +0000329}
330
331/* Day of week, where Monday==0, ..., Sunday==6. 1/1/1 was a Monday. */
332static int
333weekday(int year, int month, int day)
334{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000335 return (ymd_to_ord(year, month, day) + 6) % 7;
Tim Peters2a799bf2002-12-16 20:18:38 +0000336}
337
338/* Ordinal of the Monday starting week 1 of the ISO year. Week 1 is the
339 * first calendar week containing a Thursday.
340 */
341static int
342iso_week1_monday(int year)
343{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000344 int first_day = ymd_to_ord(year, 1, 1); /* ord of 1/1 */
345 /* 0 if 1/1 is a Monday, 1 if a Tue, etc. */
346 int first_weekday = (first_day + 6) % 7;
347 /* ordinal of closest Monday at or before 1/1 */
348 int week1_monday = first_day - first_weekday;
Tim Peters2a799bf2002-12-16 20:18:38 +0000349
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000350 if (first_weekday > 3) /* if 1/1 was Fri, Sat, Sun */
351 week1_monday += 7;
352 return week1_monday;
Tim Peters2a799bf2002-12-16 20:18:38 +0000353}
354
355/* ---------------------------------------------------------------------------
356 * Range checkers.
357 */
358
359/* Check that -MAX_DELTA_DAYS <= days <= MAX_DELTA_DAYS. If so, return 0.
360 * If not, raise OverflowError and return -1.
361 */
362static int
363check_delta_day_range(int days)
364{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000365 if (-MAX_DELTA_DAYS <= days && days <= MAX_DELTA_DAYS)
366 return 0;
367 PyErr_Format(PyExc_OverflowError,
368 "days=%d; must have magnitude <= %d",
369 days, MAX_DELTA_DAYS);
370 return -1;
Tim Peters2a799bf2002-12-16 20:18:38 +0000371}
372
373/* Check that date arguments are in range. Return 0 if they are. If they
374 * aren't, raise ValueError and return -1.
375 */
376static int
377check_date_args(int year, int month, int day)
378{
379
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000380 if (year < MINYEAR || year > MAXYEAR) {
381 PyErr_SetString(PyExc_ValueError,
382 "year is out of range");
383 return -1;
384 }
385 if (month < 1 || month > 12) {
386 PyErr_SetString(PyExc_ValueError,
387 "month must be in 1..12");
388 return -1;
389 }
390 if (day < 1 || day > days_in_month(year, month)) {
391 PyErr_SetString(PyExc_ValueError,
392 "day is out of range for month");
393 return -1;
394 }
395 return 0;
Tim Peters2a799bf2002-12-16 20:18:38 +0000396}
397
398/* Check that time arguments are in range. Return 0 if they are. If they
399 * aren't, raise ValueError and return -1.
400 */
401static int
402check_time_args(int h, int m, int s, int us)
403{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000404 if (h < 0 || h > 23) {
405 PyErr_SetString(PyExc_ValueError,
406 "hour must be in 0..23");
407 return -1;
408 }
409 if (m < 0 || m > 59) {
410 PyErr_SetString(PyExc_ValueError,
411 "minute must be in 0..59");
412 return -1;
413 }
414 if (s < 0 || s > 59) {
415 PyErr_SetString(PyExc_ValueError,
416 "second must be in 0..59");
417 return -1;
418 }
419 if (us < 0 || us > 999999) {
420 PyErr_SetString(PyExc_ValueError,
421 "microsecond must be in 0..999999");
422 return -1;
423 }
424 return 0;
Tim Peters2a799bf2002-12-16 20:18:38 +0000425}
426
427/* ---------------------------------------------------------------------------
428 * Normalization utilities.
429 */
430
431/* One step of a mixed-radix conversion. A "hi" unit is equivalent to
432 * factor "lo" units. factor must be > 0. If *lo is less than 0, or
433 * at least factor, enough of *lo is converted into "hi" units so that
434 * 0 <= *lo < factor. The input values must be such that int overflow
435 * is impossible.
436 */
437static void
438normalize_pair(int *hi, int *lo, int factor)
439{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000440 assert(factor > 0);
441 assert(lo != hi);
442 if (*lo < 0 || *lo >= factor) {
443 const int num_hi = divmod(*lo, factor, lo);
444 const int new_hi = *hi + num_hi;
445 assert(! SIGNED_ADD_OVERFLOWED(new_hi, *hi, num_hi));
446 *hi = new_hi;
447 }
448 assert(0 <= *lo && *lo < factor);
Tim Peters2a799bf2002-12-16 20:18:38 +0000449}
450
451/* Fiddle days (d), seconds (s), and microseconds (us) so that
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000452 * 0 <= *s < 24*3600
453 * 0 <= *us < 1000000
Tim Peters2a799bf2002-12-16 20:18:38 +0000454 * The input values must be such that the internals don't overflow.
455 * The way this routine is used, we don't get close.
456 */
457static void
458normalize_d_s_us(int *d, int *s, int *us)
459{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000460 if (*us < 0 || *us >= 1000000) {
461 normalize_pair(s, us, 1000000);
462 /* |s| can't be bigger than about
463 * |original s| + |original us|/1000000 now.
464 */
Tim Peters2a799bf2002-12-16 20:18:38 +0000465
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000466 }
467 if (*s < 0 || *s >= 24*3600) {
468 normalize_pair(d, s, 24*3600);
469 /* |d| can't be bigger than about
470 * |original d| +
471 * (|original s| + |original us|/1000000) / (24*3600) now.
472 */
473 }
474 assert(0 <= *s && *s < 24*3600);
475 assert(0 <= *us && *us < 1000000);
Tim Peters2a799bf2002-12-16 20:18:38 +0000476}
477
478/* Fiddle years (y), months (m), and days (d) so that
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000479 * 1 <= *m <= 12
480 * 1 <= *d <= days_in_month(*y, *m)
Tim Peters2a799bf2002-12-16 20:18:38 +0000481 * The input values must be such that the internals don't overflow.
482 * The way this routine is used, we don't get close.
483 */
Alexander Belopolsky3efc2fd2010-05-27 22:03:53 +0000484static int
Tim Peters2a799bf2002-12-16 20:18:38 +0000485normalize_y_m_d(int *y, int *m, int *d)
486{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000487 int dim; /* # of days in month */
Tim Peters2a799bf2002-12-16 20:18:38 +0000488
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000489 /* This gets muddy: the proper range for day can't be determined
490 * without knowing the correct month and year, but if day is, e.g.,
491 * plus or minus a million, the current month and year values make
492 * no sense (and may also be out of bounds themselves).
493 * Saying 12 months == 1 year should be non-controversial.
494 */
495 if (*m < 1 || *m > 12) {
496 --*m;
497 normalize_pair(y, m, 12);
498 ++*m;
499 /* |y| can't be bigger than about
500 * |original y| + |original m|/12 now.
501 */
502 }
503 assert(1 <= *m && *m <= 12);
Tim Peters2a799bf2002-12-16 20:18:38 +0000504
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000505 /* Now only day can be out of bounds (year may also be out of bounds
506 * for a datetime object, but we don't care about that here).
507 * If day is out of bounds, what to do is arguable, but at least the
508 * method here is principled and explainable.
509 */
510 dim = days_in_month(*y, *m);
511 if (*d < 1 || *d > dim) {
512 /* Move day-1 days from the first of the month. First try to
513 * get off cheap if we're only one day out of range
514 * (adjustments for timezone alone can't be worse than that).
515 */
516 if (*d == 0) {
517 --*m;
518 if (*m > 0)
519 *d = days_in_month(*y, *m);
520 else {
521 --*y;
522 *m = 12;
523 *d = 31;
524 }
525 }
526 else if (*d == dim + 1) {
527 /* move forward a day */
528 ++*m;
529 *d = 1;
530 if (*m > 12) {
531 *m = 1;
532 ++*y;
533 }
534 }
535 else {
536 int ordinal = ymd_to_ord(*y, *m, 1) +
537 *d - 1;
Alexander Belopolsky3efc2fd2010-05-27 22:03:53 +0000538 if (ordinal < 1 || ordinal > MAXORDINAL) {
539 goto error;
540 } else {
541 ord_to_ymd(ordinal, y, m, d);
542 return 0;
543 }
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000544 }
545 }
546 assert(*m > 0);
547 assert(*d > 0);
Alexander Belopolsky3efc2fd2010-05-27 22:03:53 +0000548 if (MINYEAR <= *y && *y <= MAXYEAR)
549 return 0;
550 error:
551 PyErr_SetString(PyExc_OverflowError,
552 "date value out of range");
553 return -1;
554
Tim Peters2a799bf2002-12-16 20:18:38 +0000555}
556
557/* Fiddle out-of-bounds months and days so that the result makes some kind
558 * of sense. The parameters are both inputs and outputs. Returns < 0 on
559 * failure, where failure means the adjusted year is out of bounds.
560 */
561static int
562normalize_date(int *year, int *month, int *day)
563{
Alexander Belopolsky3efc2fd2010-05-27 22:03:53 +0000564 return normalize_y_m_d(year, month, day);
Tim Peters2a799bf2002-12-16 20:18:38 +0000565}
566
567/* Force all the datetime fields into range. The parameters are both
568 * inputs and outputs. Returns < 0 on error.
569 */
570static int
571normalize_datetime(int *year, int *month, int *day,
572 int *hour, int *minute, int *second,
573 int *microsecond)
574{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000575 normalize_pair(second, microsecond, 1000000);
576 normalize_pair(minute, second, 60);
577 normalize_pair(hour, minute, 60);
578 normalize_pair(day, hour, 24);
579 return normalize_date(year, month, day);
Tim Peters2a799bf2002-12-16 20:18:38 +0000580}
581
582/* ---------------------------------------------------------------------------
Tim Petersb0c854d2003-05-17 15:57:00 +0000583 * Basic object allocation: tp_alloc implementations. These allocate
584 * Python objects of the right size and type, and do the Python object-
585 * initialization bit. If there's not enough memory, they return NULL after
586 * setting MemoryError. All data members remain uninitialized trash.
587 *
588 * We abuse the tp_alloc "nitems" argument to communicate whether a tzinfo
Tim Peters03eaf8b2003-05-18 02:24:46 +0000589 * member is needed. This is ugly, imprecise, and possibly insecure.
590 * tp_basicsize for the time and datetime types is set to the size of the
591 * struct that has room for the tzinfo member, so subclasses in Python will
592 * allocate enough space for a tzinfo member whether or not one is actually
593 * needed. That's the "ugly and imprecise" parts. The "possibly insecure"
594 * part is that PyType_GenericAlloc() (which subclasses in Python end up
595 * using) just happens today to effectively ignore the nitems argument
596 * when tp_itemsize is 0, which it is for these type objects. If that
597 * changes, perhaps the callers of tp_alloc slots in this file should
598 * be changed to force a 0 nitems argument unless the type being allocated
599 * is a base type implemented in this file (so that tp_alloc is time_alloc
600 * or datetime_alloc below, which know about the nitems abuse).
Tim Petersb0c854d2003-05-17 15:57:00 +0000601 */
602
603static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000604time_alloc(PyTypeObject *type, Py_ssize_t aware)
Tim Petersb0c854d2003-05-17 15:57:00 +0000605{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000606 PyObject *self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000607
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000608 self = (PyObject *)
609 PyObject_MALLOC(aware ?
610 sizeof(PyDateTime_Time) :
611 sizeof(_PyDateTime_BaseTime));
612 if (self == NULL)
613 return (PyObject *)PyErr_NoMemory();
614 PyObject_INIT(self, type);
615 return self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000616}
617
618static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000619datetime_alloc(PyTypeObject *type, Py_ssize_t aware)
Tim Petersb0c854d2003-05-17 15:57:00 +0000620{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000621 PyObject *self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000622
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000623 self = (PyObject *)
624 PyObject_MALLOC(aware ?
625 sizeof(PyDateTime_DateTime) :
626 sizeof(_PyDateTime_BaseDateTime));
627 if (self == NULL)
628 return (PyObject *)PyErr_NoMemory();
629 PyObject_INIT(self, type);
630 return self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000631}
632
633/* ---------------------------------------------------------------------------
634 * Helpers for setting object fields. These work on pointers to the
635 * appropriate base class.
636 */
637
638/* For date and datetime. */
639static void
640set_date_fields(PyDateTime_Date *self, int y, int m, int d)
641{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000642 self->hashcode = -1;
643 SET_YEAR(self, y);
644 SET_MONTH(self, m);
645 SET_DAY(self, d);
Tim Petersb0c854d2003-05-17 15:57:00 +0000646}
647
648/* ---------------------------------------------------------------------------
649 * Create various objects, mostly without range checking.
650 */
651
652/* Create a date instance with no range checking. */
653static PyObject *
654new_date_ex(int year, int month, int day, PyTypeObject *type)
655{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000656 PyDateTime_Date *self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000657
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000658 self = (PyDateTime_Date *) (type->tp_alloc(type, 0));
659 if (self != NULL)
660 set_date_fields(self, year, month, day);
661 return (PyObject *) self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000662}
663
664#define new_date(year, month, day) \
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000665 new_date_ex(year, month, day, &PyDateTime_DateType)
Tim Petersb0c854d2003-05-17 15:57:00 +0000666
667/* Create a datetime instance with no range checking. */
668static PyObject *
669new_datetime_ex(int year, int month, int day, int hour, int minute,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000670 int second, int usecond, PyObject *tzinfo, PyTypeObject *type)
Tim Petersb0c854d2003-05-17 15:57:00 +0000671{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000672 PyDateTime_DateTime *self;
673 char aware = tzinfo != Py_None;
Tim Petersb0c854d2003-05-17 15:57:00 +0000674
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000675 self = (PyDateTime_DateTime *) (type->tp_alloc(type, aware));
676 if (self != NULL) {
677 self->hastzinfo = aware;
678 set_date_fields((PyDateTime_Date *)self, year, month, day);
679 DATE_SET_HOUR(self, hour);
680 DATE_SET_MINUTE(self, minute);
681 DATE_SET_SECOND(self, second);
682 DATE_SET_MICROSECOND(self, usecond);
683 if (aware) {
684 Py_INCREF(tzinfo);
685 self->tzinfo = tzinfo;
686 }
687 }
688 return (PyObject *)self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000689}
690
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000691#define new_datetime(y, m, d, hh, mm, ss, us, tzinfo) \
692 new_datetime_ex(y, m, d, hh, mm, ss, us, tzinfo, \
693 &PyDateTime_DateTimeType)
Tim Petersb0c854d2003-05-17 15:57:00 +0000694
695/* Create a time instance with no range checking. */
696static PyObject *
697new_time_ex(int hour, int minute, int second, int usecond,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000698 PyObject *tzinfo, PyTypeObject *type)
Tim Petersb0c854d2003-05-17 15:57:00 +0000699{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000700 PyDateTime_Time *self;
701 char aware = tzinfo != Py_None;
Tim Petersb0c854d2003-05-17 15:57:00 +0000702
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000703 self = (PyDateTime_Time *) (type->tp_alloc(type, aware));
704 if (self != NULL) {
705 self->hastzinfo = aware;
706 self->hashcode = -1;
707 TIME_SET_HOUR(self, hour);
708 TIME_SET_MINUTE(self, minute);
709 TIME_SET_SECOND(self, second);
710 TIME_SET_MICROSECOND(self, usecond);
711 if (aware) {
712 Py_INCREF(tzinfo);
713 self->tzinfo = tzinfo;
714 }
715 }
716 return (PyObject *)self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000717}
718
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000719#define new_time(hh, mm, ss, us, tzinfo) \
720 new_time_ex(hh, mm, ss, us, tzinfo, &PyDateTime_TimeType)
Tim Petersb0c854d2003-05-17 15:57:00 +0000721
722/* Create a timedelta instance. Normalize the members iff normalize is
723 * true. Passing false is a speed optimization, if you know for sure
724 * that seconds and microseconds are already in their proper ranges. In any
725 * case, raises OverflowError and returns NULL if the normalized days is out
726 * of range).
727 */
728static PyObject *
729new_delta_ex(int days, int seconds, int microseconds, int normalize,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000730 PyTypeObject *type)
Tim Petersb0c854d2003-05-17 15:57:00 +0000731{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000732 PyDateTime_Delta *self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000733
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000734 if (normalize)
735 normalize_d_s_us(&days, &seconds, &microseconds);
736 assert(0 <= seconds && seconds < 24*3600);
737 assert(0 <= microseconds && microseconds < 1000000);
Tim Petersb0c854d2003-05-17 15:57:00 +0000738
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000739 if (check_delta_day_range(days) < 0)
740 return NULL;
Tim Petersb0c854d2003-05-17 15:57:00 +0000741
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000742 self = (PyDateTime_Delta *) (type->tp_alloc(type, 0));
743 if (self != NULL) {
744 self->hashcode = -1;
745 SET_TD_DAYS(self, days);
746 SET_TD_SECONDS(self, seconds);
747 SET_TD_MICROSECONDS(self, microseconds);
748 }
749 return (PyObject *) self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000750}
751
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000752#define new_delta(d, s, us, normalize) \
753 new_delta_ex(d, s, us, normalize, &PyDateTime_DeltaType)
Tim Petersb0c854d2003-05-17 15:57:00 +0000754
755/* ---------------------------------------------------------------------------
Tim Peters2a799bf2002-12-16 20:18:38 +0000756 * tzinfo helpers.
757 */
758
Tim Peters855fe882002-12-22 03:43:39 +0000759/* Ensure that p is None or of a tzinfo subclass. Return 0 if OK; if not
760 * raise TypeError and return -1.
761 */
762static int
763check_tzinfo_subclass(PyObject *p)
764{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000765 if (p == Py_None || PyTZInfo_Check(p))
766 return 0;
767 PyErr_Format(PyExc_TypeError,
768 "tzinfo argument must be None or of a tzinfo subclass, "
769 "not type '%s'",
770 Py_TYPE(p)->tp_name);
771 return -1;
Tim Peters855fe882002-12-22 03:43:39 +0000772}
773
Tim Petersbad8ff02002-12-30 20:52:32 +0000774/* Return tzinfo.methname(tzinfoarg), without any checking of results.
Tim Peters855fe882002-12-22 03:43:39 +0000775 * If tzinfo is None, returns None.
776 */
777static PyObject *
Tim Petersbad8ff02002-12-30 20:52:32 +0000778call_tzinfo_method(PyObject *tzinfo, char *methname, PyObject *tzinfoarg)
Tim Peters855fe882002-12-22 03:43:39 +0000779{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000780 PyObject *result;
Tim Peters855fe882002-12-22 03:43:39 +0000781
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000782 assert(tzinfo && methname && tzinfoarg);
783 assert(check_tzinfo_subclass(tzinfo) >= 0);
784 if (tzinfo == Py_None) {
785 result = Py_None;
786 Py_INCREF(result);
787 }
788 else
789 result = PyObject_CallMethod(tzinfo, methname, "O", tzinfoarg);
790 return result;
Tim Peters855fe882002-12-22 03:43:39 +0000791}
792
Tim Peters2a799bf2002-12-16 20:18:38 +0000793/* If self has a tzinfo member, return a BORROWED reference to it. Else
794 * return NULL, which is NOT AN ERROR. There are no error returns here,
795 * and the caller must not decref the result.
796 */
797static PyObject *
798get_tzinfo_member(PyObject *self)
799{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000800 PyObject *tzinfo = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +0000801
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000802 if (PyDateTime_Check(self) && HASTZINFO(self))
803 tzinfo = ((PyDateTime_DateTime *)self)->tzinfo;
804 else if (PyTime_Check(self) && HASTZINFO(self))
805 tzinfo = ((PyDateTime_Time *)self)->tzinfo;
Tim Peters2a799bf2002-12-16 20:18:38 +0000806
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000807 return tzinfo;
Tim Peters2a799bf2002-12-16 20:18:38 +0000808}
809
Tim Petersbad8ff02002-12-30 20:52:32 +0000810/* Call getattr(tzinfo, name)(tzinfoarg), and extract an int from the
Tim Peters2a799bf2002-12-16 20:18:38 +0000811 * result. tzinfo must be an instance of the tzinfo class. If the method
812 * returns None, this returns 0 and sets *none to 1. If the method doesn't
Tim Peters397301e2003-01-02 21:28:08 +0000813 * return None or timedelta, TypeError is raised and this returns -1. If it
814 * returnsa timedelta and the value is out of range or isn't a whole number
815 * of minutes, ValueError is raised and this returns -1.
Tim Peters2a799bf2002-12-16 20:18:38 +0000816 * Else *none is set to 0 and the integer method result is returned.
817 */
818static int
819call_utc_tzinfo_method(PyObject *tzinfo, char *name, PyObject *tzinfoarg,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000820 int *none)
Tim Peters2a799bf2002-12-16 20:18:38 +0000821{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000822 PyObject *u;
823 int result = -1;
Tim Peters2a799bf2002-12-16 20:18:38 +0000824
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000825 assert(tzinfo != NULL);
826 assert(PyTZInfo_Check(tzinfo));
827 assert(tzinfoarg != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +0000828
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000829 *none = 0;
830 u = call_tzinfo_method(tzinfo, name, tzinfoarg);
831 if (u == NULL)
832 return -1;
Tim Peters2a799bf2002-12-16 20:18:38 +0000833
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000834 else if (u == Py_None) {
835 result = 0;
836 *none = 1;
837 }
838 else if (PyDelta_Check(u)) {
839 const int days = GET_TD_DAYS(u);
840 if (days < -1 || days > 0)
841 result = 24*60; /* trigger ValueError below */
842 else {
843 /* next line can't overflow because we know days
844 * is -1 or 0 now
845 */
846 int ss = days * 24 * 3600 + GET_TD_SECONDS(u);
847 result = divmod(ss, 60, &ss);
848 if (ss || GET_TD_MICROSECONDS(u)) {
849 PyErr_Format(PyExc_ValueError,
850 "tzinfo.%s() must return a "
851 "whole number of minutes",
852 name);
853 result = -1;
854 }
855 }
856 }
857 else {
858 PyErr_Format(PyExc_TypeError,
859 "tzinfo.%s() must return None or "
860 "timedelta, not '%s'",
861 name, Py_TYPE(u)->tp_name);
862 }
Tim Peters2a799bf2002-12-16 20:18:38 +0000863
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000864 Py_DECREF(u);
865 if (result < -1439 || result > 1439) {
866 PyErr_Format(PyExc_ValueError,
867 "tzinfo.%s() returned %d; must be in "
868 "-1439 .. 1439",
869 name, result);
870 result = -1;
871 }
872 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +0000873}
874
875/* Call tzinfo.utcoffset(tzinfoarg), and extract an integer from the
876 * result. tzinfo must be an instance of the tzinfo class. If utcoffset()
877 * returns None, call_utcoffset returns 0 and sets *none to 1. If uctoffset()
Tim Peters397301e2003-01-02 21:28:08 +0000878 * doesn't return None or timedelta, TypeError is raised and this returns -1.
879 * If utcoffset() returns an invalid timedelta (out of range, or not a whole
880 * # of minutes), ValueError is raised and this returns -1. Else *none is
881 * set to 0 and the offset is returned (as int # of minutes east of UTC).
Tim Peters2a799bf2002-12-16 20:18:38 +0000882 */
883static int
884call_utcoffset(PyObject *tzinfo, PyObject *tzinfoarg, int *none)
885{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000886 return call_utc_tzinfo_method(tzinfo, "utcoffset", tzinfoarg, none);
Tim Peters2a799bf2002-12-16 20:18:38 +0000887}
888
Tim Petersbad8ff02002-12-30 20:52:32 +0000889/* Call tzinfo.name(tzinfoarg), and return the offset as a timedelta or None.
890 */
Tim Peters855fe882002-12-22 03:43:39 +0000891static PyObject *
Tim Petersbad8ff02002-12-30 20:52:32 +0000892offset_as_timedelta(PyObject *tzinfo, char *name, PyObject *tzinfoarg) {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000893 PyObject *result;
Tim Peters855fe882002-12-22 03:43:39 +0000894
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000895 assert(tzinfo && name && tzinfoarg);
896 if (tzinfo == Py_None) {
897 result = Py_None;
898 Py_INCREF(result);
899 }
900 else {
901 int none;
902 int offset = call_utc_tzinfo_method(tzinfo, name, tzinfoarg,
903 &none);
904 if (offset < 0 && PyErr_Occurred())
905 return NULL;
906 if (none) {
907 result = Py_None;
908 Py_INCREF(result);
909 }
910 else
911 result = new_delta(0, offset * 60, 0, 1);
912 }
913 return result;
Tim Peters855fe882002-12-22 03:43:39 +0000914}
915
Tim Peters2a799bf2002-12-16 20:18:38 +0000916/* Call tzinfo.dst(tzinfoarg), and extract an integer from the
917 * result. tzinfo must be an instance of the tzinfo class. If dst()
918 * returns None, call_dst returns 0 and sets *none to 1. If dst()
Tim Peters397301e2003-01-02 21:28:08 +0000919 & doesn't return None or timedelta, TypeError is raised and this
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000920 * returns -1. If dst() returns an invalid timedelta for a UTC offset,
Tim Peters397301e2003-01-02 21:28:08 +0000921 * ValueError is raised and this returns -1. Else *none is set to 0 and
922 * the offset is returned (as an int # of minutes east of UTC).
Tim Peters2a799bf2002-12-16 20:18:38 +0000923 */
924static int
925call_dst(PyObject *tzinfo, PyObject *tzinfoarg, int *none)
926{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000927 return call_utc_tzinfo_method(tzinfo, "dst", tzinfoarg, none);
Tim Peters2a799bf2002-12-16 20:18:38 +0000928}
929
Tim Petersbad8ff02002-12-30 20:52:32 +0000930/* Call tzinfo.tzname(tzinfoarg), and return the result. tzinfo must be
Tim Peters855fe882002-12-22 03:43:39 +0000931 * an instance of the tzinfo class or None. If tzinfo isn't None, and
Tim Petersbad8ff02002-12-30 20:52:32 +0000932 * tzname() doesn't return None or a string, TypeError is raised and this
Guido van Rossume3d1d412007-05-23 21:24:35 +0000933 * returns NULL. If the result is a string, we ensure it is a Unicode
934 * string.
Tim Peters2a799bf2002-12-16 20:18:38 +0000935 */
936static PyObject *
Tim Petersbad8ff02002-12-30 20:52:32 +0000937call_tzname(PyObject *tzinfo, PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +0000938{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000939 PyObject *result;
Tim Peters2a799bf2002-12-16 20:18:38 +0000940
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000941 assert(tzinfo != NULL);
942 assert(check_tzinfo_subclass(tzinfo) >= 0);
943 assert(tzinfoarg != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +0000944
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000945 if (tzinfo == Py_None) {
946 result = Py_None;
947 Py_INCREF(result);
948 }
949 else
950 result = PyObject_CallMethod(tzinfo, "tzname", "O", tzinfoarg);
Tim Peters855fe882002-12-22 03:43:39 +0000951
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000952 if (result != NULL && result != Py_None) {
953 if (!PyUnicode_Check(result)) {
954 PyErr_Format(PyExc_TypeError, "tzinfo.tzname() must "
955 "return None or a string, not '%s'",
956 Py_TYPE(result)->tp_name);
957 Py_DECREF(result);
958 result = NULL;
959 }
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000960 }
961 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +0000962}
963
964typedef enum {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000965 /* an exception has been set; the caller should pass it on */
966 OFFSET_ERROR,
Tim Peters2a799bf2002-12-16 20:18:38 +0000967
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000968 /* type isn't date, datetime, or time subclass */
969 OFFSET_UNKNOWN,
Tim Peters2a799bf2002-12-16 20:18:38 +0000970
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000971 /* date,
972 * datetime with !hastzinfo
973 * datetime with None tzinfo,
974 * datetime where utcoffset() returns None
975 * time with !hastzinfo
976 * time with None tzinfo,
977 * time where utcoffset() returns None
978 */
979 OFFSET_NAIVE,
Tim Peters2a799bf2002-12-16 20:18:38 +0000980
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000981 /* time or datetime where utcoffset() doesn't return None */
982 OFFSET_AWARE
Tim Peters2a799bf2002-12-16 20:18:38 +0000983} naivety;
984
Tim Peters14b69412002-12-22 18:10:22 +0000985/* Classify an object as to whether it's naive or offset-aware. See
Tim Peters2a799bf2002-12-16 20:18:38 +0000986 * the "naivety" typedef for details. If the type is aware, *offset is set
987 * to minutes east of UTC (as returned by the tzinfo.utcoffset() method).
Tim Peters14b69412002-12-22 18:10:22 +0000988 * If the type is offset-naive (or unknown, or error), *offset is set to 0.
Tim Peterse39a80c2002-12-30 21:28:52 +0000989 * tzinfoarg is the argument to pass to the tzinfo.utcoffset() method.
Tim Peters2a799bf2002-12-16 20:18:38 +0000990 */
991static naivety
Tim Peterse39a80c2002-12-30 21:28:52 +0000992classify_utcoffset(PyObject *op, PyObject *tzinfoarg, int *offset)
Tim Peters2a799bf2002-12-16 20:18:38 +0000993{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000994 int none;
995 PyObject *tzinfo;
Tim Peters2a799bf2002-12-16 20:18:38 +0000996
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000997 assert(tzinfoarg != NULL);
998 *offset = 0;
999 tzinfo = get_tzinfo_member(op); /* NULL means no tzinfo, not error */
1000 if (tzinfo == Py_None)
1001 return OFFSET_NAIVE;
1002 if (tzinfo == NULL) {
1003 /* note that a datetime passes the PyDate_Check test */
1004 return (PyTime_Check(op) || PyDate_Check(op)) ?
1005 OFFSET_NAIVE : OFFSET_UNKNOWN;
1006 }
1007 *offset = call_utcoffset(tzinfo, tzinfoarg, &none);
1008 if (*offset == -1 && PyErr_Occurred())
1009 return OFFSET_ERROR;
1010 return none ? OFFSET_NAIVE : OFFSET_AWARE;
Tim Peters2a799bf2002-12-16 20:18:38 +00001011}
1012
Tim Peters00237032002-12-27 02:21:51 +00001013/* Classify two objects as to whether they're naive or offset-aware.
1014 * This isn't quite the same as calling classify_utcoffset() twice: for
1015 * binary operations (comparison and subtraction), we generally want to
1016 * ignore the tzinfo members if they're identical. This is by design,
1017 * so that results match "naive" expectations when mixing objects from a
1018 * single timezone. So in that case, this sets both offsets to 0 and
1019 * both naiveties to OFFSET_NAIVE.
1020 * The function returns 0 if everything's OK, and -1 on error.
1021 */
1022static int
1023classify_two_utcoffsets(PyObject *o1, int *offset1, naivety *n1,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001024 PyObject *tzinfoarg1,
1025 PyObject *o2, int *offset2, naivety *n2,
1026 PyObject *tzinfoarg2)
Tim Peters00237032002-12-27 02:21:51 +00001027{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001028 if (get_tzinfo_member(o1) == get_tzinfo_member(o2)) {
1029 *offset1 = *offset2 = 0;
1030 *n1 = *n2 = OFFSET_NAIVE;
1031 }
1032 else {
1033 *n1 = classify_utcoffset(o1, tzinfoarg1, offset1);
1034 if (*n1 == OFFSET_ERROR)
1035 return -1;
1036 *n2 = classify_utcoffset(o2, tzinfoarg2, offset2);
1037 if (*n2 == OFFSET_ERROR)
1038 return -1;
1039 }
1040 return 0;
Tim Peters00237032002-12-27 02:21:51 +00001041}
1042
Tim Peters2a799bf2002-12-16 20:18:38 +00001043/* repr is like "someclass(arg1, arg2)". If tzinfo isn't None,
1044 * stuff
1045 * ", tzinfo=" + repr(tzinfo)
1046 * before the closing ")".
1047 */
1048static PyObject *
1049append_keyword_tzinfo(PyObject *repr, PyObject *tzinfo)
1050{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001051 PyObject *temp;
Tim Peters2a799bf2002-12-16 20:18:38 +00001052
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001053 assert(PyUnicode_Check(repr));
1054 assert(tzinfo);
1055 if (tzinfo == Py_None)
1056 return repr;
1057 /* Get rid of the trailing ')'. */
1058 assert(PyUnicode_AS_UNICODE(repr)[PyUnicode_GET_SIZE(repr)-1] == ')');
1059 temp = PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(repr),
1060 PyUnicode_GET_SIZE(repr) - 1);
1061 Py_DECREF(repr);
1062 if (temp == NULL)
1063 return NULL;
1064 repr = PyUnicode_FromFormat("%U, tzinfo=%R)", temp, tzinfo);
1065 Py_DECREF(temp);
1066 return repr;
Tim Peters2a799bf2002-12-16 20:18:38 +00001067}
1068
1069/* ---------------------------------------------------------------------------
1070 * String format helpers.
1071 */
1072
1073static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00001074format_ctime(PyDateTime_Date *date, int hours, int minutes, int seconds)
Tim Peters2a799bf2002-12-16 20:18:38 +00001075{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001076 static const char *DayNames[] = {
1077 "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"
1078 };
1079 static const char *MonthNames[] = {
1080 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
1081 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
1082 };
Tim Peters2a799bf2002-12-16 20:18:38 +00001083
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001084 int wday = weekday(GET_YEAR(date), GET_MONTH(date), GET_DAY(date));
Tim Peters2a799bf2002-12-16 20:18:38 +00001085
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001086 return PyUnicode_FromFormat("%s %s %2d %02d:%02d:%02d %04d",
1087 DayNames[wday], MonthNames[GET_MONTH(date)-1],
1088 GET_DAY(date), hours, minutes, seconds,
1089 GET_YEAR(date));
Tim Peters2a799bf2002-12-16 20:18:38 +00001090}
1091
1092/* Add an hours & minutes UTC offset string to buf. buf has no more than
1093 * buflen bytes remaining. The UTC offset is gotten by calling
1094 * tzinfo.uctoffset(tzinfoarg). If that returns None, \0 is stored into
1095 * *buf, and that's all. Else the returned value is checked for sanity (an
1096 * integer in range), and if that's OK it's converted to an hours & minutes
1097 * string of the form
1098 * sign HH sep MM
1099 * Returns 0 if everything is OK. If the return value from utcoffset() is
1100 * bogus, an appropriate exception is set and -1 is returned.
1101 */
1102static int
Tim Peters328fff72002-12-20 01:31:27 +00001103format_utcoffset(char *buf, size_t buflen, const char *sep,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001104 PyObject *tzinfo, PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +00001105{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001106 int offset;
1107 int hours;
1108 int minutes;
1109 char sign;
1110 int none;
Tim Peters2a799bf2002-12-16 20:18:38 +00001111
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001112 assert(buflen >= 1);
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00001113
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001114 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;
Tim Peters2a799bf2002-12-16 20:18:38 +00001129}
1130
Guido van Rossumd8595fe2007-05-23 21:36:49 +00001131static PyObject *
1132make_Zreplacement(PyObject *object, PyObject *tzinfoarg)
1133{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001134 PyObject *temp;
1135 PyObject *tzinfo = get_tzinfo_member(object);
1136 PyObject *Zreplacement = PyUnicode_FromStringAndSize(NULL, 0);
1137 if (Zreplacement == NULL)
1138 return NULL;
1139 if (tzinfo == Py_None || tzinfo == NULL)
1140 return Zreplacement;
Neal Norwitzaea70e02007-08-12 04:32:26 +00001141
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001142 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 }
Neal Norwitzaea70e02007-08-12 04:32:26 +00001150
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001151 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)) {
1162 PyErr_SetString(PyExc_TypeError,
1163 "tzname.replace() did not return a string");
1164 goto Error;
1165 }
1166 return Zreplacement;
Guido van Rossumd8595fe2007-05-23 21:36:49 +00001167
1168 Error:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001169 Py_DECREF(Zreplacement);
1170 return NULL;
Guido van Rossumd8595fe2007-05-23 21:36:49 +00001171}
1172
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001173static PyObject *
1174make_freplacement(PyObject *object)
1175{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001176 char freplacement[64];
1177 if (PyTime_Check(object))
1178 sprintf(freplacement, "%06d", TIME_GET_MICROSECOND(object));
1179 else if (PyDateTime_Check(object))
1180 sprintf(freplacement, "%06d", DATE_GET_MICROSECOND(object));
1181 else
1182 sprintf(freplacement, "%06d", 0);
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001183
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001184 return PyBytes_FromStringAndSize(freplacement, strlen(freplacement));
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001185}
1186
Tim Peters2a799bf2002-12-16 20:18:38 +00001187/* I sure don't want to reproduce the strftime code from the time module,
1188 * so this imports the module and calls it. All the hair is due to
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001189 * giving special meanings to the %z, %Z and %f format codes via a
1190 * preprocessing step on the format string.
Tim Petersbad8ff02002-12-30 20:52:32 +00001191 * tzinfoarg is the argument to pass to the object's tzinfo method, if
1192 * needed.
Tim Peters2a799bf2002-12-16 20:18:38 +00001193 */
1194static PyObject *
Tim Petersbad8ff02002-12-30 20:52:32 +00001195wrap_strftime(PyObject *object, PyObject *format, PyObject *timetuple,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001196 PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +00001197{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001198 PyObject *result = NULL; /* guilty until proved innocent */
Tim Peters2a799bf2002-12-16 20:18:38 +00001199
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001200 PyObject *zreplacement = NULL; /* py string, replacement for %z */
1201 PyObject *Zreplacement = NULL; /* py string, replacement for %Z */
1202 PyObject *freplacement = NULL; /* py string, replacement for %f */
Tim Peters2a799bf2002-12-16 20:18:38 +00001203
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001204 const char *pin; /* pointer to next char in input format */
1205 Py_ssize_t flen; /* length of input format */
1206 char ch; /* next char in input format */
Tim Peters2a799bf2002-12-16 20:18:38 +00001207
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001208 PyObject *newfmt = NULL; /* py string, the output format */
1209 char *pnew; /* pointer to available byte in output format */
1210 size_t totalnew; /* number bytes total in output format buffer,
1211 exclusive of trailing \0 */
1212 size_t usednew; /* number bytes used so far in output format buffer */
Tim Peters2a799bf2002-12-16 20:18:38 +00001213
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001214 const char *ptoappend; /* ptr to string to append to output buffer */
1215 Py_ssize_t ntoappend; /* # of bytes to append to output buffer */
Tim Peters2a799bf2002-12-16 20:18:38 +00001216
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001217 assert(object && format && timetuple);
1218 assert(PyUnicode_Check(format));
1219 /* Convert the input format to a C string and size */
1220 pin = _PyUnicode_AsStringAndSize(format, &flen);
1221 if (!pin)
1222 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001223
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001224 /* Give up if the year is before 1900.
1225 * Python strftime() plays games with the year, and different
1226 * games depending on whether envar PYTHON2K is set. This makes
1227 * years before 1900 a nightmare, even if the platform strftime
1228 * supports them (and not all do).
1229 * We could get a lot farther here by avoiding Python's strftime
1230 * wrapper and calling the C strftime() directly, but that isn't
1231 * an option in the Python implementation of this module.
1232 */
1233 {
1234 long year;
1235 PyObject *pyyear = PySequence_GetItem(timetuple, 0);
1236 if (pyyear == NULL) return NULL;
1237 assert(PyLong_Check(pyyear));
1238 year = PyLong_AsLong(pyyear);
1239 Py_DECREF(pyyear);
1240 if (year < 1900) {
1241 PyErr_Format(PyExc_ValueError, "year=%ld is before "
1242 "1900; the datetime strftime() "
1243 "methods require year >= 1900",
1244 year);
1245 return NULL;
1246 }
1247 }
Tim Petersd6844152002-12-22 20:58:42 +00001248
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001249 /* Scan the input format, looking for %z/%Z/%f escapes, building
1250 * a new format. Since computing the replacements for those codes
1251 * is expensive, don't unless they're actually used.
1252 */
1253 if (flen > INT_MAX - 1) {
1254 PyErr_NoMemory();
1255 goto Done;
1256 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00001257
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001258 totalnew = flen + 1; /* realistic if no %z/%Z */
1259 newfmt = PyBytes_FromStringAndSize(NULL, totalnew);
1260 if (newfmt == NULL) goto Done;
1261 pnew = PyBytes_AsString(newfmt);
1262 usednew = 0;
Tim Peters2a799bf2002-12-16 20:18:38 +00001263
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001264 while ((ch = *pin++) != '\0') {
1265 if (ch != '%') {
1266 ptoappend = pin - 1;
1267 ntoappend = 1;
1268 }
1269 else if ((ch = *pin++) == '\0') {
1270 /* There's a lone trailing %; doesn't make sense. */
1271 PyErr_SetString(PyExc_ValueError, "strftime format "
1272 "ends with raw %");
1273 goto Done;
1274 }
1275 /* A % has been seen and ch is the character after it. */
1276 else if (ch == 'z') {
1277 if (zreplacement == NULL) {
1278 /* format utcoffset */
1279 char buf[100];
1280 PyObject *tzinfo = get_tzinfo_member(object);
1281 zreplacement = PyBytes_FromStringAndSize("", 0);
1282 if (zreplacement == NULL) goto Done;
1283 if (tzinfo != Py_None && tzinfo != NULL) {
1284 assert(tzinfoarg != NULL);
1285 if (format_utcoffset(buf,
1286 sizeof(buf),
1287 "",
1288 tzinfo,
1289 tzinfoarg) < 0)
1290 goto Done;
1291 Py_DECREF(zreplacement);
1292 zreplacement =
1293 PyBytes_FromStringAndSize(buf,
1294 strlen(buf));
1295 if (zreplacement == NULL)
1296 goto Done;
1297 }
1298 }
1299 assert(zreplacement != NULL);
1300 ptoappend = PyBytes_AS_STRING(zreplacement);
1301 ntoappend = PyBytes_GET_SIZE(zreplacement);
1302 }
1303 else if (ch == 'Z') {
1304 /* format tzname */
1305 if (Zreplacement == NULL) {
1306 Zreplacement = make_Zreplacement(object,
1307 tzinfoarg);
1308 if (Zreplacement == NULL)
1309 goto Done;
1310 }
1311 assert(Zreplacement != NULL);
1312 assert(PyUnicode_Check(Zreplacement));
1313 ptoappend = _PyUnicode_AsStringAndSize(Zreplacement,
1314 &ntoappend);
1315 ntoappend = Py_SIZE(Zreplacement);
1316 }
1317 else if (ch == 'f') {
1318 /* format microseconds */
1319 if (freplacement == NULL) {
1320 freplacement = make_freplacement(object);
1321 if (freplacement == NULL)
1322 goto Done;
1323 }
1324 assert(freplacement != NULL);
1325 assert(PyBytes_Check(freplacement));
1326 ptoappend = PyBytes_AS_STRING(freplacement);
1327 ntoappend = PyBytes_GET_SIZE(freplacement);
1328 }
1329 else {
1330 /* percent followed by neither z nor Z */
1331 ptoappend = pin - 2;
1332 ntoappend = 2;
1333 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001334
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001335 /* Append the ntoappend chars starting at ptoappend to
1336 * the new format.
1337 */
1338 if (ntoappend == 0)
1339 continue;
1340 assert(ptoappend != NULL);
1341 assert(ntoappend > 0);
1342 while (usednew + ntoappend > totalnew) {
1343 size_t bigger = totalnew << 1;
1344 if ((bigger >> 1) != totalnew) { /* overflow */
1345 PyErr_NoMemory();
1346 goto Done;
1347 }
1348 if (_PyBytes_Resize(&newfmt, bigger) < 0)
1349 goto Done;
1350 totalnew = bigger;
1351 pnew = PyBytes_AsString(newfmt) + usednew;
1352 }
1353 memcpy(pnew, ptoappend, ntoappend);
1354 pnew += ntoappend;
1355 usednew += ntoappend;
1356 assert(usednew <= totalnew);
1357 } /* end while() */
Tim Peters2a799bf2002-12-16 20:18:38 +00001358
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001359 if (_PyBytes_Resize(&newfmt, usednew) < 0)
1360 goto Done;
1361 {
1362 PyObject *format;
1363 PyObject *time = PyImport_ImportModuleNoBlock("time");
1364 if (time == NULL)
1365 goto Done;
1366 format = PyUnicode_FromString(PyBytes_AS_STRING(newfmt));
1367 if (format != NULL) {
1368 result = PyObject_CallMethod(time, "strftime", "OO",
1369 format, timetuple);
1370 Py_DECREF(format);
1371 }
1372 Py_DECREF(time);
1373 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001374 Done:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001375 Py_XDECREF(freplacement);
1376 Py_XDECREF(zreplacement);
1377 Py_XDECREF(Zreplacement);
1378 Py_XDECREF(newfmt);
1379 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001380}
1381
Tim Peters2a799bf2002-12-16 20:18:38 +00001382/* ---------------------------------------------------------------------------
1383 * Wrap functions from the time module. These aren't directly available
1384 * from C. Perhaps they should be.
1385 */
1386
1387/* Call time.time() and return its result (a Python float). */
1388static PyObject *
Guido van Rossumbd43e912002-12-16 20:34:55 +00001389time_time(void)
Tim Peters2a799bf2002-12-16 20:18:38 +00001390{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001391 PyObject *result = NULL;
1392 PyObject *time = PyImport_ImportModuleNoBlock("time");
Tim Peters2a799bf2002-12-16 20:18:38 +00001393
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001394 if (time != NULL) {
1395 result = PyObject_CallMethod(time, "time", "()");
1396 Py_DECREF(time);
1397 }
1398 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001399}
1400
1401/* Build a time.struct_time. The weekday and day number are automatically
1402 * computed from the y,m,d args.
1403 */
1404static PyObject *
1405build_struct_time(int y, int m, int d, int hh, int mm, int ss, int dstflag)
1406{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001407 PyObject *time;
1408 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001409
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001410 time = PyImport_ImportModuleNoBlock("time");
1411 if (time != NULL) {
1412 result = PyObject_CallMethod(time, "struct_time",
1413 "((iiiiiiiii))",
1414 y, m, d,
1415 hh, mm, ss,
1416 weekday(y, m, d),
1417 days_before_month(y, m) + d,
1418 dstflag);
1419 Py_DECREF(time);
1420 }
1421 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001422}
1423
1424/* ---------------------------------------------------------------------------
1425 * Miscellaneous helpers.
1426 */
1427
Mark Dickinsone94c6792009-02-02 20:36:42 +00001428/* For various reasons, we need to use tp_richcompare instead of tp_reserved.
Tim Peters2a799bf2002-12-16 20:18:38 +00001429 * The comparisons here all most naturally compute a cmp()-like result.
1430 * This little helper turns that into a bool result for rich comparisons.
1431 */
1432static PyObject *
1433diff_to_bool(int diff, int op)
1434{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001435 PyObject *result;
1436 int istrue;
Tim Peters2a799bf2002-12-16 20:18:38 +00001437
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001438 switch (op) {
1439 case Py_EQ: istrue = diff == 0; break;
1440 case Py_NE: istrue = diff != 0; break;
1441 case Py_LE: istrue = diff <= 0; break;
1442 case Py_GE: istrue = diff >= 0; break;
1443 case Py_LT: istrue = diff < 0; break;
1444 case Py_GT: istrue = diff > 0; break;
1445 default:
1446 assert(! "op unknown");
1447 istrue = 0; /* To shut up compiler */
1448 }
1449 result = istrue ? Py_True : Py_False;
1450 Py_INCREF(result);
1451 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001452}
1453
Tim Peters07534a62003-02-07 22:50:28 +00001454/* Raises a "can't compare" TypeError and returns NULL. */
1455static PyObject *
1456cmperror(PyObject *a, PyObject *b)
1457{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001458 PyErr_Format(PyExc_TypeError,
1459 "can't compare %s to %s",
1460 Py_TYPE(a)->tp_name, Py_TYPE(b)->tp_name);
1461 return NULL;
Tim Peters07534a62003-02-07 22:50:28 +00001462}
1463
Tim Peters2a799bf2002-12-16 20:18:38 +00001464/* ---------------------------------------------------------------------------
Tim Peters2a799bf2002-12-16 20:18:38 +00001465 * Cached Python objects; these are set by the module init function.
1466 */
1467
1468/* Conversion factors. */
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001469static PyObject *us_per_us = NULL; /* 1 */
1470static PyObject *us_per_ms = NULL; /* 1000 */
1471static PyObject *us_per_second = NULL; /* 1000000 */
1472static PyObject *us_per_minute = NULL; /* 1e6 * 60 as Python int */
1473static PyObject *us_per_hour = NULL; /* 1e6 * 3600 as Python long */
1474static PyObject *us_per_day = NULL; /* 1e6 * 3600 * 24 as Python long */
1475static PyObject *us_per_week = NULL; /* 1e6*3600*24*7 as Python long */
Tim Peters2a799bf2002-12-16 20:18:38 +00001476static PyObject *seconds_per_day = NULL; /* 3600*24 as Python int */
1477
Tim Peters2a799bf2002-12-16 20:18:38 +00001478/* ---------------------------------------------------------------------------
1479 * Class implementations.
1480 */
1481
1482/*
1483 * PyDateTime_Delta implementation.
1484 */
1485
1486/* Convert a timedelta to a number of us,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001487 * (24*3600*self.days + self.seconds)*1000000 + self.microseconds
Tim Peters2a799bf2002-12-16 20:18:38 +00001488 * as a Python int or long.
1489 * Doing mixed-radix arithmetic by hand instead is excruciating in C,
1490 * due to ubiquitous overflow possibilities.
1491 */
1492static PyObject *
1493delta_to_microseconds(PyDateTime_Delta *self)
1494{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001495 PyObject *x1 = NULL;
1496 PyObject *x2 = NULL;
1497 PyObject *x3 = NULL;
1498 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001499
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001500 x1 = PyLong_FromLong(GET_TD_DAYS(self));
1501 if (x1 == NULL)
1502 goto Done;
1503 x2 = PyNumber_Multiply(x1, seconds_per_day); /* days in seconds */
1504 if (x2 == NULL)
1505 goto Done;
1506 Py_DECREF(x1);
1507 x1 = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001508
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001509 /* x2 has days in seconds */
1510 x1 = PyLong_FromLong(GET_TD_SECONDS(self)); /* seconds */
1511 if (x1 == NULL)
1512 goto Done;
1513 x3 = PyNumber_Add(x1, x2); /* days and seconds in seconds */
1514 if (x3 == NULL)
1515 goto Done;
1516 Py_DECREF(x1);
1517 Py_DECREF(x2);
1518 x1 = x2 = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001519
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001520 /* x3 has days+seconds in seconds */
1521 x1 = PyNumber_Multiply(x3, us_per_second); /* us */
1522 if (x1 == NULL)
1523 goto Done;
1524 Py_DECREF(x3);
1525 x3 = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001526
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001527 /* x1 has days+seconds in us */
1528 x2 = PyLong_FromLong(GET_TD_MICROSECONDS(self));
1529 if (x2 == NULL)
1530 goto Done;
1531 result = PyNumber_Add(x1, x2);
Tim Peters2a799bf2002-12-16 20:18:38 +00001532
1533Done:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001534 Py_XDECREF(x1);
1535 Py_XDECREF(x2);
1536 Py_XDECREF(x3);
1537 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001538}
1539
1540/* Convert a number of us (as a Python int or long) to a timedelta.
1541 */
1542static PyObject *
Tim Petersb0c854d2003-05-17 15:57:00 +00001543microseconds_to_delta_ex(PyObject *pyus, PyTypeObject *type)
Tim Peters2a799bf2002-12-16 20:18:38 +00001544{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001545 int us;
1546 int s;
1547 int d;
1548 long temp;
Tim Peters2a799bf2002-12-16 20:18:38 +00001549
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001550 PyObject *tuple = NULL;
1551 PyObject *num = NULL;
1552 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001553
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001554 tuple = PyNumber_Divmod(pyus, us_per_second);
1555 if (tuple == NULL)
1556 goto Done;
Tim Peters2a799bf2002-12-16 20:18:38 +00001557
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001558 num = PyTuple_GetItem(tuple, 1); /* us */
1559 if (num == NULL)
1560 goto Done;
1561 temp = PyLong_AsLong(num);
1562 num = NULL;
1563 if (temp == -1 && PyErr_Occurred())
1564 goto Done;
1565 assert(0 <= temp && temp < 1000000);
1566 us = (int)temp;
1567 if (us < 0) {
1568 /* The divisor was positive, so this must be an error. */
1569 assert(PyErr_Occurred());
1570 goto Done;
1571 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001572
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001573 num = PyTuple_GetItem(tuple, 0); /* leftover seconds */
1574 if (num == NULL)
1575 goto Done;
1576 Py_INCREF(num);
1577 Py_DECREF(tuple);
Tim Peters2a799bf2002-12-16 20:18:38 +00001578
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001579 tuple = PyNumber_Divmod(num, seconds_per_day);
1580 if (tuple == NULL)
1581 goto Done;
1582 Py_DECREF(num);
Tim Peters2a799bf2002-12-16 20:18:38 +00001583
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001584 num = PyTuple_GetItem(tuple, 1); /* seconds */
1585 if (num == NULL)
1586 goto Done;
1587 temp = PyLong_AsLong(num);
1588 num = NULL;
1589 if (temp == -1 && PyErr_Occurred())
1590 goto Done;
1591 assert(0 <= temp && temp < 24*3600);
1592 s = (int)temp;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001593
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001594 if (s < 0) {
1595 /* The divisor was positive, so this must be an error. */
1596 assert(PyErr_Occurred());
1597 goto Done;
1598 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001599
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001600 num = PyTuple_GetItem(tuple, 0); /* leftover days */
1601 if (num == NULL)
1602 goto Done;
1603 Py_INCREF(num);
1604 temp = PyLong_AsLong(num);
1605 if (temp == -1 && PyErr_Occurred())
1606 goto Done;
1607 d = (int)temp;
1608 if ((long)d != temp) {
1609 PyErr_SetString(PyExc_OverflowError, "normalized days too "
1610 "large to fit in a C int");
1611 goto Done;
1612 }
1613 result = new_delta_ex(d, s, us, 0, type);
Tim Peters2a799bf2002-12-16 20:18:38 +00001614
1615Done:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001616 Py_XDECREF(tuple);
1617 Py_XDECREF(num);
1618 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001619}
1620
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001621#define microseconds_to_delta(pymicros) \
1622 microseconds_to_delta_ex(pymicros, &PyDateTime_DeltaType)
Tim Petersb0c854d2003-05-17 15:57:00 +00001623
Tim Peters2a799bf2002-12-16 20:18:38 +00001624static PyObject *
1625multiply_int_timedelta(PyObject *intobj, PyDateTime_Delta *delta)
1626{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001627 PyObject *pyus_in;
1628 PyObject *pyus_out;
1629 PyObject *result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001630
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001631 pyus_in = delta_to_microseconds(delta);
1632 if (pyus_in == NULL)
1633 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001634
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001635 pyus_out = PyNumber_Multiply(pyus_in, intobj);
1636 Py_DECREF(pyus_in);
1637 if (pyus_out == NULL)
1638 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001639
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001640 result = microseconds_to_delta(pyus_out);
1641 Py_DECREF(pyus_out);
1642 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001643}
1644
1645static PyObject *
1646divide_timedelta_int(PyDateTime_Delta *delta, PyObject *intobj)
1647{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001648 PyObject *pyus_in;
1649 PyObject *pyus_out;
1650 PyObject *result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001651
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001652 pyus_in = delta_to_microseconds(delta);
1653 if (pyus_in == NULL)
1654 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001655
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001656 pyus_out = PyNumber_FloorDivide(pyus_in, intobj);
1657 Py_DECREF(pyus_in);
1658 if (pyus_out == NULL)
1659 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001660
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001661 result = microseconds_to_delta(pyus_out);
1662 Py_DECREF(pyus_out);
1663 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001664}
1665
1666static PyObject *
1667delta_add(PyObject *left, PyObject *right)
1668{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001669 PyObject *result = Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00001670
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001671 if (PyDelta_Check(left) && PyDelta_Check(right)) {
1672 /* delta + delta */
1673 /* The C-level additions can't overflow because of the
1674 * invariant bounds.
1675 */
1676 int days = GET_TD_DAYS(left) + GET_TD_DAYS(right);
1677 int seconds = GET_TD_SECONDS(left) + GET_TD_SECONDS(right);
1678 int microseconds = GET_TD_MICROSECONDS(left) +
1679 GET_TD_MICROSECONDS(right);
1680 result = new_delta(days, seconds, microseconds, 1);
1681 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001682
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001683 if (result == Py_NotImplemented)
1684 Py_INCREF(result);
1685 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001686}
1687
1688static PyObject *
1689delta_negative(PyDateTime_Delta *self)
1690{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001691 return new_delta(-GET_TD_DAYS(self),
1692 -GET_TD_SECONDS(self),
1693 -GET_TD_MICROSECONDS(self),
1694 1);
Tim Peters2a799bf2002-12-16 20:18:38 +00001695}
1696
1697static PyObject *
1698delta_positive(PyDateTime_Delta *self)
1699{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001700 /* Could optimize this (by returning self) if this isn't a
1701 * subclass -- but who uses unary + ? Approximately nobody.
1702 */
1703 return new_delta(GET_TD_DAYS(self),
1704 GET_TD_SECONDS(self),
1705 GET_TD_MICROSECONDS(self),
1706 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00001707}
1708
1709static PyObject *
1710delta_abs(PyDateTime_Delta *self)
1711{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001712 PyObject *result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001713
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001714 assert(GET_TD_MICROSECONDS(self) >= 0);
1715 assert(GET_TD_SECONDS(self) >= 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00001716
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001717 if (GET_TD_DAYS(self) < 0)
1718 result = delta_negative(self);
1719 else
1720 result = delta_positive(self);
Tim Peters2a799bf2002-12-16 20:18:38 +00001721
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001722 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001723}
1724
1725static PyObject *
1726delta_subtract(PyObject *left, PyObject *right)
1727{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001728 PyObject *result = Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00001729
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001730 if (PyDelta_Check(left) && PyDelta_Check(right)) {
1731 /* delta - delta */
1732 PyObject *minus_right = PyNumber_Negative(right);
1733 if (minus_right) {
1734 result = delta_add(left, minus_right);
1735 Py_DECREF(minus_right);
1736 }
1737 else
1738 result = NULL;
1739 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001740
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001741 if (result == Py_NotImplemented)
1742 Py_INCREF(result);
1743 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001744}
1745
Tim Peters2a799bf2002-12-16 20:18:38 +00001746static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00001747delta_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters2a799bf2002-12-16 20:18:38 +00001748{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001749 if (PyDelta_Check(other)) {
1750 int diff = GET_TD_DAYS(self) - GET_TD_DAYS(other);
1751 if (diff == 0) {
1752 diff = GET_TD_SECONDS(self) - GET_TD_SECONDS(other);
1753 if (diff == 0)
1754 diff = GET_TD_MICROSECONDS(self) -
1755 GET_TD_MICROSECONDS(other);
1756 }
1757 return diff_to_bool(diff, op);
1758 }
1759 else {
1760 Py_INCREF(Py_NotImplemented);
1761 return Py_NotImplemented;
1762 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001763}
1764
1765static PyObject *delta_getstate(PyDateTime_Delta *self);
1766
1767static long
1768delta_hash(PyDateTime_Delta *self)
1769{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001770 if (self->hashcode == -1) {
1771 PyObject *temp = delta_getstate(self);
1772 if (temp != NULL) {
1773 self->hashcode = PyObject_Hash(temp);
1774 Py_DECREF(temp);
1775 }
1776 }
1777 return self->hashcode;
Tim Peters2a799bf2002-12-16 20:18:38 +00001778}
1779
1780static PyObject *
1781delta_multiply(PyObject *left, PyObject *right)
1782{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001783 PyObject *result = Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00001784
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001785 if (PyDelta_Check(left)) {
1786 /* delta * ??? */
1787 if (PyLong_Check(right))
1788 result = multiply_int_timedelta(right,
1789 (PyDateTime_Delta *) left);
1790 }
1791 else if (PyLong_Check(left))
1792 result = multiply_int_timedelta(left,
1793 (PyDateTime_Delta *) right);
Tim Peters2a799bf2002-12-16 20:18:38 +00001794
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001795 if (result == Py_NotImplemented)
1796 Py_INCREF(result);
1797 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001798}
1799
1800static PyObject *
1801delta_divide(PyObject *left, PyObject *right)
1802{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001803 PyObject *result = Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00001804
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001805 if (PyDelta_Check(left)) {
1806 /* delta * ??? */
1807 if (PyLong_Check(right))
1808 result = divide_timedelta_int(
1809 (PyDateTime_Delta *)left,
1810 right);
1811 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001812
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001813 if (result == Py_NotImplemented)
1814 Py_INCREF(result);
1815 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001816}
1817
1818/* Fold in the value of the tag ("seconds", "weeks", etc) component of a
1819 * timedelta constructor. sofar is the # of microseconds accounted for
1820 * so far, and there are factor microseconds per current unit, the number
1821 * of which is given by num. num * factor is added to sofar in a
1822 * numerically careful way, and that's the result. Any fractional
1823 * microseconds left over (this can happen if num is a float type) are
1824 * added into *leftover.
1825 * Note that there are many ways this can give an error (NULL) return.
1826 */
1827static PyObject *
1828accum(const char* tag, PyObject *sofar, PyObject *num, PyObject *factor,
1829 double *leftover)
1830{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001831 PyObject *prod;
1832 PyObject *sum;
Tim Peters2a799bf2002-12-16 20:18:38 +00001833
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001834 assert(num != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +00001835
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001836 if (PyLong_Check(num)) {
1837 prod = PyNumber_Multiply(num, factor);
1838 if (prod == NULL)
1839 return NULL;
1840 sum = PyNumber_Add(sofar, prod);
1841 Py_DECREF(prod);
1842 return sum;
1843 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001844
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001845 if (PyFloat_Check(num)) {
1846 double dnum;
1847 double fracpart;
1848 double intpart;
1849 PyObject *x;
1850 PyObject *y;
Tim Peters2a799bf2002-12-16 20:18:38 +00001851
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001852 /* The Plan: decompose num into an integer part and a
1853 * fractional part, num = intpart + fracpart.
1854 * Then num * factor ==
1855 * intpart * factor + fracpart * factor
1856 * and the LHS can be computed exactly in long arithmetic.
1857 * The RHS is again broken into an int part and frac part.
1858 * and the frac part is added into *leftover.
1859 */
1860 dnum = PyFloat_AsDouble(num);
1861 if (dnum == -1.0 && PyErr_Occurred())
1862 return NULL;
1863 fracpart = modf(dnum, &intpart);
1864 x = PyLong_FromDouble(intpart);
1865 if (x == NULL)
1866 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001867
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001868 prod = PyNumber_Multiply(x, factor);
1869 Py_DECREF(x);
1870 if (prod == NULL)
1871 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001872
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001873 sum = PyNumber_Add(sofar, prod);
1874 Py_DECREF(prod);
1875 if (sum == NULL)
1876 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001877
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001878 if (fracpart == 0.0)
1879 return sum;
1880 /* So far we've lost no information. Dealing with the
1881 * fractional part requires float arithmetic, and may
1882 * lose a little info.
1883 */
1884 assert(PyLong_Check(factor));
1885 dnum = PyLong_AsDouble(factor);
Tim Peters2a799bf2002-12-16 20:18:38 +00001886
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001887 dnum *= fracpart;
1888 fracpart = modf(dnum, &intpart);
1889 x = PyLong_FromDouble(intpart);
1890 if (x == NULL) {
1891 Py_DECREF(sum);
1892 return NULL;
1893 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001894
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001895 y = PyNumber_Add(sum, x);
1896 Py_DECREF(sum);
1897 Py_DECREF(x);
1898 *leftover += fracpart;
1899 return y;
1900 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001901
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001902 PyErr_Format(PyExc_TypeError,
1903 "unsupported type for timedelta %s component: %s",
1904 tag, Py_TYPE(num)->tp_name);
1905 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001906}
1907
1908static PyObject *
1909delta_new(PyTypeObject *type, PyObject *args, PyObject *kw)
1910{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001911 PyObject *self = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001912
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001913 /* Argument objects. */
1914 PyObject *day = NULL;
1915 PyObject *second = NULL;
1916 PyObject *us = NULL;
1917 PyObject *ms = NULL;
1918 PyObject *minute = NULL;
1919 PyObject *hour = NULL;
1920 PyObject *week = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001921
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001922 PyObject *x = NULL; /* running sum of microseconds */
1923 PyObject *y = NULL; /* temp sum of microseconds */
1924 double leftover_us = 0.0;
Tim Peters2a799bf2002-12-16 20:18:38 +00001925
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001926 static char *keywords[] = {
1927 "days", "seconds", "microseconds", "milliseconds",
1928 "minutes", "hours", "weeks", NULL
1929 };
Tim Peters2a799bf2002-12-16 20:18:38 +00001930
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001931 if (PyArg_ParseTupleAndKeywords(args, kw, "|OOOOOOO:__new__",
1932 keywords,
1933 &day, &second, &us,
1934 &ms, &minute, &hour, &week) == 0)
1935 goto Done;
Tim Peters2a799bf2002-12-16 20:18:38 +00001936
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001937 x = PyLong_FromLong(0);
1938 if (x == NULL)
1939 goto Done;
Tim Peters2a799bf2002-12-16 20:18:38 +00001940
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001941#define CLEANUP \
1942 Py_DECREF(x); \
1943 x = y; \
1944 if (x == NULL) \
1945 goto Done
Tim Peters2a799bf2002-12-16 20:18:38 +00001946
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001947 if (us) {
1948 y = accum("microseconds", x, us, us_per_us, &leftover_us);
1949 CLEANUP;
1950 }
1951 if (ms) {
1952 y = accum("milliseconds", x, ms, us_per_ms, &leftover_us);
1953 CLEANUP;
1954 }
1955 if (second) {
1956 y = accum("seconds", x, second, us_per_second, &leftover_us);
1957 CLEANUP;
1958 }
1959 if (minute) {
1960 y = accum("minutes", x, minute, us_per_minute, &leftover_us);
1961 CLEANUP;
1962 }
1963 if (hour) {
1964 y = accum("hours", x, hour, us_per_hour, &leftover_us);
1965 CLEANUP;
1966 }
1967 if (day) {
1968 y = accum("days", x, day, us_per_day, &leftover_us);
1969 CLEANUP;
1970 }
1971 if (week) {
1972 y = accum("weeks", x, week, us_per_week, &leftover_us);
1973 CLEANUP;
1974 }
1975 if (leftover_us) {
1976 /* Round to nearest whole # of us, and add into x. */
1977 PyObject *temp = PyLong_FromLong(round_to_long(leftover_us));
1978 if (temp == NULL) {
1979 Py_DECREF(x);
1980 goto Done;
1981 }
1982 y = PyNumber_Add(x, temp);
1983 Py_DECREF(temp);
1984 CLEANUP;
1985 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001986
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001987 self = microseconds_to_delta_ex(x, type);
1988 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00001989Done:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001990 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00001991
1992#undef CLEANUP
1993}
1994
1995static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00001996delta_bool(PyDateTime_Delta *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00001997{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001998 return (GET_TD_DAYS(self) != 0
1999 || GET_TD_SECONDS(self) != 0
2000 || GET_TD_MICROSECONDS(self) != 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00002001}
2002
2003static PyObject *
2004delta_repr(PyDateTime_Delta *self)
2005{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002006 if (GET_TD_MICROSECONDS(self) != 0)
2007 return PyUnicode_FromFormat("%s(%d, %d, %d)",
2008 Py_TYPE(self)->tp_name,
2009 GET_TD_DAYS(self),
2010 GET_TD_SECONDS(self),
2011 GET_TD_MICROSECONDS(self));
2012 if (GET_TD_SECONDS(self) != 0)
2013 return PyUnicode_FromFormat("%s(%d, %d)",
2014 Py_TYPE(self)->tp_name,
2015 GET_TD_DAYS(self),
2016 GET_TD_SECONDS(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002017
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002018 return PyUnicode_FromFormat("%s(%d)",
2019 Py_TYPE(self)->tp_name,
2020 GET_TD_DAYS(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002021}
2022
2023static PyObject *
2024delta_str(PyDateTime_Delta *self)
2025{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002026 int us = GET_TD_MICROSECONDS(self);
2027 int seconds = GET_TD_SECONDS(self);
2028 int minutes = divmod(seconds, 60, &seconds);
2029 int hours = divmod(minutes, 60, &minutes);
2030 int days = GET_TD_DAYS(self);
Tim Peters2a799bf2002-12-16 20:18:38 +00002031
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002032 if (days) {
2033 if (us)
2034 return PyUnicode_FromFormat("%d day%s, %d:%02d:%02d.%06d",
2035 days, (days == 1 || days == -1) ? "" : "s",
2036 hours, minutes, seconds, us);
2037 else
2038 return PyUnicode_FromFormat("%d day%s, %d:%02d:%02d",
2039 days, (days == 1 || days == -1) ? "" : "s",
2040 hours, minutes, seconds);
2041 } else {
2042 if (us)
2043 return PyUnicode_FromFormat("%d:%02d:%02d.%06d",
2044 hours, minutes, seconds, us);
2045 else
2046 return PyUnicode_FromFormat("%d:%02d:%02d",
2047 hours, minutes, seconds);
2048 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002049
Tim Peters2a799bf2002-12-16 20:18:38 +00002050}
2051
Tim Peters371935f2003-02-01 01:52:50 +00002052/* Pickle support, a simple use of __reduce__. */
2053
Tim Petersb57f8f02003-02-01 02:54:15 +00002054/* __getstate__ isn't exposed */
Tim Peters2a799bf2002-12-16 20:18:38 +00002055static PyObject *
2056delta_getstate(PyDateTime_Delta *self)
2057{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002058 return Py_BuildValue("iii", GET_TD_DAYS(self),
2059 GET_TD_SECONDS(self),
2060 GET_TD_MICROSECONDS(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002061}
2062
Tim Peters2a799bf2002-12-16 20:18:38 +00002063static PyObject *
2064delta_reduce(PyDateTime_Delta* self)
2065{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002066 return Py_BuildValue("ON", Py_TYPE(self), delta_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002067}
2068
2069#define OFFSET(field) offsetof(PyDateTime_Delta, field)
2070
2071static PyMemberDef delta_members[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002072
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002073 {"days", T_INT, OFFSET(days), READONLY,
2074 PyDoc_STR("Number of days.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002075
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002076 {"seconds", T_INT, OFFSET(seconds), READONLY,
2077 PyDoc_STR("Number of seconds (>= 0 and less than 1 day).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002078
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002079 {"microseconds", T_INT, OFFSET(microseconds), READONLY,
2080 PyDoc_STR("Number of microseconds (>= 0 and less than 1 second).")},
2081 {NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00002082};
2083
2084static PyMethodDef delta_methods[] = {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002085 {"__reduce__", (PyCFunction)delta_reduce, METH_NOARGS,
2086 PyDoc_STR("__reduce__() -> (cls, state)")},
Guido van Rossum177e41a2003-01-30 22:06:23 +00002087
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002088 {NULL, NULL},
Tim Peters2a799bf2002-12-16 20:18:38 +00002089};
2090
2091static char delta_doc[] =
2092PyDoc_STR("Difference between two datetime values.");
2093
2094static PyNumberMethods delta_as_number = {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002095 delta_add, /* nb_add */
2096 delta_subtract, /* nb_subtract */
2097 delta_multiply, /* nb_multiply */
2098 0, /* nb_remainder */
2099 0, /* nb_divmod */
2100 0, /* nb_power */
2101 (unaryfunc)delta_negative, /* nb_negative */
2102 (unaryfunc)delta_positive, /* nb_positive */
2103 (unaryfunc)delta_abs, /* nb_absolute */
2104 (inquiry)delta_bool, /* nb_bool */
2105 0, /*nb_invert*/
2106 0, /*nb_lshift*/
2107 0, /*nb_rshift*/
2108 0, /*nb_and*/
2109 0, /*nb_xor*/
2110 0, /*nb_or*/
2111 0, /*nb_int*/
2112 0, /*nb_reserved*/
2113 0, /*nb_float*/
2114 0, /*nb_inplace_add*/
2115 0, /*nb_inplace_subtract*/
2116 0, /*nb_inplace_multiply*/
2117 0, /*nb_inplace_remainder*/
2118 0, /*nb_inplace_power*/
2119 0, /*nb_inplace_lshift*/
2120 0, /*nb_inplace_rshift*/
2121 0, /*nb_inplace_and*/
2122 0, /*nb_inplace_xor*/
2123 0, /*nb_inplace_or*/
2124 delta_divide, /* nb_floor_divide */
2125 0, /* nb_true_divide */
2126 0, /* nb_inplace_floor_divide */
2127 0, /* nb_inplace_true_divide */
Tim Peters2a799bf2002-12-16 20:18:38 +00002128};
2129
2130static PyTypeObject PyDateTime_DeltaType = {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002131 PyVarObject_HEAD_INIT(NULL, 0)
2132 "datetime.timedelta", /* tp_name */
2133 sizeof(PyDateTime_Delta), /* tp_basicsize */
2134 0, /* tp_itemsize */
2135 0, /* tp_dealloc */
2136 0, /* tp_print */
2137 0, /* tp_getattr */
2138 0, /* tp_setattr */
2139 0, /* tp_reserved */
2140 (reprfunc)delta_repr, /* tp_repr */
2141 &delta_as_number, /* tp_as_number */
2142 0, /* tp_as_sequence */
2143 0, /* tp_as_mapping */
2144 (hashfunc)delta_hash, /* tp_hash */
2145 0, /* tp_call */
2146 (reprfunc)delta_str, /* tp_str */
2147 PyObject_GenericGetAttr, /* tp_getattro */
2148 0, /* tp_setattro */
2149 0, /* tp_as_buffer */
2150 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
2151 delta_doc, /* tp_doc */
2152 0, /* tp_traverse */
2153 0, /* tp_clear */
2154 delta_richcompare, /* tp_richcompare */
2155 0, /* tp_weaklistoffset */
2156 0, /* tp_iter */
2157 0, /* tp_iternext */
2158 delta_methods, /* tp_methods */
2159 delta_members, /* tp_members */
2160 0, /* tp_getset */
2161 0, /* tp_base */
2162 0, /* tp_dict */
2163 0, /* tp_descr_get */
2164 0, /* tp_descr_set */
2165 0, /* tp_dictoffset */
2166 0, /* tp_init */
2167 0, /* tp_alloc */
2168 delta_new, /* tp_new */
2169 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00002170};
2171
2172/*
2173 * PyDateTime_Date implementation.
2174 */
2175
2176/* Accessor properties. */
2177
2178static PyObject *
2179date_year(PyDateTime_Date *self, void *unused)
2180{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002181 return PyLong_FromLong(GET_YEAR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002182}
2183
2184static PyObject *
2185date_month(PyDateTime_Date *self, void *unused)
2186{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002187 return PyLong_FromLong(GET_MONTH(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002188}
2189
2190static PyObject *
2191date_day(PyDateTime_Date *self, void *unused)
2192{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002193 return PyLong_FromLong(GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002194}
2195
2196static PyGetSetDef date_getset[] = {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002197 {"year", (getter)date_year},
2198 {"month", (getter)date_month},
2199 {"day", (getter)date_day},
2200 {NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00002201};
2202
2203/* Constructors. */
2204
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00002205static char *date_kws[] = {"year", "month", "day", NULL};
Tim Peters12bf3392002-12-24 05:41:27 +00002206
Tim Peters2a799bf2002-12-16 20:18:38 +00002207static PyObject *
2208date_new(PyTypeObject *type, PyObject *args, PyObject *kw)
2209{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002210 PyObject *self = NULL;
2211 PyObject *state;
2212 int year;
2213 int month;
2214 int day;
Tim Peters2a799bf2002-12-16 20:18:38 +00002215
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002216 /* Check for invocation from pickle with __getstate__ state */
2217 if (PyTuple_GET_SIZE(args) == 1 &&
2218 PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) &&
2219 PyBytes_GET_SIZE(state) == _PyDateTime_DATE_DATASIZE &&
2220 MONTH_IS_SANE(PyBytes_AS_STRING(state)[2]))
2221 {
2222 PyDateTime_Date *me;
Tim Peters70533e22003-02-01 04:40:04 +00002223
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002224 me = (PyDateTime_Date *) (type->tp_alloc(type, 0));
2225 if (me != NULL) {
2226 char *pdata = PyBytes_AS_STRING(state);
2227 memcpy(me->data, pdata, _PyDateTime_DATE_DATASIZE);
2228 me->hashcode = -1;
2229 }
2230 return (PyObject *)me;
2231 }
Guido van Rossum177e41a2003-01-30 22:06:23 +00002232
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002233 if (PyArg_ParseTupleAndKeywords(args, kw, "iii", date_kws,
2234 &year, &month, &day)) {
2235 if (check_date_args(year, month, day) < 0)
2236 return NULL;
2237 self = new_date_ex(year, month, day, type);
2238 }
2239 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00002240}
2241
2242/* Return new date from localtime(t). */
2243static PyObject *
Tim Peters1b6f7a92004-06-20 02:50:16 +00002244date_local_from_time_t(PyObject *cls, double ts)
Tim Peters2a799bf2002-12-16 20:18:38 +00002245{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002246 struct tm *tm;
2247 time_t t;
2248 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002249
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002250 t = _PyTime_DoubleToTimet(ts);
2251 if (t == (time_t)-1 && PyErr_Occurred())
2252 return NULL;
2253 tm = localtime(&t);
2254 if (tm)
2255 result = PyObject_CallFunction(cls, "iii",
2256 tm->tm_year + 1900,
2257 tm->tm_mon + 1,
2258 tm->tm_mday);
2259 else
2260 PyErr_SetString(PyExc_ValueError,
2261 "timestamp out of range for "
2262 "platform localtime() function");
2263 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002264}
2265
2266/* Return new date from current time.
2267 * We say this is equivalent to fromtimestamp(time.time()), and the
2268 * only way to be sure of that is to *call* time.time(). That's not
2269 * generally the same as calling C's time.
2270 */
2271static PyObject *
2272date_today(PyObject *cls, PyObject *dummy)
2273{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002274 PyObject *time;
2275 PyObject *result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002276
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002277 time = time_time();
2278 if (time == NULL)
2279 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002280
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002281 /* Note well: today() is a class method, so this may not call
2282 * date.fromtimestamp. For example, it may call
2283 * datetime.fromtimestamp. That's why we need all the accuracy
2284 * time.time() delivers; if someone were gonzo about optimization,
2285 * date.today() could get away with plain C time().
2286 */
2287 result = PyObject_CallMethod(cls, "fromtimestamp", "O", time);
2288 Py_DECREF(time);
2289 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002290}
2291
2292/* Return new date from given timestamp (Python timestamp -- a double). */
2293static PyObject *
2294date_fromtimestamp(PyObject *cls, PyObject *args)
2295{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002296 double timestamp;
2297 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002298
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002299 if (PyArg_ParseTuple(args, "d:fromtimestamp", &timestamp))
2300 result = date_local_from_time_t(cls, timestamp);
2301 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002302}
2303
2304/* Return new date from proleptic Gregorian ordinal. Raises ValueError if
2305 * the ordinal is out of range.
2306 */
2307static PyObject *
2308date_fromordinal(PyObject *cls, PyObject *args)
2309{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002310 PyObject *result = NULL;
2311 int ordinal;
Tim Peters2a799bf2002-12-16 20:18:38 +00002312
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002313 if (PyArg_ParseTuple(args, "i:fromordinal", &ordinal)) {
2314 int year;
2315 int month;
2316 int day;
Tim Peters2a799bf2002-12-16 20:18:38 +00002317
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002318 if (ordinal < 1)
2319 PyErr_SetString(PyExc_ValueError, "ordinal must be "
2320 ">= 1");
2321 else {
2322 ord_to_ymd(ordinal, &year, &month, &day);
2323 result = PyObject_CallFunction(cls, "iii",
2324 year, month, day);
2325 }
2326 }
2327 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002328}
2329
2330/*
2331 * Date arithmetic.
2332 */
2333
2334/* date + timedelta -> date. If arg negate is true, subtract the timedelta
2335 * instead.
2336 */
2337static PyObject *
2338add_date_timedelta(PyDateTime_Date *date, PyDateTime_Delta *delta, int negate)
2339{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002340 PyObject *result = NULL;
2341 int year = GET_YEAR(date);
2342 int month = GET_MONTH(date);
2343 int deltadays = GET_TD_DAYS(delta);
2344 /* C-level overflow is impossible because |deltadays| < 1e9. */
2345 int day = GET_DAY(date) + (negate ? -deltadays : deltadays);
Tim Peters2a799bf2002-12-16 20:18:38 +00002346
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002347 if (normalize_date(&year, &month, &day) >= 0)
2348 result = new_date(year, month, day);
2349 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002350}
2351
2352static PyObject *
2353date_add(PyObject *left, PyObject *right)
2354{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002355 if (PyDateTime_Check(left) || PyDateTime_Check(right)) {
2356 Py_INCREF(Py_NotImplemented);
2357 return Py_NotImplemented;
2358 }
2359 if (PyDate_Check(left)) {
2360 /* date + ??? */
2361 if (PyDelta_Check(right))
2362 /* date + delta */
2363 return add_date_timedelta((PyDateTime_Date *) left,
2364 (PyDateTime_Delta *) right,
2365 0);
2366 }
2367 else {
2368 /* ??? + date
2369 * 'right' must be one of us, or we wouldn't have been called
2370 */
2371 if (PyDelta_Check(left))
2372 /* delta + date */
2373 return add_date_timedelta((PyDateTime_Date *) right,
2374 (PyDateTime_Delta *) left,
2375 0);
2376 }
2377 Py_INCREF(Py_NotImplemented);
2378 return Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00002379}
2380
2381static PyObject *
2382date_subtract(PyObject *left, PyObject *right)
2383{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002384 if (PyDateTime_Check(left) || PyDateTime_Check(right)) {
2385 Py_INCREF(Py_NotImplemented);
2386 return Py_NotImplemented;
2387 }
2388 if (PyDate_Check(left)) {
2389 if (PyDate_Check(right)) {
2390 /* date - date */
2391 int left_ord = ymd_to_ord(GET_YEAR(left),
2392 GET_MONTH(left),
2393 GET_DAY(left));
2394 int right_ord = ymd_to_ord(GET_YEAR(right),
2395 GET_MONTH(right),
2396 GET_DAY(right));
2397 return new_delta(left_ord - right_ord, 0, 0, 0);
2398 }
2399 if (PyDelta_Check(right)) {
2400 /* date - delta */
2401 return add_date_timedelta((PyDateTime_Date *) left,
2402 (PyDateTime_Delta *) right,
2403 1);
2404 }
2405 }
2406 Py_INCREF(Py_NotImplemented);
2407 return Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00002408}
2409
2410
2411/* Various ways to turn a date into a string. */
2412
2413static PyObject *
2414date_repr(PyDateTime_Date *self)
2415{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002416 return PyUnicode_FromFormat("%s(%d, %d, %d)",
2417 Py_TYPE(self)->tp_name,
2418 GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002419}
2420
2421static PyObject *
2422date_isoformat(PyDateTime_Date *self)
2423{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002424 return PyUnicode_FromFormat("%04d-%02d-%02d",
2425 GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002426}
2427
Tim Peterse2df5ff2003-05-02 18:39:55 +00002428/* str() calls the appropriate isoformat() method. */
Tim Peters2a799bf2002-12-16 20:18:38 +00002429static PyObject *
2430date_str(PyDateTime_Date *self)
2431{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002432 return PyObject_CallMethod((PyObject *)self, "isoformat", "()");
Tim Peters2a799bf2002-12-16 20:18:38 +00002433}
2434
2435
2436static PyObject *
2437date_ctime(PyDateTime_Date *self)
2438{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002439 return format_ctime(self, 0, 0, 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00002440}
2441
2442static PyObject *
2443date_strftime(PyDateTime_Date *self, PyObject *args, PyObject *kw)
2444{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002445 /* This method can be inherited, and needs to call the
2446 * timetuple() method appropriate to self's class.
2447 */
2448 PyObject *result;
2449 PyObject *tuple;
2450 PyObject *format;
2451 static char *keywords[] = {"format", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00002452
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002453 if (! PyArg_ParseTupleAndKeywords(args, kw, "U:strftime", keywords,
2454 &format))
2455 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002456
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002457 tuple = PyObject_CallMethod((PyObject *)self, "timetuple", "()");
2458 if (tuple == NULL)
2459 return NULL;
2460 result = wrap_strftime((PyObject *)self, format, tuple,
2461 (PyObject *)self);
2462 Py_DECREF(tuple);
2463 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002464}
2465
Eric Smith1ba31142007-09-11 18:06:02 +00002466static PyObject *
2467date_format(PyDateTime_Date *self, PyObject *args)
2468{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002469 PyObject *format;
Eric Smith1ba31142007-09-11 18:06:02 +00002470
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002471 if (!PyArg_ParseTuple(args, "U:__format__", &format))
2472 return NULL;
Eric Smith1ba31142007-09-11 18:06:02 +00002473
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002474 /* if the format is zero length, return str(self) */
2475 if (PyUnicode_GetSize(format) == 0)
2476 return PyObject_Str((PyObject *)self);
Eric Smith1ba31142007-09-11 18:06:02 +00002477
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002478 return PyObject_CallMethod((PyObject *)self, "strftime", "O", format);
Eric Smith1ba31142007-09-11 18:06:02 +00002479}
2480
Tim Peters2a799bf2002-12-16 20:18:38 +00002481/* ISO methods. */
2482
2483static PyObject *
2484date_isoweekday(PyDateTime_Date *self)
2485{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002486 int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002487
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002488 return PyLong_FromLong(dow + 1);
Tim Peters2a799bf2002-12-16 20:18:38 +00002489}
2490
2491static PyObject *
2492date_isocalendar(PyDateTime_Date *self)
2493{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002494 int year = GET_YEAR(self);
2495 int week1_monday = iso_week1_monday(year);
2496 int today = ymd_to_ord(year, GET_MONTH(self), GET_DAY(self));
2497 int week;
2498 int day;
Tim Peters2a799bf2002-12-16 20:18:38 +00002499
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002500 week = divmod(today - week1_monday, 7, &day);
2501 if (week < 0) {
2502 --year;
2503 week1_monday = iso_week1_monday(year);
2504 week = divmod(today - week1_monday, 7, &day);
2505 }
2506 else if (week >= 52 && today >= iso_week1_monday(year + 1)) {
2507 ++year;
2508 week = 0;
2509 }
2510 return Py_BuildValue("iii", year, week + 1, day + 1);
Tim Peters2a799bf2002-12-16 20:18:38 +00002511}
2512
2513/* Miscellaneous methods. */
2514
Tim Peters2a799bf2002-12-16 20:18:38 +00002515static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00002516date_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters2a799bf2002-12-16 20:18:38 +00002517{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002518 if (PyDate_Check(other)) {
2519 int diff = memcmp(((PyDateTime_Date *)self)->data,
2520 ((PyDateTime_Date *)other)->data,
2521 _PyDateTime_DATE_DATASIZE);
2522 return diff_to_bool(diff, op);
2523 }
2524 else {
2525 Py_INCREF(Py_NotImplemented);
2526 return Py_NotImplemented;
2527 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002528}
2529
2530static PyObject *
2531date_timetuple(PyDateTime_Date *self)
2532{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002533 return build_struct_time(GET_YEAR(self),
2534 GET_MONTH(self),
2535 GET_DAY(self),
2536 0, 0, 0, -1);
Tim Peters2a799bf2002-12-16 20:18:38 +00002537}
2538
Tim Peters12bf3392002-12-24 05:41:27 +00002539static PyObject *
2540date_replace(PyDateTime_Date *self, PyObject *args, PyObject *kw)
2541{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002542 PyObject *clone;
2543 PyObject *tuple;
2544 int year = GET_YEAR(self);
2545 int month = GET_MONTH(self);
2546 int day = GET_DAY(self);
Tim Peters12bf3392002-12-24 05:41:27 +00002547
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002548 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iii:replace", date_kws,
2549 &year, &month, &day))
2550 return NULL;
2551 tuple = Py_BuildValue("iii", year, month, day);
2552 if (tuple == NULL)
2553 return NULL;
2554 clone = date_new(Py_TYPE(self), tuple, NULL);
2555 Py_DECREF(tuple);
2556 return clone;
Tim Peters12bf3392002-12-24 05:41:27 +00002557}
2558
Guido van Rossumfd53fd62007-08-24 04:05:13 +00002559/*
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002560 Borrowed from stringobject.c, originally it was string_hash()
Guido van Rossumfd53fd62007-08-24 04:05:13 +00002561*/
2562static long
2563generic_hash(unsigned char *data, int len)
2564{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002565 register unsigned char *p;
2566 register long x;
Guido van Rossumfd53fd62007-08-24 04:05:13 +00002567
Benjamin Peterson69e97272012-02-21 11:08:50 -05002568 assert(_Py_HashSecret_Initialized);
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002569 p = (unsigned char *) data;
Georg Brandl2daf6ae2012-02-20 19:54:16 +01002570 x = _Py_HashSecret.prefix;
2571 x ^= *p << 7;
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002572 while (--len >= 0)
2573 x = (1000003*x) ^ *p++;
2574 x ^= len;
Georg Brandl2daf6ae2012-02-20 19:54:16 +01002575 x ^= _Py_HashSecret.suffix;
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002576 if (x == -1)
2577 x = -2;
Guido van Rossumfd53fd62007-08-24 04:05:13 +00002578
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002579 return x;
Guido van Rossumfd53fd62007-08-24 04:05:13 +00002580}
2581
2582
2583static PyObject *date_getstate(PyDateTime_Date *self);
Tim Peters2a799bf2002-12-16 20:18:38 +00002584
2585static long
2586date_hash(PyDateTime_Date *self)
2587{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002588 if (self->hashcode == -1)
2589 self->hashcode = generic_hash(
2590 (unsigned char *)self->data, _PyDateTime_DATE_DATASIZE);
Guido van Rossum254348e2007-11-21 19:29:53 +00002591
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002592 return self->hashcode;
Tim Peters2a799bf2002-12-16 20:18:38 +00002593}
2594
2595static PyObject *
2596date_toordinal(PyDateTime_Date *self)
2597{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002598 return PyLong_FromLong(ymd_to_ord(GET_YEAR(self), GET_MONTH(self),
2599 GET_DAY(self)));
Tim Peters2a799bf2002-12-16 20:18:38 +00002600}
2601
2602static PyObject *
2603date_weekday(PyDateTime_Date *self)
2604{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002605 int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002606
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002607 return PyLong_FromLong(dow);
Tim Peters2a799bf2002-12-16 20:18:38 +00002608}
2609
Tim Peters371935f2003-02-01 01:52:50 +00002610/* Pickle support, a simple use of __reduce__. */
Tim Peters2a799bf2002-12-16 20:18:38 +00002611
Tim Petersb57f8f02003-02-01 02:54:15 +00002612/* __getstate__ isn't exposed */
Tim Peters2a799bf2002-12-16 20:18:38 +00002613static PyObject *
Guido van Rossumfd53fd62007-08-24 04:05:13 +00002614date_getstate(PyDateTime_Date *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00002615{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002616 PyObject* field;
2617 field = PyBytes_FromStringAndSize((char*)self->data,
2618 _PyDateTime_DATE_DATASIZE);
2619 return Py_BuildValue("(N)", field);
Tim Peters2a799bf2002-12-16 20:18:38 +00002620}
2621
2622static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00002623date_reduce(PyDateTime_Date *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00002624{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002625 return Py_BuildValue("(ON)", Py_TYPE(self), date_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002626}
2627
2628static PyMethodDef date_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002629
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002630 /* Class methods: */
Guido van Rossum177e41a2003-01-30 22:06:23 +00002631
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002632 {"fromtimestamp", (PyCFunction)date_fromtimestamp, METH_VARARGS |
2633 METH_CLASS,
2634 PyDoc_STR("timestamp -> local date from a POSIX timestamp (like "
2635 "time.time()).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002636
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002637 {"fromordinal", (PyCFunction)date_fromordinal, METH_VARARGS |
2638 METH_CLASS,
2639 PyDoc_STR("int -> date corresponding to a proleptic Gregorian "
2640 "ordinal.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002641
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002642 {"today", (PyCFunction)date_today, METH_NOARGS | METH_CLASS,
2643 PyDoc_STR("Current date or datetime: same as "
2644 "self.__class__.fromtimestamp(time.time()).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002645
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002646 /* Instance methods: */
Tim Peters2a799bf2002-12-16 20:18:38 +00002647
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002648 {"ctime", (PyCFunction)date_ctime, METH_NOARGS,
2649 PyDoc_STR("Return ctime() style string.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002650
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002651 {"strftime", (PyCFunction)date_strftime, METH_VARARGS | METH_KEYWORDS,
2652 PyDoc_STR("format -> strftime() style string.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002653
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002654 {"__format__", (PyCFunction)date_format, METH_VARARGS,
2655 PyDoc_STR("Formats self with strftime.")},
Eric Smith1ba31142007-09-11 18:06:02 +00002656
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002657 {"timetuple", (PyCFunction)date_timetuple, METH_NOARGS,
2658 PyDoc_STR("Return time tuple, compatible with time.localtime().")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002659
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002660 {"isocalendar", (PyCFunction)date_isocalendar, METH_NOARGS,
2661 PyDoc_STR("Return a 3-tuple containing ISO year, week number, and "
2662 "weekday.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002663
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002664 {"isoformat", (PyCFunction)date_isoformat, METH_NOARGS,
2665 PyDoc_STR("Return string in ISO 8601 format, YYYY-MM-DD.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002666
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002667 {"isoweekday", (PyCFunction)date_isoweekday, METH_NOARGS,
2668 PyDoc_STR("Return the day of the week represented by the date.\n"
2669 "Monday == 1 ... Sunday == 7")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002670
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002671 {"toordinal", (PyCFunction)date_toordinal, METH_NOARGS,
2672 PyDoc_STR("Return proleptic Gregorian ordinal. January 1 of year "
2673 "1 is day 1.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002674
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002675 {"weekday", (PyCFunction)date_weekday, METH_NOARGS,
2676 PyDoc_STR("Return the day of the week represented by the date.\n"
2677 "Monday == 0 ... Sunday == 6")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002678
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002679 {"replace", (PyCFunction)date_replace, METH_VARARGS | METH_KEYWORDS,
2680 PyDoc_STR("Return date with new specified fields.")},
Tim Peters12bf3392002-12-24 05:41:27 +00002681
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002682 {"__reduce__", (PyCFunction)date_reduce, METH_NOARGS,
2683 PyDoc_STR("__reduce__() -> (cls, state)")},
Guido van Rossum177e41a2003-01-30 22:06:23 +00002684
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002685 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00002686};
2687
2688static char date_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00002689PyDoc_STR("date(year, month, day) --> date object");
Tim Peters2a799bf2002-12-16 20:18:38 +00002690
2691static PyNumberMethods date_as_number = {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002692 date_add, /* nb_add */
2693 date_subtract, /* nb_subtract */
2694 0, /* nb_multiply */
2695 0, /* nb_remainder */
2696 0, /* nb_divmod */
2697 0, /* nb_power */
2698 0, /* nb_negative */
2699 0, /* nb_positive */
2700 0, /* nb_absolute */
2701 0, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00002702};
2703
2704static PyTypeObject PyDateTime_DateType = {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002705 PyVarObject_HEAD_INIT(NULL, 0)
2706 "datetime.date", /* tp_name */
2707 sizeof(PyDateTime_Date), /* tp_basicsize */
2708 0, /* tp_itemsize */
2709 0, /* tp_dealloc */
2710 0, /* tp_print */
2711 0, /* tp_getattr */
2712 0, /* tp_setattr */
2713 0, /* tp_reserved */
2714 (reprfunc)date_repr, /* tp_repr */
2715 &date_as_number, /* tp_as_number */
2716 0, /* tp_as_sequence */
2717 0, /* tp_as_mapping */
2718 (hashfunc)date_hash, /* tp_hash */
2719 0, /* tp_call */
2720 (reprfunc)date_str, /* tp_str */
2721 PyObject_GenericGetAttr, /* tp_getattro */
2722 0, /* tp_setattro */
2723 0, /* tp_as_buffer */
2724 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
2725 date_doc, /* tp_doc */
2726 0, /* tp_traverse */
2727 0, /* tp_clear */
2728 date_richcompare, /* tp_richcompare */
2729 0, /* tp_weaklistoffset */
2730 0, /* tp_iter */
2731 0, /* tp_iternext */
2732 date_methods, /* tp_methods */
2733 0, /* tp_members */
2734 date_getset, /* tp_getset */
2735 0, /* tp_base */
2736 0, /* tp_dict */
2737 0, /* tp_descr_get */
2738 0, /* tp_descr_set */
2739 0, /* tp_dictoffset */
2740 0, /* tp_init */
2741 0, /* tp_alloc */
2742 date_new, /* tp_new */
2743 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00002744};
2745
2746/*
Tim Peters2a799bf2002-12-16 20:18:38 +00002747 * PyDateTime_TZInfo implementation.
2748 */
2749
2750/* This is a pure abstract base class, so doesn't do anything beyond
2751 * raising NotImplemented exceptions. Real tzinfo classes need
2752 * to derive from this. This is mostly for clarity, and for efficiency in
Tim Petersa9bc1682003-01-11 03:39:11 +00002753 * datetime and time constructors (their tzinfo arguments need to
Tim Peters2a799bf2002-12-16 20:18:38 +00002754 * be subclasses of this tzinfo class, which is easy and quick to check).
2755 *
2756 * Note: For reasons having to do with pickling of subclasses, we have
2757 * to allow tzinfo objects to be instantiated. This wasn't an issue
2758 * in the Python implementation (__init__() could raise NotImplementedError
2759 * there without ill effect), but doing so in the C implementation hit a
2760 * brick wall.
2761 */
2762
2763static PyObject *
2764tzinfo_nogo(const char* methodname)
2765{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002766 PyErr_Format(PyExc_NotImplementedError,
2767 "a tzinfo subclass must implement %s()",
2768 methodname);
2769 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002770}
2771
2772/* Methods. A subclass must implement these. */
2773
Tim Peters52dcce22003-01-23 16:36:11 +00002774static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002775tzinfo_tzname(PyDateTime_TZInfo *self, PyObject *dt)
2776{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002777 return tzinfo_nogo("tzname");
Tim Peters2a799bf2002-12-16 20:18:38 +00002778}
2779
Tim Peters52dcce22003-01-23 16:36:11 +00002780static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002781tzinfo_utcoffset(PyDateTime_TZInfo *self, PyObject *dt)
2782{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002783 return tzinfo_nogo("utcoffset");
Tim Peters2a799bf2002-12-16 20:18:38 +00002784}
2785
Tim Peters52dcce22003-01-23 16:36:11 +00002786static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002787tzinfo_dst(PyDateTime_TZInfo *self, PyObject *dt)
2788{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002789 return tzinfo_nogo("dst");
Tim Peters2a799bf2002-12-16 20:18:38 +00002790}
2791
Tim Peters52dcce22003-01-23 16:36:11 +00002792static PyObject *
2793tzinfo_fromutc(PyDateTime_TZInfo *self, PyDateTime_DateTime *dt)
2794{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002795 int y, m, d, hh, mm, ss, us;
Tim Peters52dcce22003-01-23 16:36:11 +00002796
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002797 PyObject *result;
2798 int off, dst;
2799 int none;
2800 int delta;
Tim Peters52dcce22003-01-23 16:36:11 +00002801
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002802 if (! PyDateTime_Check(dt)) {
2803 PyErr_SetString(PyExc_TypeError,
2804 "fromutc: argument must be a datetime");
2805 return NULL;
2806 }
2807 if (! HASTZINFO(dt) || dt->tzinfo != (PyObject *)self) {
2808 PyErr_SetString(PyExc_ValueError, "fromutc: dt.tzinfo "
2809 "is not self");
2810 return NULL;
2811 }
Tim Peters52dcce22003-01-23 16:36:11 +00002812
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002813 off = call_utcoffset(dt->tzinfo, (PyObject *)dt, &none);
2814 if (off == -1 && PyErr_Occurred())
2815 return NULL;
2816 if (none) {
2817 PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
2818 "utcoffset() result required");
2819 return NULL;
2820 }
Tim Peters52dcce22003-01-23 16:36:11 +00002821
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002822 dst = call_dst(dt->tzinfo, (PyObject *)dt, &none);
2823 if (dst == -1 && PyErr_Occurred())
2824 return NULL;
2825 if (none) {
2826 PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
2827 "dst() result required");
2828 return NULL;
2829 }
Tim Peters52dcce22003-01-23 16:36:11 +00002830
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002831 y = GET_YEAR(dt);
2832 m = GET_MONTH(dt);
2833 d = GET_DAY(dt);
2834 hh = DATE_GET_HOUR(dt);
2835 mm = DATE_GET_MINUTE(dt);
2836 ss = DATE_GET_SECOND(dt);
2837 us = DATE_GET_MICROSECOND(dt);
Tim Peters52dcce22003-01-23 16:36:11 +00002838
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002839 delta = off - dst;
2840 mm += delta;
2841 if ((mm < 0 || mm >= 60) &&
2842 normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
2843 return NULL;
2844 result = new_datetime(y, m, d, hh, mm, ss, us, dt->tzinfo);
2845 if (result == NULL)
2846 return result;
Tim Peters52dcce22003-01-23 16:36:11 +00002847
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002848 dst = call_dst(dt->tzinfo, result, &none);
2849 if (dst == -1 && PyErr_Occurred())
2850 goto Fail;
2851 if (none)
2852 goto Inconsistent;
2853 if (dst == 0)
2854 return result;
Tim Peters52dcce22003-01-23 16:36:11 +00002855
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002856 mm += dst;
2857 if ((mm < 0 || mm >= 60) &&
2858 normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
2859 goto Fail;
2860 Py_DECREF(result);
2861 result = new_datetime(y, m, d, hh, mm, ss, us, dt->tzinfo);
2862 return result;
Tim Peters52dcce22003-01-23 16:36:11 +00002863
2864Inconsistent:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002865 PyErr_SetString(PyExc_ValueError, "fromutc: tz.dst() gave"
2866 "inconsistent results; cannot convert");
Tim Peters52dcce22003-01-23 16:36:11 +00002867
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002868 /* fall thru to failure */
Tim Peters52dcce22003-01-23 16:36:11 +00002869Fail:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002870 Py_DECREF(result);
2871 return NULL;
Tim Peters52dcce22003-01-23 16:36:11 +00002872}
2873
Tim Peters2a799bf2002-12-16 20:18:38 +00002874/*
2875 * Pickle support. This is solely so that tzinfo subclasses can use
Guido van Rossum177e41a2003-01-30 22:06:23 +00002876 * pickling -- tzinfo itself is supposed to be uninstantiable.
Tim Peters2a799bf2002-12-16 20:18:38 +00002877 */
2878
Guido van Rossum177e41a2003-01-30 22:06:23 +00002879static PyObject *
2880tzinfo_reduce(PyObject *self)
2881{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002882 PyObject *args, *state, *tmp;
2883 PyObject *getinitargs, *getstate;
Tim Peters2a799bf2002-12-16 20:18:38 +00002884
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002885 tmp = PyTuple_New(0);
2886 if (tmp == NULL)
2887 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002888
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002889 getinitargs = PyObject_GetAttrString(self, "__getinitargs__");
2890 if (getinitargs != NULL) {
2891 args = PyObject_CallObject(getinitargs, tmp);
2892 Py_DECREF(getinitargs);
2893 if (args == NULL) {
2894 Py_DECREF(tmp);
2895 return NULL;
2896 }
2897 }
2898 else {
2899 PyErr_Clear();
2900 args = tmp;
2901 Py_INCREF(args);
2902 }
Guido van Rossum177e41a2003-01-30 22:06:23 +00002903
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002904 getstate = PyObject_GetAttrString(self, "__getstate__");
2905 if (getstate != NULL) {
2906 state = PyObject_CallObject(getstate, tmp);
2907 Py_DECREF(getstate);
2908 if (state == NULL) {
2909 Py_DECREF(args);
2910 Py_DECREF(tmp);
2911 return NULL;
2912 }
2913 }
2914 else {
2915 PyObject **dictptr;
2916 PyErr_Clear();
2917 state = Py_None;
2918 dictptr = _PyObject_GetDictPtr(self);
2919 if (dictptr && *dictptr && PyDict_Size(*dictptr))
2920 state = *dictptr;
2921 Py_INCREF(state);
2922 }
Guido van Rossum177e41a2003-01-30 22:06:23 +00002923
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002924 Py_DECREF(tmp);
Guido van Rossum177e41a2003-01-30 22:06:23 +00002925
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002926 if (state == Py_None) {
2927 Py_DECREF(state);
2928 return Py_BuildValue("(ON)", Py_TYPE(self), args);
2929 }
2930 else
2931 return Py_BuildValue("(ONN)", Py_TYPE(self), args, state);
Guido van Rossum177e41a2003-01-30 22:06:23 +00002932}
Tim Peters2a799bf2002-12-16 20:18:38 +00002933
2934static PyMethodDef tzinfo_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002935
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002936 {"tzname", (PyCFunction)tzinfo_tzname, METH_O,
2937 PyDoc_STR("datetime -> string name of time zone.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002938
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002939 {"utcoffset", (PyCFunction)tzinfo_utcoffset, METH_O,
2940 PyDoc_STR("datetime -> minutes east of UTC (negative for "
2941 "west of UTC).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002942
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002943 {"dst", (PyCFunction)tzinfo_dst, METH_O,
2944 PyDoc_STR("datetime -> DST offset in minutes east of UTC.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002945
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002946 {"fromutc", (PyCFunction)tzinfo_fromutc, METH_O,
Georg Brandlc62efa82010-07-11 10:41:07 +00002947 PyDoc_STR("datetime -> timedelta showing offset from UTC, negative "
2948 "values indicating West of UTC")},
Tim Peters52dcce22003-01-23 16:36:11 +00002949
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002950 {"__reduce__", (PyCFunction)tzinfo_reduce, METH_NOARGS,
2951 PyDoc_STR("-> (cls, state)")},
Guido van Rossum177e41a2003-01-30 22:06:23 +00002952
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002953 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00002954};
2955
2956static char tzinfo_doc[] =
2957PyDoc_STR("Abstract base class for time zone info objects.");
2958
Neal Norwitz227b5332006-03-22 09:28:35 +00002959static PyTypeObject PyDateTime_TZInfoType = {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002960 PyVarObject_HEAD_INIT(NULL, 0)
2961 "datetime.tzinfo", /* tp_name */
2962 sizeof(PyDateTime_TZInfo), /* tp_basicsize */
2963 0, /* tp_itemsize */
2964 0, /* tp_dealloc */
2965 0, /* tp_print */
2966 0, /* tp_getattr */
2967 0, /* tp_setattr */
2968 0, /* tp_reserved */
2969 0, /* tp_repr */
2970 0, /* tp_as_number */
2971 0, /* tp_as_sequence */
2972 0, /* tp_as_mapping */
2973 0, /* tp_hash */
2974 0, /* tp_call */
2975 0, /* tp_str */
2976 PyObject_GenericGetAttr, /* tp_getattro */
2977 0, /* tp_setattro */
2978 0, /* tp_as_buffer */
2979 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
2980 tzinfo_doc, /* tp_doc */
2981 0, /* tp_traverse */
2982 0, /* tp_clear */
2983 0, /* tp_richcompare */
2984 0, /* tp_weaklistoffset */
2985 0, /* tp_iter */
2986 0, /* tp_iternext */
2987 tzinfo_methods, /* tp_methods */
2988 0, /* tp_members */
2989 0, /* tp_getset */
2990 0, /* tp_base */
2991 0, /* tp_dict */
2992 0, /* tp_descr_get */
2993 0, /* tp_descr_set */
2994 0, /* tp_dictoffset */
2995 0, /* tp_init */
2996 0, /* tp_alloc */
2997 PyType_GenericNew, /* tp_new */
2998 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00002999};
3000
3001/*
Tim Peters37f39822003-01-10 03:49:02 +00003002 * PyDateTime_Time implementation.
Tim Peters2a799bf2002-12-16 20:18:38 +00003003 */
3004
Tim Peters37f39822003-01-10 03:49:02 +00003005/* Accessor properties.
Tim Peters2a799bf2002-12-16 20:18:38 +00003006 */
3007
3008static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003009time_hour(PyDateTime_Time *self, void *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00003010{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003011 return PyLong_FromLong(TIME_GET_HOUR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00003012}
3013
Tim Peters37f39822003-01-10 03:49:02 +00003014static PyObject *
3015time_minute(PyDateTime_Time *self, void *unused)
3016{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003017 return PyLong_FromLong(TIME_GET_MINUTE(self));
Tim Peters37f39822003-01-10 03:49:02 +00003018}
3019
3020/* The name time_second conflicted with some platform header file. */
3021static PyObject *
3022py_time_second(PyDateTime_Time *self, void *unused)
3023{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003024 return PyLong_FromLong(TIME_GET_SECOND(self));
Tim Peters37f39822003-01-10 03:49:02 +00003025}
3026
3027static PyObject *
3028time_microsecond(PyDateTime_Time *self, void *unused)
3029{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003030 return PyLong_FromLong(TIME_GET_MICROSECOND(self));
Tim Peters37f39822003-01-10 03:49:02 +00003031}
3032
3033static PyObject *
3034time_tzinfo(PyDateTime_Time *self, void *unused)
3035{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003036 PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
3037 Py_INCREF(result);
3038 return result;
Tim Peters37f39822003-01-10 03:49:02 +00003039}
3040
3041static PyGetSetDef time_getset[] = {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003042 {"hour", (getter)time_hour},
3043 {"minute", (getter)time_minute},
3044 {"second", (getter)py_time_second},
3045 {"microsecond", (getter)time_microsecond},
3046 {"tzinfo", (getter)time_tzinfo},
3047 {NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00003048};
3049
3050/*
3051 * Constructors.
3052 */
3053
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003054static char *time_kws[] = {"hour", "minute", "second", "microsecond",
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003055 "tzinfo", NULL};
Tim Peters12bf3392002-12-24 05:41:27 +00003056
Tim Peters2a799bf2002-12-16 20:18:38 +00003057static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003058time_new(PyTypeObject *type, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003059{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003060 PyObject *self = NULL;
3061 PyObject *state;
3062 int hour = 0;
3063 int minute = 0;
3064 int second = 0;
3065 int usecond = 0;
3066 PyObject *tzinfo = Py_None;
Tim Peters2a799bf2002-12-16 20:18:38 +00003067
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003068 /* Check for invocation from pickle with __getstate__ state */
3069 if (PyTuple_GET_SIZE(args) >= 1 &&
3070 PyTuple_GET_SIZE(args) <= 2 &&
3071 PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) &&
3072 PyBytes_GET_SIZE(state) == _PyDateTime_TIME_DATASIZE &&
3073 ((unsigned char) (PyBytes_AS_STRING(state)[0])) < 24)
3074 {
3075 PyDateTime_Time *me;
3076 char aware;
Tim Peters70533e22003-02-01 04:40:04 +00003077
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003078 if (PyTuple_GET_SIZE(args) == 2) {
3079 tzinfo = PyTuple_GET_ITEM(args, 1);
3080 if (check_tzinfo_subclass(tzinfo) < 0) {
3081 PyErr_SetString(PyExc_TypeError, "bad "
3082 "tzinfo state arg");
3083 return NULL;
3084 }
3085 }
3086 aware = (char)(tzinfo != Py_None);
3087 me = (PyDateTime_Time *) (type->tp_alloc(type, aware));
3088 if (me != NULL) {
3089 char *pdata = PyBytes_AS_STRING(state);
Tim Peters70533e22003-02-01 04:40:04 +00003090
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003091 memcpy(me->data, pdata, _PyDateTime_TIME_DATASIZE);
3092 me->hashcode = -1;
3093 me->hastzinfo = aware;
3094 if (aware) {
3095 Py_INCREF(tzinfo);
3096 me->tzinfo = tzinfo;
3097 }
3098 }
3099 return (PyObject *)me;
3100 }
Guido van Rossum177e41a2003-01-30 22:06:23 +00003101
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003102 if (PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO", time_kws,
3103 &hour, &minute, &second, &usecond,
3104 &tzinfo)) {
3105 if (check_time_args(hour, minute, second, usecond) < 0)
3106 return NULL;
3107 if (check_tzinfo_subclass(tzinfo) < 0)
3108 return NULL;
3109 self = new_time_ex(hour, minute, second, usecond, tzinfo,
3110 type);
3111 }
3112 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00003113}
3114
3115/*
3116 * Destructor.
3117 */
3118
3119static void
Tim Peters37f39822003-01-10 03:49:02 +00003120time_dealloc(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003121{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003122 if (HASTZINFO(self)) {
3123 Py_XDECREF(self->tzinfo);
3124 }
3125 Py_TYPE(self)->tp_free((PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00003126}
3127
3128/*
Tim Peters855fe882002-12-22 03:43:39 +00003129 * Indirect access to tzinfo methods.
Tim Peters2a799bf2002-12-16 20:18:38 +00003130 */
3131
Tim Peters2a799bf2002-12-16 20:18:38 +00003132/* These are all METH_NOARGS, so don't need to check the arglist. */
3133static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003134time_utcoffset(PyDateTime_Time *self, PyObject *unused) {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003135 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
3136 "utcoffset", Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00003137}
3138
3139static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003140time_dst(PyDateTime_Time *self, PyObject *unused) {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003141 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
3142 "dst", Py_None);
Tim Peters855fe882002-12-22 03:43:39 +00003143}
3144
3145static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003146time_tzname(PyDateTime_Time *self, PyObject *unused) {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003147 return call_tzname(HASTZINFO(self) ? self->tzinfo : Py_None,
3148 Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00003149}
3150
3151/*
Tim Peters37f39822003-01-10 03:49:02 +00003152 * Various ways to turn a time into a string.
Tim Peters2a799bf2002-12-16 20:18:38 +00003153 */
3154
3155static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003156time_repr(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003157{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003158 const char *type_name = Py_TYPE(self)->tp_name;
3159 int h = TIME_GET_HOUR(self);
3160 int m = TIME_GET_MINUTE(self);
3161 int s = TIME_GET_SECOND(self);
3162 int us = TIME_GET_MICROSECOND(self);
3163 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00003164
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003165 if (us)
3166 result = PyUnicode_FromFormat("%s(%d, %d, %d, %d)",
3167 type_name, h, m, s, us);
3168 else if (s)
3169 result = PyUnicode_FromFormat("%s(%d, %d, %d)",
3170 type_name, h, m, s);
3171 else
3172 result = PyUnicode_FromFormat("%s(%d, %d)", type_name, h, m);
3173 if (result != NULL && HASTZINFO(self))
3174 result = append_keyword_tzinfo(result, self->tzinfo);
3175 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00003176}
3177
Tim Peters37f39822003-01-10 03:49:02 +00003178static PyObject *
3179time_str(PyDateTime_Time *self)
3180{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003181 return PyObject_CallMethod((PyObject *)self, "isoformat", "()");
Tim Peters37f39822003-01-10 03:49:02 +00003182}
Tim Peters2a799bf2002-12-16 20:18:38 +00003183
3184static PyObject *
Thomas Wouterscf297e42007-02-23 15:07:44 +00003185time_isoformat(PyDateTime_Time *self, PyObject *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00003186{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003187 char buf[100];
3188 PyObject *result;
3189 int us = TIME_GET_MICROSECOND(self);;
Tim Peters2a799bf2002-12-16 20:18:38 +00003190
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003191 if (us)
3192 result = PyUnicode_FromFormat("%02d:%02d:%02d.%06d",
3193 TIME_GET_HOUR(self),
3194 TIME_GET_MINUTE(self),
3195 TIME_GET_SECOND(self),
3196 us);
3197 else
3198 result = PyUnicode_FromFormat("%02d:%02d:%02d",
3199 TIME_GET_HOUR(self),
3200 TIME_GET_MINUTE(self),
3201 TIME_GET_SECOND(self));
Tim Peters37f39822003-01-10 03:49:02 +00003202
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003203 if (result == NULL || ! HASTZINFO(self) || self->tzinfo == Py_None)
3204 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00003205
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003206 /* We need to append the UTC offset. */
3207 if (format_utcoffset(buf, sizeof(buf), ":", self->tzinfo,
3208 Py_None) < 0) {
3209 Py_DECREF(result);
3210 return NULL;
3211 }
3212 PyUnicode_AppendAndDel(&result, PyUnicode_FromString(buf));
3213 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00003214}
3215
Tim Peters37f39822003-01-10 03:49:02 +00003216static PyObject *
3217time_strftime(PyDateTime_Time *self, PyObject *args, PyObject *kw)
3218{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003219 PyObject *result;
3220 PyObject *tuple;
3221 PyObject *format;
3222 static char *keywords[] = {"format", NULL};
Tim Peters37f39822003-01-10 03:49:02 +00003223
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003224 if (! PyArg_ParseTupleAndKeywords(args, kw, "U:strftime", keywords,
3225 &format))
3226 return NULL;
Tim Peters37f39822003-01-10 03:49:02 +00003227
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003228 /* Python's strftime does insane things with the year part of the
3229 * timetuple. The year is forced to (the otherwise nonsensical)
3230 * 1900 to worm around that.
3231 */
3232 tuple = Py_BuildValue("iiiiiiiii",
3233 1900, 1, 1, /* year, month, day */
3234 TIME_GET_HOUR(self),
3235 TIME_GET_MINUTE(self),
3236 TIME_GET_SECOND(self),
3237 0, 1, -1); /* weekday, daynum, dst */
3238 if (tuple == NULL)
3239 return NULL;
3240 assert(PyTuple_Size(tuple) == 9);
3241 result = wrap_strftime((PyObject *)self, format, tuple,
3242 Py_None);
3243 Py_DECREF(tuple);
3244 return result;
Tim Peters37f39822003-01-10 03:49:02 +00003245}
Tim Peters2a799bf2002-12-16 20:18:38 +00003246
3247/*
3248 * Miscellaneous methods.
3249 */
3250
Tim Peters37f39822003-01-10 03:49:02 +00003251static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00003252time_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters37f39822003-01-10 03:49:02 +00003253{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003254 int diff;
3255 naivety n1, n2;
3256 int offset1, offset2;
Tim Peters37f39822003-01-10 03:49:02 +00003257
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003258 if (! PyTime_Check(other)) {
3259 Py_INCREF(Py_NotImplemented);
3260 return Py_NotImplemented;
3261 }
3262 if (classify_two_utcoffsets(self, &offset1, &n1, Py_None,
3263 other, &offset2, &n2, Py_None) < 0)
3264 return NULL;
3265 assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
3266 /* If they're both naive, or both aware and have the same offsets,
3267 * we get off cheap. Note that if they're both naive, offset1 ==
3268 * offset2 == 0 at this point.
3269 */
3270 if (n1 == n2 && offset1 == offset2) {
3271 diff = memcmp(((PyDateTime_Time *)self)->data,
3272 ((PyDateTime_Time *)other)->data,
3273 _PyDateTime_TIME_DATASIZE);
3274 return diff_to_bool(diff, op);
3275 }
Tim Peters37f39822003-01-10 03:49:02 +00003276
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003277 if (n1 == OFFSET_AWARE && n2 == OFFSET_AWARE) {
3278 assert(offset1 != offset2); /* else last "if" handled it */
3279 /* Convert everything except microseconds to seconds. These
3280 * can't overflow (no more than the # of seconds in 2 days).
3281 */
3282 offset1 = TIME_GET_HOUR(self) * 3600 +
3283 (TIME_GET_MINUTE(self) - offset1) * 60 +
3284 TIME_GET_SECOND(self);
3285 offset2 = TIME_GET_HOUR(other) * 3600 +
3286 (TIME_GET_MINUTE(other) - offset2) * 60 +
3287 TIME_GET_SECOND(other);
3288 diff = offset1 - offset2;
3289 if (diff == 0)
3290 diff = TIME_GET_MICROSECOND(self) -
3291 TIME_GET_MICROSECOND(other);
3292 return diff_to_bool(diff, op);
3293 }
Tim Peters37f39822003-01-10 03:49:02 +00003294
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003295 assert(n1 != n2);
3296 PyErr_SetString(PyExc_TypeError,
3297 "can't compare offset-naive and "
3298 "offset-aware times");
3299 return NULL;
Tim Peters37f39822003-01-10 03:49:02 +00003300}
3301
3302static long
3303time_hash(PyDateTime_Time *self)
3304{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003305 if (self->hashcode == -1) {
3306 naivety n;
3307 int offset;
3308 PyObject *temp;
Tim Peters37f39822003-01-10 03:49:02 +00003309
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003310 n = classify_utcoffset((PyObject *)self, Py_None, &offset);
3311 assert(n != OFFSET_UNKNOWN);
3312 if (n == OFFSET_ERROR)
3313 return -1;
Tim Peters37f39822003-01-10 03:49:02 +00003314
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003315 /* Reduce this to a hash of another object. */
3316 if (offset == 0) {
3317 self->hashcode = generic_hash(
3318 (unsigned char *)self->data, _PyDateTime_TIME_DATASIZE);
3319 return self->hashcode;
3320 }
3321 else {
3322 int hour;
3323 int minute;
Tim Peters37f39822003-01-10 03:49:02 +00003324
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003325 assert(n == OFFSET_AWARE);
3326 assert(HASTZINFO(self));
3327 hour = divmod(TIME_GET_HOUR(self) * 60 +
3328 TIME_GET_MINUTE(self) - offset,
3329 60,
3330 &minute);
3331 if (0 <= hour && hour < 24)
3332 temp = new_time(hour, minute,
3333 TIME_GET_SECOND(self),
3334 TIME_GET_MICROSECOND(self),
3335 Py_None);
3336 else
3337 temp = Py_BuildValue("iiii",
3338 hour, minute,
3339 TIME_GET_SECOND(self),
3340 TIME_GET_MICROSECOND(self));
3341 }
3342 if (temp != NULL) {
3343 self->hashcode = PyObject_Hash(temp);
3344 Py_DECREF(temp);
3345 }
3346 }
3347 return self->hashcode;
Tim Peters37f39822003-01-10 03:49:02 +00003348}
Tim Peters2a799bf2002-12-16 20:18:38 +00003349
Tim Peters12bf3392002-12-24 05:41:27 +00003350static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003351time_replace(PyDateTime_Time *self, PyObject *args, PyObject *kw)
Tim Peters12bf3392002-12-24 05:41:27 +00003352{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003353 PyObject *clone;
3354 PyObject *tuple;
3355 int hh = TIME_GET_HOUR(self);
3356 int mm = TIME_GET_MINUTE(self);
3357 int ss = TIME_GET_SECOND(self);
3358 int us = TIME_GET_MICROSECOND(self);
3359 PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
Tim Peters12bf3392002-12-24 05:41:27 +00003360
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003361 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO:replace",
3362 time_kws,
3363 &hh, &mm, &ss, &us, &tzinfo))
3364 return NULL;
3365 tuple = Py_BuildValue("iiiiO", hh, mm, ss, us, tzinfo);
3366 if (tuple == NULL)
3367 return NULL;
3368 clone = time_new(Py_TYPE(self), tuple, NULL);
3369 Py_DECREF(tuple);
3370 return clone;
Tim Peters12bf3392002-12-24 05:41:27 +00003371}
3372
Tim Peters2a799bf2002-12-16 20:18:38 +00003373static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00003374time_bool(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003375{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003376 int offset;
3377 int none;
Tim Peters2a799bf2002-12-16 20:18:38 +00003378
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003379 if (TIME_GET_SECOND(self) || TIME_GET_MICROSECOND(self)) {
3380 /* Since utcoffset is in whole minutes, nothing can
3381 * alter the conclusion that this is nonzero.
3382 */
3383 return 1;
3384 }
3385 offset = 0;
3386 if (HASTZINFO(self) && self->tzinfo != Py_None) {
3387 offset = call_utcoffset(self->tzinfo, Py_None, &none);
3388 if (offset == -1 && PyErr_Occurred())
3389 return -1;
3390 }
3391 return (TIME_GET_MINUTE(self) - offset + TIME_GET_HOUR(self)*60) != 0;
Tim Peters2a799bf2002-12-16 20:18:38 +00003392}
3393
Tim Peters371935f2003-02-01 01:52:50 +00003394/* Pickle support, a simple use of __reduce__. */
Tim Peters2a799bf2002-12-16 20:18:38 +00003395
Tim Peters33e0f382003-01-10 02:05:14 +00003396/* Let basestate be the non-tzinfo data string.
Tim Peters2a799bf2002-12-16 20:18:38 +00003397 * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
3398 * So it's a tuple in any (non-error) case.
Tim Petersb57f8f02003-02-01 02:54:15 +00003399 * __getstate__ isn't exposed.
Tim Peters2a799bf2002-12-16 20:18:38 +00003400 */
3401static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003402time_getstate(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003403{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003404 PyObject *basestate;
3405 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00003406
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003407 basestate = PyBytes_FromStringAndSize((char *)self->data,
3408 _PyDateTime_TIME_DATASIZE);
3409 if (basestate != NULL) {
3410 if (! HASTZINFO(self) || self->tzinfo == Py_None)
3411 result = PyTuple_Pack(1, basestate);
3412 else
3413 result = PyTuple_Pack(2, basestate, self->tzinfo);
3414 Py_DECREF(basestate);
3415 }
3416 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00003417}
3418
3419static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00003420time_reduce(PyDateTime_Time *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00003421{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003422 return Py_BuildValue("(ON)", Py_TYPE(self), time_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00003423}
3424
Tim Peters37f39822003-01-10 03:49:02 +00003425static PyMethodDef time_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00003426
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003427 {"isoformat", (PyCFunction)time_isoformat, METH_NOARGS,
3428 PyDoc_STR("Return string in ISO 8601 format, HH:MM:SS[.mmmmmm]"
3429 "[+HH:MM].")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003430
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003431 {"strftime", (PyCFunction)time_strftime, METH_VARARGS | METH_KEYWORDS,
3432 PyDoc_STR("format -> strftime() style string.")},
Tim Peters37f39822003-01-10 03:49:02 +00003433
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003434 {"__format__", (PyCFunction)date_format, METH_VARARGS,
3435 PyDoc_STR("Formats self with strftime.")},
Eric Smith1ba31142007-09-11 18:06:02 +00003436
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003437 {"utcoffset", (PyCFunction)time_utcoffset, METH_NOARGS,
3438 PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003439
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003440 {"tzname", (PyCFunction)time_tzname, METH_NOARGS,
3441 PyDoc_STR("Return self.tzinfo.tzname(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003442
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003443 {"dst", (PyCFunction)time_dst, METH_NOARGS,
3444 PyDoc_STR("Return self.tzinfo.dst(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003445
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003446 {"replace", (PyCFunction)time_replace, METH_VARARGS | METH_KEYWORDS,
3447 PyDoc_STR("Return time with new specified fields.")},
Tim Peters12bf3392002-12-24 05:41:27 +00003448
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003449 {"__reduce__", (PyCFunction)time_reduce, METH_NOARGS,
3450 PyDoc_STR("__reduce__() -> (cls, state)")},
Guido van Rossum177e41a2003-01-30 22:06:23 +00003451
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003452 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00003453};
3454
Tim Peters37f39822003-01-10 03:49:02 +00003455static char time_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00003456PyDoc_STR("time([hour[, minute[, second[, microsecond[, tzinfo]]]]]) --> a time object\n\
3457\n\
3458All arguments are optional. tzinfo may be None, or an instance of\n\
3459a tzinfo subclass. The remaining arguments may be ints or longs.\n");
Tim Peters2a799bf2002-12-16 20:18:38 +00003460
Tim Peters37f39822003-01-10 03:49:02 +00003461static PyNumberMethods time_as_number = {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003462 0, /* nb_add */
3463 0, /* nb_subtract */
3464 0, /* nb_multiply */
3465 0, /* nb_remainder */
3466 0, /* nb_divmod */
3467 0, /* nb_power */
3468 0, /* nb_negative */
3469 0, /* nb_positive */
3470 0, /* nb_absolute */
3471 (inquiry)time_bool, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00003472};
3473
Neal Norwitz227b5332006-03-22 09:28:35 +00003474static PyTypeObject PyDateTime_TimeType = {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003475 PyVarObject_HEAD_INIT(NULL, 0)
3476 "datetime.time", /* tp_name */
3477 sizeof(PyDateTime_Time), /* tp_basicsize */
3478 0, /* tp_itemsize */
3479 (destructor)time_dealloc, /* tp_dealloc */
3480 0, /* tp_print */
3481 0, /* tp_getattr */
3482 0, /* tp_setattr */
3483 0, /* tp_reserved */
3484 (reprfunc)time_repr, /* tp_repr */
3485 &time_as_number, /* tp_as_number */
3486 0, /* tp_as_sequence */
3487 0, /* tp_as_mapping */
3488 (hashfunc)time_hash, /* tp_hash */
3489 0, /* tp_call */
3490 (reprfunc)time_str, /* tp_str */
3491 PyObject_GenericGetAttr, /* tp_getattro */
3492 0, /* tp_setattro */
3493 0, /* tp_as_buffer */
3494 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
3495 time_doc, /* tp_doc */
3496 0, /* tp_traverse */
3497 0, /* tp_clear */
3498 time_richcompare, /* tp_richcompare */
3499 0, /* tp_weaklistoffset */
3500 0, /* tp_iter */
3501 0, /* tp_iternext */
3502 time_methods, /* tp_methods */
3503 0, /* tp_members */
3504 time_getset, /* tp_getset */
3505 0, /* tp_base */
3506 0, /* tp_dict */
3507 0, /* tp_descr_get */
3508 0, /* tp_descr_set */
3509 0, /* tp_dictoffset */
3510 0, /* tp_init */
3511 time_alloc, /* tp_alloc */
3512 time_new, /* tp_new */
3513 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00003514};
3515
3516/*
Tim Petersa9bc1682003-01-11 03:39:11 +00003517 * PyDateTime_DateTime implementation.
Tim Peters2a799bf2002-12-16 20:18:38 +00003518 */
3519
Tim Petersa9bc1682003-01-11 03:39:11 +00003520/* Accessor properties. Properties for day, month, and year are inherited
3521 * from date.
Tim Peters2a799bf2002-12-16 20:18:38 +00003522 */
3523
3524static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003525datetime_hour(PyDateTime_DateTime *self, void *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00003526{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003527 return PyLong_FromLong(DATE_GET_HOUR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00003528}
3529
Tim Petersa9bc1682003-01-11 03:39:11 +00003530static PyObject *
3531datetime_minute(PyDateTime_DateTime *self, void *unused)
3532{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003533 return PyLong_FromLong(DATE_GET_MINUTE(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00003534}
3535
3536static PyObject *
3537datetime_second(PyDateTime_DateTime *self, void *unused)
3538{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003539 return PyLong_FromLong(DATE_GET_SECOND(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00003540}
3541
3542static PyObject *
3543datetime_microsecond(PyDateTime_DateTime *self, void *unused)
3544{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003545 return PyLong_FromLong(DATE_GET_MICROSECOND(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00003546}
3547
3548static PyObject *
3549datetime_tzinfo(PyDateTime_DateTime *self, void *unused)
3550{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003551 PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
3552 Py_INCREF(result);
3553 return result;
Tim Petersa9bc1682003-01-11 03:39:11 +00003554}
3555
3556static PyGetSetDef datetime_getset[] = {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003557 {"hour", (getter)datetime_hour},
3558 {"minute", (getter)datetime_minute},
3559 {"second", (getter)datetime_second},
3560 {"microsecond", (getter)datetime_microsecond},
3561 {"tzinfo", (getter)datetime_tzinfo},
3562 {NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00003563};
3564
3565/*
3566 * Constructors.
Tim Peters2a799bf2002-12-16 20:18:38 +00003567 */
3568
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003569static char *datetime_kws[] = {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003570 "year", "month", "day", "hour", "minute", "second",
3571 "microsecond", "tzinfo", NULL
Tim Peters12bf3392002-12-24 05:41:27 +00003572};
3573
Tim Peters2a799bf2002-12-16 20:18:38 +00003574static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003575datetime_new(PyTypeObject *type, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003576{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003577 PyObject *self = NULL;
3578 PyObject *state;
3579 int year;
3580 int month;
3581 int day;
3582 int hour = 0;
3583 int minute = 0;
3584 int second = 0;
3585 int usecond = 0;
3586 PyObject *tzinfo = Py_None;
Tim Peters2a799bf2002-12-16 20:18:38 +00003587
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003588 /* Check for invocation from pickle with __getstate__ state */
3589 if (PyTuple_GET_SIZE(args) >= 1 &&
3590 PyTuple_GET_SIZE(args) <= 2 &&
3591 PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) &&
3592 PyBytes_GET_SIZE(state) == _PyDateTime_DATETIME_DATASIZE &&
3593 MONTH_IS_SANE(PyBytes_AS_STRING(state)[2]))
3594 {
3595 PyDateTime_DateTime *me;
3596 char aware;
Tim Peters70533e22003-02-01 04:40:04 +00003597
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003598 if (PyTuple_GET_SIZE(args) == 2) {
3599 tzinfo = PyTuple_GET_ITEM(args, 1);
3600 if (check_tzinfo_subclass(tzinfo) < 0) {
3601 PyErr_SetString(PyExc_TypeError, "bad "
3602 "tzinfo state arg");
3603 return NULL;
3604 }
3605 }
3606 aware = (char)(tzinfo != Py_None);
3607 me = (PyDateTime_DateTime *) (type->tp_alloc(type , aware));
3608 if (me != NULL) {
3609 char *pdata = PyBytes_AS_STRING(state);
Tim Peters70533e22003-02-01 04:40:04 +00003610
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003611 memcpy(me->data, pdata, _PyDateTime_DATETIME_DATASIZE);
3612 me->hashcode = -1;
3613 me->hastzinfo = aware;
3614 if (aware) {
3615 Py_INCREF(tzinfo);
3616 me->tzinfo = tzinfo;
3617 }
3618 }
3619 return (PyObject *)me;
3620 }
Guido van Rossum177e41a2003-01-30 22:06:23 +00003621
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003622 if (PyArg_ParseTupleAndKeywords(args, kw, "iii|iiiiO", datetime_kws,
3623 &year, &month, &day, &hour, &minute,
3624 &second, &usecond, &tzinfo)) {
3625 if (check_date_args(year, month, day) < 0)
3626 return NULL;
3627 if (check_time_args(hour, minute, second, usecond) < 0)
3628 return NULL;
3629 if (check_tzinfo_subclass(tzinfo) < 0)
3630 return NULL;
3631 self = new_datetime_ex(year, month, day,
3632 hour, minute, second, usecond,
3633 tzinfo, type);
3634 }
3635 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00003636}
3637
Tim Petersa9bc1682003-01-11 03:39:11 +00003638/* TM_FUNC is the shared type of localtime() and gmtime(). */
3639typedef struct tm *(*TM_FUNC)(const time_t *timer);
3640
3641/* Internal helper.
3642 * Build datetime from a time_t and a distinct count of microseconds.
3643 * Pass localtime or gmtime for f, to control the interpretation of timet.
3644 */
3645static PyObject *
3646datetime_from_timet_and_us(PyObject *cls, TM_FUNC f, time_t timet, int us,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003647 PyObject *tzinfo)
Tim Petersa9bc1682003-01-11 03:39:11 +00003648{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003649 struct tm *tm;
3650 PyObject *result = NULL;
Tim Petersa9bc1682003-01-11 03:39:11 +00003651
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003652 tm = f(&timet);
3653 if (tm) {
3654 /* The platform localtime/gmtime may insert leap seconds,
3655 * indicated by tm->tm_sec > 59. We don't care about them,
3656 * except to the extent that passing them on to the datetime
3657 * constructor would raise ValueError for a reason that
3658 * made no sense to the user.
3659 */
3660 if (tm->tm_sec > 59)
3661 tm->tm_sec = 59;
3662 result = PyObject_CallFunction(cls, "iiiiiiiO",
3663 tm->tm_year + 1900,
3664 tm->tm_mon + 1,
3665 tm->tm_mday,
3666 tm->tm_hour,
3667 tm->tm_min,
3668 tm->tm_sec,
3669 us,
3670 tzinfo);
3671 }
3672 else
3673 PyErr_SetString(PyExc_ValueError,
3674 "timestamp out of range for "
3675 "platform localtime()/gmtime() function");
3676 return result;
Tim Petersa9bc1682003-01-11 03:39:11 +00003677}
3678
3679/* Internal helper.
3680 * Build datetime from a Python timestamp. Pass localtime or gmtime for f,
3681 * to control the interpretation of the timestamp. Since a double doesn't
3682 * have enough bits to cover a datetime's full range of precision, it's
3683 * better to call datetime_from_timet_and_us provided you have a way
3684 * to get that much precision (e.g., C time() isn't good enough).
3685 */
3686static PyObject *
3687datetime_from_timestamp(PyObject *cls, TM_FUNC f, double timestamp,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003688 PyObject *tzinfo)
Tim Petersa9bc1682003-01-11 03:39:11 +00003689{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003690 time_t timet;
3691 double fraction;
3692 int us;
Tim Petersa9bc1682003-01-11 03:39:11 +00003693
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003694 timet = _PyTime_DoubleToTimet(timestamp);
3695 if (timet == (time_t)-1 && PyErr_Occurred())
3696 return NULL;
3697 fraction = timestamp - (double)timet;
3698 us = (int)round_to_long(fraction * 1e6);
3699 if (us < 0) {
3700 /* Truncation towards zero is not what we wanted
3701 for negative numbers (Python's mod semantics) */
3702 timet -= 1;
3703 us += 1000000;
3704 }
3705 /* If timestamp is less than one microsecond smaller than a
3706 * full second, round up. Otherwise, ValueErrors are raised
3707 * for some floats. */
3708 if (us == 1000000) {
3709 timet += 1;
3710 us = 0;
3711 }
3712 return datetime_from_timet_and_us(cls, f, timet, us, tzinfo);
Tim Petersa9bc1682003-01-11 03:39:11 +00003713}
3714
3715/* Internal helper.
3716 * Build most accurate possible datetime for current time. Pass localtime or
3717 * gmtime for f as appropriate.
3718 */
3719static PyObject *
3720datetime_best_possible(PyObject *cls, TM_FUNC f, PyObject *tzinfo)
3721{
3722#ifdef HAVE_GETTIMEOFDAY
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003723 struct timeval t;
Tim Petersa9bc1682003-01-11 03:39:11 +00003724
3725#ifdef GETTIMEOFDAY_NO_TZ
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003726 gettimeofday(&t);
Tim Petersa9bc1682003-01-11 03:39:11 +00003727#else
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003728 gettimeofday(&t, (struct timezone *)NULL);
Tim Petersa9bc1682003-01-11 03:39:11 +00003729#endif
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003730 return datetime_from_timet_and_us(cls, f, t.tv_sec, (int)t.tv_usec,
3731 tzinfo);
Tim Petersa9bc1682003-01-11 03:39:11 +00003732
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003733#else /* ! HAVE_GETTIMEOFDAY */
3734 /* No flavor of gettimeofday exists on this platform. Python's
3735 * time.time() does a lot of other platform tricks to get the
3736 * best time it can on the platform, and we're not going to do
3737 * better than that (if we could, the better code would belong
3738 * in time.time()!) We're limited by the precision of a double,
3739 * though.
3740 */
3741 PyObject *time;
3742 double dtime;
Tim Petersa9bc1682003-01-11 03:39:11 +00003743
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003744 time = time_time();
3745 if (time == NULL)
3746 return NULL;
3747 dtime = PyFloat_AsDouble(time);
3748 Py_DECREF(time);
3749 if (dtime == -1.0 && PyErr_Occurred())
3750 return NULL;
3751 return datetime_from_timestamp(cls, f, dtime, tzinfo);
3752#endif /* ! HAVE_GETTIMEOFDAY */
Tim Petersa9bc1682003-01-11 03:39:11 +00003753}
3754
Tim Peters2a799bf2002-12-16 20:18:38 +00003755/* Return best possible local time -- this isn't constrained by the
3756 * precision of a timestamp.
3757 */
3758static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003759datetime_now(PyObject *cls, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003760{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003761 PyObject *self;
3762 PyObject *tzinfo = Py_None;
3763 static char *keywords[] = {"tz", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00003764
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003765 if (! PyArg_ParseTupleAndKeywords(args, kw, "|O:now", keywords,
3766 &tzinfo))
3767 return NULL;
3768 if (check_tzinfo_subclass(tzinfo) < 0)
3769 return NULL;
Tim Peters10cadce2003-01-23 19:58:02 +00003770
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003771 self = datetime_best_possible(cls,
3772 tzinfo == Py_None ? localtime : gmtime,
3773 tzinfo);
3774 if (self != NULL && tzinfo != Py_None) {
3775 /* Convert UTC to tzinfo's zone. */
3776 PyObject *temp = self;
3777 self = PyObject_CallMethod(tzinfo, "fromutc", "O", self);
3778 Py_DECREF(temp);
3779 }
3780 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00003781}
3782
Tim Petersa9bc1682003-01-11 03:39:11 +00003783/* Return best possible UTC time -- this isn't constrained by the
3784 * precision of a timestamp.
3785 */
3786static PyObject *
3787datetime_utcnow(PyObject *cls, PyObject *dummy)
3788{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003789 return datetime_best_possible(cls, gmtime, Py_None);
Tim Petersa9bc1682003-01-11 03:39:11 +00003790}
3791
Tim Peters2a799bf2002-12-16 20:18:38 +00003792/* Return new local datetime from timestamp (Python timestamp -- a double). */
3793static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003794datetime_fromtimestamp(PyObject *cls, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003795{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003796 PyObject *self;
3797 double timestamp;
3798 PyObject *tzinfo = Py_None;
3799 static char *keywords[] = {"timestamp", "tz", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00003800
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003801 if (! PyArg_ParseTupleAndKeywords(args, kw, "d|O:fromtimestamp",
3802 keywords, &timestamp, &tzinfo))
3803 return NULL;
3804 if (check_tzinfo_subclass(tzinfo) < 0)
3805 return NULL;
Tim Peters2a44a8d2003-01-23 20:53:10 +00003806
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003807 self = datetime_from_timestamp(cls,
3808 tzinfo == Py_None ? localtime : gmtime,
3809 timestamp,
3810 tzinfo);
3811 if (self != NULL && tzinfo != Py_None) {
3812 /* Convert UTC to tzinfo's zone. */
3813 PyObject *temp = self;
3814 self = PyObject_CallMethod(tzinfo, "fromutc", "O", self);
3815 Py_DECREF(temp);
3816 }
3817 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00003818}
3819
Tim Petersa9bc1682003-01-11 03:39:11 +00003820/* Return new UTC datetime from timestamp (Python timestamp -- a double). */
3821static PyObject *
3822datetime_utcfromtimestamp(PyObject *cls, PyObject *args)
3823{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003824 double timestamp;
3825 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00003826
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003827 if (PyArg_ParseTuple(args, "d:utcfromtimestamp", &timestamp))
3828 result = datetime_from_timestamp(cls, gmtime, timestamp,
3829 Py_None);
3830 return result;
Tim Petersa9bc1682003-01-11 03:39:11 +00003831}
3832
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003833/* Return new datetime from time.strptime(). */
3834static PyObject *
3835datetime_strptime(PyObject *cls, PyObject *args)
3836{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003837 static PyObject *module = NULL;
3838 PyObject *result = NULL, *obj, *st = NULL, *frac = NULL;
3839 const Py_UNICODE *string, *format;
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003840
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003841 if (!PyArg_ParseTuple(args, "uu:strptime", &string, &format))
3842 return NULL;
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003843
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003844 if (module == NULL &&
3845 (module = PyImport_ImportModuleNoBlock("_strptime")) == NULL)
3846 return NULL;
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003847
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003848 /* _strptime._strptime returns a two-element tuple. The first
3849 element is a time.struct_time object. The second is the
3850 microseconds (which are not defined for time.struct_time). */
3851 obj = PyObject_CallMethod(module, "_strptime", "uu", string, format);
3852 if (obj != NULL) {
3853 int i, good_timetuple = 1;
3854 long int ia[7];
3855 if (PySequence_Check(obj) && PySequence_Size(obj) == 2) {
3856 st = PySequence_GetItem(obj, 0);
3857 frac = PySequence_GetItem(obj, 1);
3858 if (st == NULL || frac == NULL)
3859 good_timetuple = 0;
3860 /* copy y/m/d/h/m/s values out of the
3861 time.struct_time */
3862 if (good_timetuple &&
3863 PySequence_Check(st) &&
3864 PySequence_Size(st) >= 6) {
3865 for (i=0; i < 6; i++) {
3866 PyObject *p = PySequence_GetItem(st, i);
3867 if (p == NULL) {
3868 good_timetuple = 0;
3869 break;
3870 }
3871 if (PyLong_Check(p))
3872 ia[i] = PyLong_AsLong(p);
3873 else
3874 good_timetuple = 0;
3875 Py_DECREF(p);
3876 }
3877/* if (PyLong_CheckExact(p)) {
3878 ia[i] = PyLong_AsLongAndOverflow(p, &overflow);
3879 if (overflow)
3880 good_timetuple = 0;
3881 }
3882 else
3883 good_timetuple = 0;
3884 Py_DECREF(p);
3885*/ }
3886 else
3887 good_timetuple = 0;
3888 /* follow that up with a little dose of microseconds */
3889 if (PyLong_Check(frac))
3890 ia[6] = PyLong_AsLong(frac);
3891 else
3892 good_timetuple = 0;
3893 }
3894 else
3895 good_timetuple = 0;
3896 if (good_timetuple)
3897 result = PyObject_CallFunction(cls, "iiiiiii",
3898 ia[0], ia[1], ia[2],
3899 ia[3], ia[4], ia[5],
3900 ia[6]);
3901 else
3902 PyErr_SetString(PyExc_ValueError,
3903 "unexpected value from _strptime._strptime");
3904 }
3905 Py_XDECREF(obj);
3906 Py_XDECREF(st);
3907 Py_XDECREF(frac);
3908 return result;
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003909}
3910
Tim Petersa9bc1682003-01-11 03:39:11 +00003911/* Return new datetime from date/datetime and time arguments. */
3912static PyObject *
3913datetime_combine(PyObject *cls, PyObject *args, PyObject *kw)
3914{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003915 static char *keywords[] = {"date", "time", NULL};
3916 PyObject *date;
3917 PyObject *time;
3918 PyObject *result = NULL;
Tim Petersa9bc1682003-01-11 03:39:11 +00003919
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003920 if (PyArg_ParseTupleAndKeywords(args, kw, "O!O!:combine", keywords,
3921 &PyDateTime_DateType, &date,
3922 &PyDateTime_TimeType, &time)) {
3923 PyObject *tzinfo = Py_None;
Tim Petersa9bc1682003-01-11 03:39:11 +00003924
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003925 if (HASTZINFO(time))
3926 tzinfo = ((PyDateTime_Time *)time)->tzinfo;
3927 result = PyObject_CallFunction(cls, "iiiiiiiO",
3928 GET_YEAR(date),
3929 GET_MONTH(date),
3930 GET_DAY(date),
3931 TIME_GET_HOUR(time),
3932 TIME_GET_MINUTE(time),
3933 TIME_GET_SECOND(time),
3934 TIME_GET_MICROSECOND(time),
3935 tzinfo);
3936 }
3937 return result;
Tim Petersa9bc1682003-01-11 03:39:11 +00003938}
Tim Peters2a799bf2002-12-16 20:18:38 +00003939
3940/*
3941 * Destructor.
3942 */
3943
3944static void
Tim Petersa9bc1682003-01-11 03:39:11 +00003945datetime_dealloc(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003946{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003947 if (HASTZINFO(self)) {
3948 Py_XDECREF(self->tzinfo);
3949 }
3950 Py_TYPE(self)->tp_free((PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00003951}
3952
3953/*
3954 * Indirect access to tzinfo methods.
3955 */
3956
Tim Peters2a799bf2002-12-16 20:18:38 +00003957/* These are all METH_NOARGS, so don't need to check the arglist. */
3958static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003959datetime_utcoffset(PyDateTime_DateTime *self, PyObject *unused) {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003960 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
3961 "utcoffset", (PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00003962}
3963
3964static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003965datetime_dst(PyDateTime_DateTime *self, PyObject *unused) {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003966 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
3967 "dst", (PyObject *)self);
Tim Peters855fe882002-12-22 03:43:39 +00003968}
3969
3970static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003971datetime_tzname(PyDateTime_DateTime *self, PyObject *unused) {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003972 return call_tzname(HASTZINFO(self) ? self->tzinfo : Py_None,
3973 (PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00003974}
3975
3976/*
Tim Petersa9bc1682003-01-11 03:39:11 +00003977 * datetime arithmetic.
Tim Peters2a799bf2002-12-16 20:18:38 +00003978 */
3979
Tim Petersa9bc1682003-01-11 03:39:11 +00003980/* factor must be 1 (to add) or -1 (to subtract). The result inherits
3981 * the tzinfo state of date.
Tim Peters2a799bf2002-12-16 20:18:38 +00003982 */
3983static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003984add_datetime_timedelta(PyDateTime_DateTime *date, PyDateTime_Delta *delta,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003985 int factor)
Tim Peters2a799bf2002-12-16 20:18:38 +00003986{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003987 /* Note that the C-level additions can't overflow, because of
3988 * invariant bounds on the member values.
3989 */
3990 int year = GET_YEAR(date);
3991 int month = GET_MONTH(date);
3992 int day = GET_DAY(date) + GET_TD_DAYS(delta) * factor;
3993 int hour = DATE_GET_HOUR(date);
3994 int minute = DATE_GET_MINUTE(date);
3995 int second = DATE_GET_SECOND(date) + GET_TD_SECONDS(delta) * factor;
3996 int microsecond = DATE_GET_MICROSECOND(date) +
3997 GET_TD_MICROSECONDS(delta) * factor;
Tim Peters2a799bf2002-12-16 20:18:38 +00003998
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00003999 assert(factor == 1 || factor == -1);
4000 if (normalize_datetime(&year, &month, &day,
4001 &hour, &minute, &second, &microsecond) < 0)
4002 return NULL;
4003 else
4004 return new_datetime(year, month, day,
4005 hour, minute, second, microsecond,
4006 HASTZINFO(date) ? date->tzinfo : Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004007}
4008
4009static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004010datetime_add(PyObject *left, PyObject *right)
Tim Peters2a799bf2002-12-16 20:18:38 +00004011{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004012 if (PyDateTime_Check(left)) {
4013 /* datetime + ??? */
4014 if (PyDelta_Check(right))
4015 /* datetime + delta */
4016 return add_datetime_timedelta(
4017 (PyDateTime_DateTime *)left,
4018 (PyDateTime_Delta *)right,
4019 1);
4020 }
4021 else if (PyDelta_Check(left)) {
4022 /* delta + datetime */
4023 return add_datetime_timedelta((PyDateTime_DateTime *) right,
4024 (PyDateTime_Delta *) left,
4025 1);
4026 }
4027 Py_INCREF(Py_NotImplemented);
4028 return Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00004029}
4030
4031static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004032datetime_subtract(PyObject *left, PyObject *right)
Tim Peters2a799bf2002-12-16 20:18:38 +00004033{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004034 PyObject *result = Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00004035
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004036 if (PyDateTime_Check(left)) {
4037 /* datetime - ??? */
4038 if (PyDateTime_Check(right)) {
4039 /* datetime - datetime */
4040 naivety n1, n2;
4041 int offset1, offset2;
4042 int delta_d, delta_s, delta_us;
Tim Peters2a799bf2002-12-16 20:18:38 +00004043
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004044 if (classify_two_utcoffsets(left, &offset1, &n1, left,
4045 right, &offset2, &n2,
4046 right) < 0)
4047 return NULL;
4048 assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
4049 if (n1 != n2) {
4050 PyErr_SetString(PyExc_TypeError,
4051 "can't subtract offset-naive and "
4052 "offset-aware datetimes");
4053 return NULL;
4054 }
4055 delta_d = ymd_to_ord(GET_YEAR(left),
4056 GET_MONTH(left),
4057 GET_DAY(left)) -
4058 ymd_to_ord(GET_YEAR(right),
4059 GET_MONTH(right),
4060 GET_DAY(right));
4061 /* These can't overflow, since the values are
4062 * normalized. At most this gives the number of
4063 * seconds in one day.
4064 */
4065 delta_s = (DATE_GET_HOUR(left) -
4066 DATE_GET_HOUR(right)) * 3600 +
4067 (DATE_GET_MINUTE(left) -
4068 DATE_GET_MINUTE(right)) * 60 +
4069 (DATE_GET_SECOND(left) -
4070 DATE_GET_SECOND(right));
4071 delta_us = DATE_GET_MICROSECOND(left) -
4072 DATE_GET_MICROSECOND(right);
4073 /* (left - offset1) - (right - offset2) =
4074 * (left - right) + (offset2 - offset1)
4075 */
4076 delta_s += (offset2 - offset1) * 60;
4077 result = new_delta(delta_d, delta_s, delta_us, 1);
4078 }
4079 else if (PyDelta_Check(right)) {
4080 /* datetime - delta */
4081 result = add_datetime_timedelta(
4082 (PyDateTime_DateTime *)left,
4083 (PyDateTime_Delta *)right,
4084 -1);
4085 }
4086 }
Tim Peters2a799bf2002-12-16 20:18:38 +00004087
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004088 if (result == Py_NotImplemented)
4089 Py_INCREF(result);
4090 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00004091}
4092
4093/* Various ways to turn a datetime into a string. */
4094
4095static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004096datetime_repr(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004097{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004098 const char *type_name = Py_TYPE(self)->tp_name;
4099 PyObject *baserepr;
Tim Peters2a799bf2002-12-16 20:18:38 +00004100
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004101 if (DATE_GET_MICROSECOND(self)) {
4102 baserepr = PyUnicode_FromFormat(
4103 "%s(%d, %d, %d, %d, %d, %d, %d)",
4104 type_name,
4105 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4106 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4107 DATE_GET_SECOND(self),
4108 DATE_GET_MICROSECOND(self));
4109 }
4110 else if (DATE_GET_SECOND(self)) {
4111 baserepr = PyUnicode_FromFormat(
4112 "%s(%d, %d, %d, %d, %d, %d)",
4113 type_name,
4114 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4115 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4116 DATE_GET_SECOND(self));
4117 }
4118 else {
4119 baserepr = PyUnicode_FromFormat(
4120 "%s(%d, %d, %d, %d, %d)",
4121 type_name,
4122 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4123 DATE_GET_HOUR(self), DATE_GET_MINUTE(self));
4124 }
4125 if (baserepr == NULL || ! HASTZINFO(self))
4126 return baserepr;
4127 return append_keyword_tzinfo(baserepr, self->tzinfo);
Tim Peters2a799bf2002-12-16 20:18:38 +00004128}
4129
Tim Petersa9bc1682003-01-11 03:39:11 +00004130static PyObject *
4131datetime_str(PyDateTime_DateTime *self)
4132{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004133 return PyObject_CallMethod((PyObject *)self, "isoformat", "(s)", " ");
Tim Petersa9bc1682003-01-11 03:39:11 +00004134}
Tim Peters2a799bf2002-12-16 20:18:38 +00004135
4136static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004137datetime_isoformat(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00004138{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004139 int sep = 'T';
4140 static char *keywords[] = {"sep", NULL};
4141 char buffer[100];
4142 PyObject *result;
4143 int us = DATE_GET_MICROSECOND(self);
Tim Peters2a799bf2002-12-16 20:18:38 +00004144
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004145 if (!PyArg_ParseTupleAndKeywords(args, kw, "|C:isoformat", keywords, &sep))
4146 return NULL;
4147 if (us)
4148 result = PyUnicode_FromFormat("%04d-%02d-%02d%c%02d:%02d:%02d.%06d",
4149 GET_YEAR(self), GET_MONTH(self),
4150 GET_DAY(self), (int)sep,
4151 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4152 DATE_GET_SECOND(self), us);
4153 else
4154 result = PyUnicode_FromFormat("%04d-%02d-%02d%c%02d:%02d:%02d",
4155 GET_YEAR(self), GET_MONTH(self),
4156 GET_DAY(self), (int)sep,
4157 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4158 DATE_GET_SECOND(self));
Walter Dörwaldbafa1372007-05-31 17:50:48 +00004159
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004160 if (!result || !HASTZINFO(self))
4161 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00004162
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004163 /* We need to append the UTC offset. */
4164 if (format_utcoffset(buffer, sizeof(buffer), ":", self->tzinfo,
4165 (PyObject *)self) < 0) {
4166 Py_DECREF(result);
4167 return NULL;
4168 }
4169 PyUnicode_AppendAndDel(&result, PyUnicode_FromString(buffer));
4170 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00004171}
4172
Tim Petersa9bc1682003-01-11 03:39:11 +00004173static PyObject *
4174datetime_ctime(PyDateTime_DateTime *self)
4175{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004176 return format_ctime((PyDateTime_Date *)self,
4177 DATE_GET_HOUR(self),
4178 DATE_GET_MINUTE(self),
4179 DATE_GET_SECOND(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00004180}
4181
Tim Peters2a799bf2002-12-16 20:18:38 +00004182/* Miscellaneous methods. */
4183
Tim Petersa9bc1682003-01-11 03:39:11 +00004184static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00004185datetime_richcompare(PyObject *self, PyObject *other, int op)
Tim Petersa9bc1682003-01-11 03:39:11 +00004186{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004187 int diff;
4188 naivety n1, n2;
4189 int offset1, offset2;
Tim Petersa9bc1682003-01-11 03:39:11 +00004190
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004191 if (! PyDateTime_Check(other)) {
4192 if (PyDate_Check(other)) {
4193 /* Prevent invocation of date_richcompare. We want to
4194 return NotImplemented here to give the other object
4195 a chance. But since DateTime is a subclass of
4196 Date, if the other object is a Date, it would
4197 compute an ordering based on the date part alone,
4198 and we don't want that. So force unequal or
4199 uncomparable here in that case. */
4200 if (op == Py_EQ)
4201 Py_RETURN_FALSE;
4202 if (op == Py_NE)
4203 Py_RETURN_TRUE;
4204 return cmperror(self, other);
4205 }
4206 Py_INCREF(Py_NotImplemented);
4207 return Py_NotImplemented;
4208 }
Tim Petersa9bc1682003-01-11 03:39:11 +00004209
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004210 if (classify_two_utcoffsets(self, &offset1, &n1, self,
4211 other, &offset2, &n2, other) < 0)
4212 return NULL;
4213 assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
4214 /* If they're both naive, or both aware and have the same offsets,
4215 * we get off cheap. Note that if they're both naive, offset1 ==
4216 * offset2 == 0 at this point.
4217 */
4218 if (n1 == n2 && offset1 == offset2) {
4219 diff = memcmp(((PyDateTime_DateTime *)self)->data,
4220 ((PyDateTime_DateTime *)other)->data,
4221 _PyDateTime_DATETIME_DATASIZE);
4222 return diff_to_bool(diff, op);
4223 }
Tim Petersa9bc1682003-01-11 03:39:11 +00004224
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004225 if (n1 == OFFSET_AWARE && n2 == OFFSET_AWARE) {
4226 PyDateTime_Delta *delta;
Tim Petersa9bc1682003-01-11 03:39:11 +00004227
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004228 assert(offset1 != offset2); /* else last "if" handled it */
4229 delta = (PyDateTime_Delta *)datetime_subtract((PyObject *)self,
4230 other);
4231 if (delta == NULL)
4232 return NULL;
4233 diff = GET_TD_DAYS(delta);
4234 if (diff == 0)
4235 diff = GET_TD_SECONDS(delta) |
4236 GET_TD_MICROSECONDS(delta);
4237 Py_DECREF(delta);
4238 return diff_to_bool(diff, op);
4239 }
Tim Petersa9bc1682003-01-11 03:39:11 +00004240
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004241 assert(n1 != n2);
4242 PyErr_SetString(PyExc_TypeError,
4243 "can't compare offset-naive and "
4244 "offset-aware datetimes");
4245 return NULL;
Tim Petersa9bc1682003-01-11 03:39:11 +00004246}
4247
4248static long
4249datetime_hash(PyDateTime_DateTime *self)
4250{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004251 if (self->hashcode == -1) {
4252 naivety n;
4253 int offset;
4254 PyObject *temp;
Tim Petersa9bc1682003-01-11 03:39:11 +00004255
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004256 n = classify_utcoffset((PyObject *)self, (PyObject *)self,
4257 &offset);
4258 assert(n != OFFSET_UNKNOWN);
4259 if (n == OFFSET_ERROR)
4260 return -1;
Tim Petersa9bc1682003-01-11 03:39:11 +00004261
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004262 /* Reduce this to a hash of another object. */
4263 if (n == OFFSET_NAIVE) {
4264 self->hashcode = generic_hash(
4265 (unsigned char *)self->data, _PyDateTime_DATETIME_DATASIZE);
4266 return self->hashcode;
4267 }
4268 else {
4269 int days;
4270 int seconds;
Tim Petersa9bc1682003-01-11 03:39:11 +00004271
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004272 assert(n == OFFSET_AWARE);
4273 assert(HASTZINFO(self));
4274 days = ymd_to_ord(GET_YEAR(self),
4275 GET_MONTH(self),
4276 GET_DAY(self));
4277 seconds = DATE_GET_HOUR(self) * 3600 +
4278 (DATE_GET_MINUTE(self) - offset) * 60 +
4279 DATE_GET_SECOND(self);
4280 temp = new_delta(days,
4281 seconds,
4282 DATE_GET_MICROSECOND(self),
4283 1);
4284 }
4285 if (temp != NULL) {
4286 self->hashcode = PyObject_Hash(temp);
4287 Py_DECREF(temp);
4288 }
4289 }
4290 return self->hashcode;
Tim Petersa9bc1682003-01-11 03:39:11 +00004291}
Tim Peters2a799bf2002-12-16 20:18:38 +00004292
4293static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004294datetime_replace(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters12bf3392002-12-24 05:41:27 +00004295{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004296 PyObject *clone;
4297 PyObject *tuple;
4298 int y = GET_YEAR(self);
4299 int m = GET_MONTH(self);
4300 int d = GET_DAY(self);
4301 int hh = DATE_GET_HOUR(self);
4302 int mm = DATE_GET_MINUTE(self);
4303 int ss = DATE_GET_SECOND(self);
4304 int us = DATE_GET_MICROSECOND(self);
4305 PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
Tim Peters12bf3392002-12-24 05:41:27 +00004306
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004307 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiiiiO:replace",
4308 datetime_kws,
4309 &y, &m, &d, &hh, &mm, &ss, &us,
4310 &tzinfo))
4311 return NULL;
4312 tuple = Py_BuildValue("iiiiiiiO", y, m, d, hh, mm, ss, us, tzinfo);
4313 if (tuple == NULL)
4314 return NULL;
4315 clone = datetime_new(Py_TYPE(self), tuple, NULL);
4316 Py_DECREF(tuple);
4317 return clone;
Tim Peters12bf3392002-12-24 05:41:27 +00004318}
4319
4320static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004321datetime_astimezone(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters80475bb2002-12-25 07:40:55 +00004322{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004323 int y, m, d, hh, mm, ss, us;
4324 PyObject *result;
4325 int offset, none;
Tim Peters521fc152002-12-31 17:36:56 +00004326
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004327 PyObject *tzinfo;
4328 static char *keywords[] = {"tz", NULL};
Tim Peters80475bb2002-12-25 07:40:55 +00004329
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004330 if (! PyArg_ParseTupleAndKeywords(args, kw, "O!:astimezone", keywords,
4331 &PyDateTime_TZInfoType, &tzinfo))
4332 return NULL;
Tim Peters80475bb2002-12-25 07:40:55 +00004333
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004334 if (!HASTZINFO(self) || self->tzinfo == Py_None)
4335 goto NeedAware;
Tim Peters521fc152002-12-31 17:36:56 +00004336
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004337 /* Conversion to self's own time zone is a NOP. */
4338 if (self->tzinfo == tzinfo) {
4339 Py_INCREF(self);
4340 return (PyObject *)self;
4341 }
Tim Peters521fc152002-12-31 17:36:56 +00004342
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004343 /* Convert self to UTC. */
4344 offset = call_utcoffset(self->tzinfo, (PyObject *)self, &none);
4345 if (offset == -1 && PyErr_Occurred())
4346 return NULL;
4347 if (none)
4348 goto NeedAware;
Tim Petersf3615152003-01-01 21:51:37 +00004349
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004350 y = GET_YEAR(self);
4351 m = GET_MONTH(self);
4352 d = GET_DAY(self);
4353 hh = DATE_GET_HOUR(self);
4354 mm = DATE_GET_MINUTE(self);
4355 ss = DATE_GET_SECOND(self);
4356 us = DATE_GET_MICROSECOND(self);
Tim Peters52dcce22003-01-23 16:36:11 +00004357
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004358 mm -= offset;
4359 if ((mm < 0 || mm >= 60) &&
4360 normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
4361 return NULL;
Tim Peters52dcce22003-01-23 16:36:11 +00004362
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004363 /* Attach new tzinfo and let fromutc() do the rest. */
4364 result = new_datetime(y, m, d, hh, mm, ss, us, tzinfo);
4365 if (result != NULL) {
4366 PyObject *temp = result;
Tim Peters52dcce22003-01-23 16:36:11 +00004367
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004368 result = PyObject_CallMethod(tzinfo, "fromutc", "O", temp);
4369 Py_DECREF(temp);
4370 }
4371 return result;
Tim Peters521fc152002-12-31 17:36:56 +00004372
Tim Peters52dcce22003-01-23 16:36:11 +00004373NeedAware:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004374 PyErr_SetString(PyExc_ValueError, "astimezone() cannot be applied to "
4375 "a naive datetime");
4376 return NULL;
Tim Peters80475bb2002-12-25 07:40:55 +00004377}
4378
4379static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004380datetime_timetuple(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004381{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004382 int dstflag = -1;
Tim Peters2a799bf2002-12-16 20:18:38 +00004383
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004384 if (HASTZINFO(self) && self->tzinfo != Py_None) {
4385 int none;
Tim Peters2a799bf2002-12-16 20:18:38 +00004386
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004387 dstflag = call_dst(self->tzinfo, (PyObject *)self, &none);
4388 if (dstflag == -1 && PyErr_Occurred())
4389 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004390
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004391 if (none)
4392 dstflag = -1;
4393 else if (dstflag != 0)
4394 dstflag = 1;
Tim Peters2a799bf2002-12-16 20:18:38 +00004395
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004396 }
4397 return build_struct_time(GET_YEAR(self),
4398 GET_MONTH(self),
4399 GET_DAY(self),
4400 DATE_GET_HOUR(self),
4401 DATE_GET_MINUTE(self),
4402 DATE_GET_SECOND(self),
4403 dstflag);
Tim Peters2a799bf2002-12-16 20:18:38 +00004404}
4405
4406static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004407datetime_getdate(PyDateTime_DateTime *self)
4408{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004409 return new_date(GET_YEAR(self),
4410 GET_MONTH(self),
4411 GET_DAY(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00004412}
4413
4414static PyObject *
4415datetime_gettime(PyDateTime_DateTime *self)
4416{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004417 return new_time(DATE_GET_HOUR(self),
4418 DATE_GET_MINUTE(self),
4419 DATE_GET_SECOND(self),
4420 DATE_GET_MICROSECOND(self),
4421 Py_None);
Tim Petersa9bc1682003-01-11 03:39:11 +00004422}
4423
4424static PyObject *
4425datetime_gettimetz(PyDateTime_DateTime *self)
4426{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004427 return new_time(DATE_GET_HOUR(self),
4428 DATE_GET_MINUTE(self),
4429 DATE_GET_SECOND(self),
4430 DATE_GET_MICROSECOND(self),
4431 HASTZINFO(self) ? self->tzinfo : Py_None);
Tim Petersa9bc1682003-01-11 03:39:11 +00004432}
4433
4434static PyObject *
4435datetime_utctimetuple(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004436{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004437 int y = GET_YEAR(self);
4438 int m = GET_MONTH(self);
4439 int d = GET_DAY(self);
4440 int hh = DATE_GET_HOUR(self);
4441 int mm = DATE_GET_MINUTE(self);
4442 int ss = DATE_GET_SECOND(self);
4443 int us = 0; /* microseconds are ignored in a timetuple */
4444 int offset = 0;
Tim Peters2a799bf2002-12-16 20:18:38 +00004445
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004446 if (HASTZINFO(self) && self->tzinfo != Py_None) {
4447 int none;
Tim Peters2a799bf2002-12-16 20:18:38 +00004448
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004449 offset = call_utcoffset(self->tzinfo, (PyObject *)self, &none);
4450 if (offset == -1 && PyErr_Occurred())
4451 return NULL;
4452 }
4453 /* Even if offset is 0, don't call timetuple() -- tm_isdst should be
4454 * 0 in a UTC timetuple regardless of what dst() says.
4455 */
4456 if (offset) {
4457 /* Subtract offset minutes & normalize. */
4458 int stat;
Tim Peters2a799bf2002-12-16 20:18:38 +00004459
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004460 mm -= offset;
4461 stat = normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us);
4462 if (stat < 0) {
4463 /* At the edges, it's possible we overflowed
4464 * beyond MINYEAR or MAXYEAR.
4465 */
4466 if (PyErr_ExceptionMatches(PyExc_OverflowError))
4467 PyErr_Clear();
4468 else
4469 return NULL;
4470 }
4471 }
4472 return build_struct_time(y, m, d, hh, mm, ss, 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00004473}
4474
Tim Peters371935f2003-02-01 01:52:50 +00004475/* Pickle support, a simple use of __reduce__. */
Tim Peters33e0f382003-01-10 02:05:14 +00004476
Tim Petersa9bc1682003-01-11 03:39:11 +00004477/* Let basestate be the non-tzinfo data string.
Tim Peters2a799bf2002-12-16 20:18:38 +00004478 * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
4479 * So it's a tuple in any (non-error) case.
Tim Petersb57f8f02003-02-01 02:54:15 +00004480 * __getstate__ isn't exposed.
Tim Peters2a799bf2002-12-16 20:18:38 +00004481 */
4482static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004483datetime_getstate(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004484{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004485 PyObject *basestate;
4486 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004487
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004488 basestate = PyBytes_FromStringAndSize((char *)self->data,
4489 _PyDateTime_DATETIME_DATASIZE);
4490 if (basestate != NULL) {
4491 if (! HASTZINFO(self) || self->tzinfo == Py_None)
4492 result = PyTuple_Pack(1, basestate);
4493 else
4494 result = PyTuple_Pack(2, basestate, self->tzinfo);
4495 Py_DECREF(basestate);
4496 }
4497 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00004498}
4499
4500static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00004501datetime_reduce(PyDateTime_DateTime *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00004502{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004503 return Py_BuildValue("(ON)", Py_TYPE(self), datetime_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00004504}
4505
Tim Petersa9bc1682003-01-11 03:39:11 +00004506static PyMethodDef datetime_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00004507
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004508 /* Class methods: */
Tim Peters2a799bf2002-12-16 20:18:38 +00004509
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004510 {"now", (PyCFunction)datetime_now,
4511 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
4512 PyDoc_STR("[tz] -> new datetime with tz's local day and time.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004513
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004514 {"utcnow", (PyCFunction)datetime_utcnow,
4515 METH_NOARGS | METH_CLASS,
4516 PyDoc_STR("Return a new datetime representing UTC day and time.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00004517
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004518 {"fromtimestamp", (PyCFunction)datetime_fromtimestamp,
4519 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
4520 PyDoc_STR("timestamp[, tz] -> tz's local time from POSIX timestamp.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004521
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004522 {"utcfromtimestamp", (PyCFunction)datetime_utcfromtimestamp,
4523 METH_VARARGS | METH_CLASS,
4524 PyDoc_STR("timestamp -> UTC datetime from a POSIX timestamp "
4525 "(like time.time()).")},
Tim Petersa9bc1682003-01-11 03:39:11 +00004526
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004527 {"strptime", (PyCFunction)datetime_strptime,
4528 METH_VARARGS | METH_CLASS,
4529 PyDoc_STR("string, format -> new datetime parsed from a string "
4530 "(like time.strptime()).")},
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004531
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004532 {"combine", (PyCFunction)datetime_combine,
4533 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
4534 PyDoc_STR("date, time -> datetime with same date and time fields")},
Tim Petersa9bc1682003-01-11 03:39:11 +00004535
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004536 /* Instance methods: */
Guido van Rossum177e41a2003-01-30 22:06:23 +00004537
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004538 {"date", (PyCFunction)datetime_getdate, METH_NOARGS,
4539 PyDoc_STR("Return date object with same year, month and day.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00004540
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004541 {"time", (PyCFunction)datetime_gettime, METH_NOARGS,
4542 PyDoc_STR("Return time object with same time but with tzinfo=None.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00004543
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004544 {"timetz", (PyCFunction)datetime_gettimetz, METH_NOARGS,
4545 PyDoc_STR("Return time object with same time and tzinfo.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00004546
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004547 {"ctime", (PyCFunction)datetime_ctime, METH_NOARGS,
4548 PyDoc_STR("Return ctime() style string.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00004549
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004550 {"timetuple", (PyCFunction)datetime_timetuple, METH_NOARGS,
4551 PyDoc_STR("Return time tuple, compatible with time.localtime().")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004552
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004553 {"utctimetuple", (PyCFunction)datetime_utctimetuple, METH_NOARGS,
4554 PyDoc_STR("Return UTC time tuple, compatible with time.localtime().")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004555
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004556 {"isoformat", (PyCFunction)datetime_isoformat, METH_VARARGS | METH_KEYWORDS,
4557 PyDoc_STR("[sep] -> string in ISO 8601 format, "
4558 "YYYY-MM-DDTHH:MM:SS[.mmmmmm][+HH:MM].\n\n"
4559 "sep is used to separate the year from the time, and "
4560 "defaults to 'T'.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004561
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004562 {"utcoffset", (PyCFunction)datetime_utcoffset, METH_NOARGS,
4563 PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004564
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004565 {"tzname", (PyCFunction)datetime_tzname, METH_NOARGS,
4566 PyDoc_STR("Return self.tzinfo.tzname(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004567
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004568 {"dst", (PyCFunction)datetime_dst, METH_NOARGS,
4569 PyDoc_STR("Return self.tzinfo.dst(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004570
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004571 {"replace", (PyCFunction)datetime_replace, METH_VARARGS | METH_KEYWORDS,
4572 PyDoc_STR("Return datetime with new specified fields.")},
Tim Peters12bf3392002-12-24 05:41:27 +00004573
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004574 {"astimezone", (PyCFunction)datetime_astimezone, METH_VARARGS | METH_KEYWORDS,
4575 PyDoc_STR("tz -> convert to local time in new timezone tz\n")},
Tim Peters80475bb2002-12-25 07:40:55 +00004576
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004577 {"__reduce__", (PyCFunction)datetime_reduce, METH_NOARGS,
4578 PyDoc_STR("__reduce__() -> (cls, state)")},
Guido van Rossum177e41a2003-01-30 22:06:23 +00004579
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004580 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00004581};
4582
Tim Petersa9bc1682003-01-11 03:39:11 +00004583static char datetime_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00004584PyDoc_STR("datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]])\n\
4585\n\
4586The year, month and day arguments are required. tzinfo may be None, or an\n\
4587instance of a tzinfo subclass. The remaining arguments may be ints or longs.\n");
Tim Peters2a799bf2002-12-16 20:18:38 +00004588
Tim Petersa9bc1682003-01-11 03:39:11 +00004589static PyNumberMethods datetime_as_number = {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004590 datetime_add, /* nb_add */
4591 datetime_subtract, /* nb_subtract */
4592 0, /* nb_multiply */
4593 0, /* nb_remainder */
4594 0, /* nb_divmod */
4595 0, /* nb_power */
4596 0, /* nb_negative */
4597 0, /* nb_positive */
4598 0, /* nb_absolute */
4599 0, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00004600};
4601
Neal Norwitz227b5332006-03-22 09:28:35 +00004602static PyTypeObject PyDateTime_DateTimeType = {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004603 PyVarObject_HEAD_INIT(NULL, 0)
4604 "datetime.datetime", /* tp_name */
4605 sizeof(PyDateTime_DateTime), /* tp_basicsize */
4606 0, /* tp_itemsize */
4607 (destructor)datetime_dealloc, /* tp_dealloc */
4608 0, /* tp_print */
4609 0, /* tp_getattr */
4610 0, /* tp_setattr */
4611 0, /* tp_reserved */
4612 (reprfunc)datetime_repr, /* tp_repr */
4613 &datetime_as_number, /* tp_as_number */
4614 0, /* tp_as_sequence */
4615 0, /* tp_as_mapping */
4616 (hashfunc)datetime_hash, /* tp_hash */
4617 0, /* tp_call */
4618 (reprfunc)datetime_str, /* tp_str */
4619 PyObject_GenericGetAttr, /* tp_getattro */
4620 0, /* tp_setattro */
4621 0, /* tp_as_buffer */
4622 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
4623 datetime_doc, /* tp_doc */
4624 0, /* tp_traverse */
4625 0, /* tp_clear */
4626 datetime_richcompare, /* tp_richcompare */
4627 0, /* tp_weaklistoffset */
4628 0, /* tp_iter */
4629 0, /* tp_iternext */
4630 datetime_methods, /* tp_methods */
4631 0, /* tp_members */
4632 datetime_getset, /* tp_getset */
4633 &PyDateTime_DateType, /* tp_base */
4634 0, /* tp_dict */
4635 0, /* tp_descr_get */
4636 0, /* tp_descr_set */
4637 0, /* tp_dictoffset */
4638 0, /* tp_init */
4639 datetime_alloc, /* tp_alloc */
4640 datetime_new, /* tp_new */
4641 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00004642};
4643
4644/* ---------------------------------------------------------------------------
4645 * Module methods and initialization.
4646 */
4647
4648static PyMethodDef module_methods[] = {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004649 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00004650};
4651
Tim Peters9ddf40b2004-06-20 22:41:32 +00004652/* C API. Clients get at this via PyDateTime_IMPORT, defined in
4653 * datetime.h.
4654 */
4655static PyDateTime_CAPI CAPI = {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004656 &PyDateTime_DateType,
4657 &PyDateTime_DateTimeType,
4658 &PyDateTime_TimeType,
4659 &PyDateTime_DeltaType,
4660 &PyDateTime_TZInfoType,
4661 new_date_ex,
4662 new_datetime_ex,
4663 new_time_ex,
4664 new_delta_ex,
4665 datetime_fromtimestamp,
4666 date_fromtimestamp
Tim Peters9ddf40b2004-06-20 22:41:32 +00004667};
4668
4669
Martin v. Löwis1a214512008-06-11 05:26:20 +00004670
4671static struct PyModuleDef datetimemodule = {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004672 PyModuleDef_HEAD_INIT,
4673 "datetime",
4674 "Fast implementation of the datetime type.",
4675 -1,
4676 module_methods,
4677 NULL,
4678 NULL,
4679 NULL,
4680 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00004681};
4682
Tim Peters2a799bf2002-12-16 20:18:38 +00004683PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00004684PyInit_datetime(void)
Tim Peters2a799bf2002-12-16 20:18:38 +00004685{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004686 PyObject *m; /* a module object */
4687 PyObject *d; /* its dict */
4688 PyObject *x;
Tim Peters2a799bf2002-12-16 20:18:38 +00004689
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004690 m = PyModule_Create(&datetimemodule);
4691 if (m == NULL)
4692 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004693
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004694 if (PyType_Ready(&PyDateTime_DateType) < 0)
4695 return NULL;
4696 if (PyType_Ready(&PyDateTime_DateTimeType) < 0)
4697 return NULL;
4698 if (PyType_Ready(&PyDateTime_DeltaType) < 0)
4699 return NULL;
4700 if (PyType_Ready(&PyDateTime_TimeType) < 0)
4701 return NULL;
4702 if (PyType_Ready(&PyDateTime_TZInfoType) < 0)
4703 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004704
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004705 /* timedelta values */
4706 d = PyDateTime_DeltaType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00004707
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004708 x = new_delta(0, 0, 1, 0);
4709 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4710 return NULL;
4711 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00004712
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004713 x = new_delta(-MAX_DELTA_DAYS, 0, 0, 0);
4714 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4715 return NULL;
4716 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00004717
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004718 x = new_delta(MAX_DELTA_DAYS, 24*3600-1, 1000000-1, 0);
4719 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4720 return NULL;
4721 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00004722
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004723 /* date values */
4724 d = PyDateTime_DateType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00004725
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004726 x = new_date(1, 1, 1);
4727 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4728 return NULL;
4729 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00004730
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004731 x = new_date(MAXYEAR, 12, 31);
4732 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4733 return NULL;
4734 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00004735
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004736 x = new_delta(1, 0, 0, 0);
4737 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4738 return NULL;
4739 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00004740
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004741 /* time values */
4742 d = PyDateTime_TimeType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00004743
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004744 x = new_time(0, 0, 0, 0, Py_None);
4745 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4746 return NULL;
4747 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00004748
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004749 x = new_time(23, 59, 59, 999999, Py_None);
4750 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4751 return NULL;
4752 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00004753
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004754 x = new_delta(0, 0, 1, 0);
4755 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4756 return NULL;
4757 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00004758
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004759 /* datetime values */
4760 d = PyDateTime_DateTimeType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00004761
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004762 x = new_datetime(1, 1, 1, 0, 0, 0, 0, Py_None);
4763 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4764 return NULL;
4765 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00004766
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004767 x = new_datetime(MAXYEAR, 12, 31, 23, 59, 59, 999999, Py_None);
4768 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4769 return NULL;
4770 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00004771
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004772 x = new_delta(0, 0, 1, 0);
4773 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4774 return NULL;
4775 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00004776
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004777 /* module initialization */
4778 PyModule_AddIntConstant(m, "MINYEAR", MINYEAR);
4779 PyModule_AddIntConstant(m, "MAXYEAR", MAXYEAR);
Tim Peters2a799bf2002-12-16 20:18:38 +00004780
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004781 Py_INCREF(&PyDateTime_DateType);
4782 PyModule_AddObject(m, "date", (PyObject *) &PyDateTime_DateType);
Tim Peters2a799bf2002-12-16 20:18:38 +00004783
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004784 Py_INCREF(&PyDateTime_DateTimeType);
4785 PyModule_AddObject(m, "datetime",
4786 (PyObject *)&PyDateTime_DateTimeType);
Tim Petersa9bc1682003-01-11 03:39:11 +00004787
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004788 Py_INCREF(&PyDateTime_TimeType);
4789 PyModule_AddObject(m, "time", (PyObject *) &PyDateTime_TimeType);
Tim Petersa9bc1682003-01-11 03:39:11 +00004790
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004791 Py_INCREF(&PyDateTime_DeltaType);
4792 PyModule_AddObject(m, "timedelta", (PyObject *) &PyDateTime_DeltaType);
Tim Peters2a799bf2002-12-16 20:18:38 +00004793
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004794 Py_INCREF(&PyDateTime_TZInfoType);
4795 PyModule_AddObject(m, "tzinfo", (PyObject *) &PyDateTime_TZInfoType);
Tim Peters2a799bf2002-12-16 20:18:38 +00004796
Benjamin Petersonb173f782009-05-05 22:31:58 +00004797 x = PyCapsule_New(&CAPI, PyDateTime_CAPSULE_NAME, NULL);
4798 if (x == NULL)
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004799 return NULL;
Benjamin Petersonb173f782009-05-05 22:31:58 +00004800 PyModule_AddObject(m, "datetime_CAPI", x);
Tim Peters9ddf40b2004-06-20 22:41:32 +00004801
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004802 /* A 4-year cycle has an extra leap day over what we'd get from
4803 * pasting together 4 single years.
4804 */
4805 assert(DI4Y == 4 * 365 + 1);
4806 assert(DI4Y == days_before_year(4+1));
Tim Peters2a799bf2002-12-16 20:18:38 +00004807
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004808 /* Similarly, a 400-year cycle has an extra leap day over what we'd
4809 * get from pasting together 4 100-year cycles.
4810 */
4811 assert(DI400Y == 4 * DI100Y + 1);
4812 assert(DI400Y == days_before_year(400+1));
Tim Peters2a799bf2002-12-16 20:18:38 +00004813
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004814 /* OTOH, a 100-year cycle has one fewer leap day than we'd get from
4815 * pasting together 25 4-year cycles.
4816 */
4817 assert(DI100Y == 25 * DI4Y - 1);
4818 assert(DI100Y == days_before_year(100+1));
Tim Peters2a799bf2002-12-16 20:18:38 +00004819
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004820 us_per_us = PyLong_FromLong(1);
4821 us_per_ms = PyLong_FromLong(1000);
4822 us_per_second = PyLong_FromLong(1000000);
4823 us_per_minute = PyLong_FromLong(60000000);
4824 seconds_per_day = PyLong_FromLong(24 * 3600);
4825 if (us_per_us == NULL || us_per_ms == NULL || us_per_second == NULL ||
4826 us_per_minute == NULL || seconds_per_day == NULL)
4827 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004828
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004829 /* The rest are too big for 32-bit ints, but even
4830 * us_per_week fits in 40 bits, so doubles should be exact.
4831 */
4832 us_per_hour = PyLong_FromDouble(3600000000.0);
4833 us_per_day = PyLong_FromDouble(86400000000.0);
4834 us_per_week = PyLong_FromDouble(604800000000.0);
4835 if (us_per_hour == NULL || us_per_day == NULL || us_per_week == NULL)
4836 return NULL;
4837 return m;
Tim Peters2a799bf2002-12-16 20:18:38 +00004838}
Tim Petersf3615152003-01-01 21:51:37 +00004839
4840/* ---------------------------------------------------------------------------
Tim Petersa9bc1682003-01-11 03:39:11 +00004841Some time zone algebra. For a datetime x, let
Tim Petersf3615152003-01-01 21:51:37 +00004842 x.n = x stripped of its timezone -- its naive time.
4843 x.o = x.utcoffset(), and assuming that doesn't raise an exception or
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004844 return None
Tim Petersf3615152003-01-01 21:51:37 +00004845 x.d = x.dst(), and assuming that doesn't raise an exception or
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004846 return None
Tim Petersf3615152003-01-01 21:51:37 +00004847 x.s = x's standard offset, x.o - x.d
4848
4849Now some derived rules, where k is a duration (timedelta).
4850
48511. x.o = x.s + x.d
4852 This follows from the definition of x.s.
4853
Tim Petersc5dc4da2003-01-02 17:55:03 +000048542. If x and y have the same tzinfo member, x.s = y.s.
Tim Petersf3615152003-01-01 21:51:37 +00004855 This is actually a requirement, an assumption we need to make about
4856 sane tzinfo classes.
4857
48583. The naive UTC time corresponding to x is x.n - x.o.
4859 This is again a requirement for a sane tzinfo class.
4860
48614. (x+k).s = x.s
Tim Peters8bb5ad22003-01-24 02:44:45 +00004862 This follows from #2, and that datimetimetz+timedelta preserves tzinfo.
Tim Petersf3615152003-01-01 21:51:37 +00004863
Tim Petersc5dc4da2003-01-02 17:55:03 +000048645. (x+k).n = x.n + k
Tim Petersf3615152003-01-01 21:51:37 +00004865 Again follows from how arithmetic is defined.
4866
Tim Peters8bb5ad22003-01-24 02:44:45 +00004867Now we can explain tz.fromutc(x). Let's assume it's an interesting case
Tim Petersf3615152003-01-01 21:51:37 +00004868(meaning that the various tzinfo methods exist, and don't blow up or return
4869None when called).
4870
Tim Petersa9bc1682003-01-11 03:39:11 +00004871The function wants to return a datetime y with timezone tz, equivalent to x.
Tim Peters8bb5ad22003-01-24 02:44:45 +00004872x is already in UTC.
Tim Petersf3615152003-01-01 21:51:37 +00004873
4874By #3, we want
4875
Tim Peters8bb5ad22003-01-24 02:44:45 +00004876 y.n - y.o = x.n [1]
Tim Petersf3615152003-01-01 21:51:37 +00004877
4878The algorithm starts by attaching tz to x.n, and calling that y. So
4879x.n = y.n at the start. Then it wants to add a duration k to y, so that [1]
4880becomes true; in effect, we want to solve [2] for k:
4881
Tim Peters8bb5ad22003-01-24 02:44:45 +00004882 (y+k).n - (y+k).o = x.n [2]
Tim Petersf3615152003-01-01 21:51:37 +00004883
4884By #1, this is the same as
4885
Tim Peters8bb5ad22003-01-24 02:44:45 +00004886 (y+k).n - ((y+k).s + (y+k).d) = x.n [3]
Tim Petersf3615152003-01-01 21:51:37 +00004887
4888By #5, (y+k).n = y.n + k, which equals x.n + k because x.n=y.n at the start.
4889Substituting that into [3],
4890
Tim Peters8bb5ad22003-01-24 02:44:45 +00004891 x.n + k - (y+k).s - (y+k).d = x.n; the x.n terms cancel, leaving
4892 k - (y+k).s - (y+k).d = 0; rearranging,
4893 k = (y+k).s - (y+k).d; by #4, (y+k).s == y.s, so
4894 k = y.s - (y+k).d
Tim Petersf3615152003-01-01 21:51:37 +00004895
Tim Peters8bb5ad22003-01-24 02:44:45 +00004896On the RHS, (y+k).d can't be computed directly, but y.s can be, and we
4897approximate k by ignoring the (y+k).d term at first. Note that k can't be
4898very large, since all offset-returning methods return a duration of magnitude
4899less than 24 hours. For that reason, if y is firmly in std time, (y+k).d must
4900be 0, so ignoring it has no consequence then.
Tim Petersf3615152003-01-01 21:51:37 +00004901
4902In any case, the new value is
4903
Tim Peters8bb5ad22003-01-24 02:44:45 +00004904 z = y + y.s [4]
Tim Petersf3615152003-01-01 21:51:37 +00004905
Tim Peters8bb5ad22003-01-24 02:44:45 +00004906It's helpful to step back at look at [4] from a higher level: it's simply
4907mapping from UTC to tz's standard time.
Tim Petersc5dc4da2003-01-02 17:55:03 +00004908
4909At this point, if
4910
Tim Peters8bb5ad22003-01-24 02:44:45 +00004911 z.n - z.o = x.n [5]
Tim Petersc5dc4da2003-01-02 17:55:03 +00004912
4913we have an equivalent time, and are almost done. The insecurity here is
Tim Petersf3615152003-01-01 21:51:37 +00004914at the start of daylight time. Picture US Eastern for concreteness. The wall
4915time 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 +00004916sense then. The docs ask that an Eastern tzinfo class consider such a time to
4917be EDT (because it's "after 2"), which is a redundant spelling of 1:MM EST
4918on the day DST starts. We want to return the 1:MM EST spelling because that's
Tim Petersf3615152003-01-01 21:51:37 +00004919the only spelling that makes sense on the local wall clock.
4920
Tim Petersc5dc4da2003-01-02 17:55:03 +00004921In fact, if [5] holds at this point, we do have the standard-time spelling,
4922but that takes a bit of proof. We first prove a stronger result. What's the
4923difference between the LHS and RHS of [5]? Let
Tim Petersf3615152003-01-01 21:51:37 +00004924
Tim Peters8bb5ad22003-01-24 02:44:45 +00004925 diff = x.n - (z.n - z.o) [6]
Tim Petersf3615152003-01-01 21:51:37 +00004926
Tim Petersc5dc4da2003-01-02 17:55:03 +00004927Now
4928 z.n = by [4]
Tim Peters8bb5ad22003-01-24 02:44:45 +00004929 (y + y.s).n = by #5
4930 y.n + y.s = since y.n = x.n
4931 x.n + y.s = since z and y are have the same tzinfo member,
4932 y.s = z.s by #2
4933 x.n + z.s
Tim Petersf3615152003-01-01 21:51:37 +00004934
Tim Petersc5dc4da2003-01-02 17:55:03 +00004935Plugging that back into [6] gives
Tim Petersf3615152003-01-01 21:51:37 +00004936
Tim Petersc5dc4da2003-01-02 17:55:03 +00004937 diff =
Tim Peters8bb5ad22003-01-24 02:44:45 +00004938 x.n - ((x.n + z.s) - z.o) = expanding
4939 x.n - x.n - z.s + z.o = cancelling
4940 - z.s + z.o = by #2
Tim Petersc5dc4da2003-01-02 17:55:03 +00004941 z.d
Tim Petersf3615152003-01-01 21:51:37 +00004942
Tim Petersc5dc4da2003-01-02 17:55:03 +00004943So diff = z.d.
Tim Petersf3615152003-01-01 21:51:37 +00004944
Tim Petersc5dc4da2003-01-02 17:55:03 +00004945If [5] is true now, diff = 0, so z.d = 0 too, and we have the standard-time
Tim Peters8bb5ad22003-01-24 02:44:45 +00004946spelling we wanted in the endcase described above. We're done. Contrarily,
4947if z.d = 0, then we have a UTC equivalent, and are also done.
Tim Petersf3615152003-01-01 21:51:37 +00004948
Tim Petersc5dc4da2003-01-02 17:55:03 +00004949If [5] is not true now, diff = z.d != 0, and z.d is the offset we need to
4950add to z (in effect, z is in tz's standard time, and we need to shift the
Tim Peters8bb5ad22003-01-24 02:44:45 +00004951local clock into tz's daylight time).
Tim Petersf3615152003-01-01 21:51:37 +00004952
Tim Petersc5dc4da2003-01-02 17:55:03 +00004953Let
Tim Petersf3615152003-01-01 21:51:37 +00004954
Tim Peters4fede1a2003-01-04 00:26:59 +00004955 z' = z + z.d = z + diff [7]
Tim Petersc3bb26a2003-01-02 03:14:59 +00004956
Tim Peters4fede1a2003-01-04 00:26:59 +00004957and we can again ask whether
Tim Petersc3bb26a2003-01-02 03:14:59 +00004958
Tim Peters8bb5ad22003-01-24 02:44:45 +00004959 z'.n - z'.o = x.n [8]
Tim Petersc3bb26a2003-01-02 03:14:59 +00004960
Tim Peters8bb5ad22003-01-24 02:44:45 +00004961If so, we're done. If not, the tzinfo class is insane, according to the
4962assumptions we've made. This also requires a bit of proof. As before, let's
4963compute the difference between the LHS and RHS of [8] (and skipping some of
4964the justifications for the kinds of substitutions we've done several times
4965already):
Tim Peters4fede1a2003-01-04 00:26:59 +00004966
Tim Peters8bb5ad22003-01-24 02:44:45 +00004967 diff' = x.n - (z'.n - z'.o) = replacing z'.n via [7]
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00004968 x.n - (z.n + diff - z'.o) = replacing diff via [6]
4969 x.n - (z.n + x.n - (z.n - z.o) - z'.o) =
4970 x.n - z.n - x.n + z.n - z.o + z'.o = cancel x.n
4971 - z.n + z.n - z.o + z'.o = cancel z.n
4972 - z.o + z'.o = #1 twice
4973 -z.s - z.d + z'.s + z'.d = z and z' have same tzinfo
4974 z'.d - z.d
Tim Peters4fede1a2003-01-04 00:26:59 +00004975
4976So 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 +00004977we've found the UTC-equivalent so are done. In fact, we stop with [7] and
4978return z', not bothering to compute z'.d.
Tim Peters4fede1a2003-01-04 00:26:59 +00004979
Tim Peters8bb5ad22003-01-24 02:44:45 +00004980How could z.d and z'd differ? z' = z + z.d [7], so merely moving z' by
4981a dst() offset, and starting *from* a time already in DST (we know z.d != 0),
4982would have to change the result dst() returns: we start in DST, and moving
4983a little further into it takes us out of DST.
Tim Peters4fede1a2003-01-04 00:26:59 +00004984
Tim Peters8bb5ad22003-01-24 02:44:45 +00004985There isn't a sane case where this can happen. The closest it gets is at
4986the end of DST, where there's an hour in UTC with no spelling in a hybrid
4987tzinfo class. In US Eastern, that's 5:MM UTC = 0:MM EST = 1:MM EDT. During
4988that hour, on an Eastern clock 1:MM is taken as being in standard time (6:MM
4989UTC) because the docs insist on that, but 0:MM is taken as being in daylight
4990time (4:MM UTC). There is no local time mapping to 5:MM UTC. The local
4991clock jumps from 1:59 back to 1:00 again, and repeats the 1:MM hour in
4992standard time. Since that's what the local clock *does*, we want to map both
4993UTC hours 5:MM and 6:MM to 1:MM Eastern. The result is ambiguous
Tim Peters4fede1a2003-01-04 00:26:59 +00004994in local time, but so it goes -- it's the way the local clock works.
4995
Tim Peters8bb5ad22003-01-24 02:44:45 +00004996When x = 5:MM UTC is the input to this algorithm, x.o=0, y.o=-5 and y.d=0,
4997so z=0:MM. z.d=60 (minutes) then, so [5] doesn't hold and we keep going.
4998z' = 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 +00004999(correctly) concludes that z' is not UTC-equivalent to x.
5000
5001Because we know z.d said z was in daylight time (else [5] would have held and
5002we would have stopped then), and we know z.d != z'.d (else [8] would have held
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +00005003and we would have stopped then), and there are only 2 possible values dst() can
Tim Peters4fede1a2003-01-04 00:26:59 +00005004return in Eastern, it follows that z'.d must be 0 (which it is in the example,
5005but the reasoning doesn't depend on the example -- it depends on there being
5006two possible dst() outcomes, one zero and the other non-zero). Therefore
Tim Peters8bb5ad22003-01-24 02:44:45 +00005007z' must be in standard time, and is the spelling we want in this case.
5008
5009Note again that z' is not UTC-equivalent as far as the hybrid tzinfo class is
5010concerned (because it takes z' as being in standard time rather than the
5011daylight time we intend here), but returning it gives the real-life "local
5012clock repeats an hour" behavior when mapping the "unspellable" UTC hour into
5013tz.
5014
5015When the input is 6:MM, z=1:MM and z.d=0, and we stop at once, again with
5016the 1:MM standard time spelling we want.
5017
5018So how can this break? One of the assumptions must be violated. Two
5019possibilities:
5020
50211) [2] effectively says that y.s is invariant across all y belong to a given
5022 time zone. This isn't true if, for political reasons or continental drift,
5023 a region decides to change its base offset from UTC.
5024
50252) There may be versions of "double daylight" time where the tail end of
5026 the analysis gives up a step too early. I haven't thought about that
5027 enough to say.
5028
5029In any case, it's clear that the default fromutc() is strong enough to handle
5030"almost all" time zones: so long as the standard offset is invariant, it
5031doesn't matter if daylight time transition points change from year to year, or
5032if daylight time is skipped in some years; it doesn't matter how large or
5033small dst() may get within its bounds; and it doesn't even matter if some
5034perverse time zone returns a negative dst()). So a breaking case must be
5035pretty bizarre, and a tzinfo subclass can override fromutc() if it is.
Tim Petersf3615152003-01-01 21:51:37 +00005036--------------------------------------------------------------------------- */