blob: c81f6bb81d45271cc446a8cdc75739bf5ca383c9 [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
Gregory P. Smith137d8242008-06-02 04:05:52 +00005#define PY_SSIZE_T_CLEAN
6
Tim Peters2a799bf2002-12-16 20:18:38 +00007#include "Python.h"
8#include "modsupport.h"
9#include "structmember.h"
10
11#include <time.h>
12
Tim Peters1b6f7a92004-06-20 02:50:16 +000013#include "timefuncs.h"
Tim Peters9ddf40b2004-06-20 22:41:32 +000014
15/* Differentiate between building the core module and building extension
16 * modules.
17 */
Kristján Valur Jónsson7a0da192007-04-30 15:17:46 +000018#ifndef Py_BUILD_CORE
Tim Peters9ddf40b2004-06-20 22:41:32 +000019#define Py_BUILD_CORE
Kristján Valur Jónsson7a0da192007-04-30 15:17:46 +000020#endif
Tim Peters2a799bf2002-12-16 20:18:38 +000021#include "datetime.h"
Tim Peters9ddf40b2004-06-20 22:41:32 +000022#undef Py_BUILD_CORE
Tim Peters2a799bf2002-12-16 20:18:38 +000023
24/* We require that C int be at least 32 bits, and use int virtually
25 * everywhere. In just a few cases we use a temp long, where a Python
26 * API returns a C long. In such cases, we have to ensure that the
27 * final result fits in a C int (this can be an issue on 64-bit boxes).
28 */
29#if SIZEOF_INT < 4
Antoine Pitrouc83ea132010-05-09 14:46:46 +000030# error "datetime.c requires that C int have at least 32 bits"
Tim Peters2a799bf2002-12-16 20:18:38 +000031#endif
32
33#define MINYEAR 1
34#define MAXYEAR 9999
35
36/* Nine decimal digits is easy to communicate, and leaves enough room
37 * so that two delta days can be added w/o fear of overflowing a signed
38 * 32-bit int, and with plenty of room left over to absorb any possible
39 * carries from adding seconds.
40 */
41#define MAX_DELTA_DAYS 999999999
42
43/* Rename the long macros in datetime.h to more reasonable short names. */
Antoine Pitrouc83ea132010-05-09 14:46:46 +000044#define GET_YEAR PyDateTime_GET_YEAR
45#define GET_MONTH PyDateTime_GET_MONTH
46#define GET_DAY PyDateTime_GET_DAY
47#define DATE_GET_HOUR PyDateTime_DATE_GET_HOUR
48#define DATE_GET_MINUTE PyDateTime_DATE_GET_MINUTE
49#define DATE_GET_SECOND PyDateTime_DATE_GET_SECOND
50#define DATE_GET_MICROSECOND PyDateTime_DATE_GET_MICROSECOND
Tim Peters2a799bf2002-12-16 20:18:38 +000051
52/* Date accessors for date and datetime. */
Antoine Pitrouc83ea132010-05-09 14:46:46 +000053#define SET_YEAR(o, v) (((o)->data[0] = ((v) & 0xff00) >> 8), \
54 ((o)->data[1] = ((v) & 0x00ff)))
55#define SET_MONTH(o, v) (PyDateTime_GET_MONTH(o) = (v))
56#define SET_DAY(o, v) (PyDateTime_GET_DAY(o) = (v))
Tim Peters2a799bf2002-12-16 20:18:38 +000057
58/* Date/Time accessors for datetime. */
Antoine Pitrouc83ea132010-05-09 14:46:46 +000059#define DATE_SET_HOUR(o, v) (PyDateTime_DATE_GET_HOUR(o) = (v))
60#define DATE_SET_MINUTE(o, v) (PyDateTime_DATE_GET_MINUTE(o) = (v))
61#define DATE_SET_SECOND(o, v) (PyDateTime_DATE_GET_SECOND(o) = (v))
62#define DATE_SET_MICROSECOND(o, v) \
63 (((o)->data[7] = ((v) & 0xff0000) >> 16), \
64 ((o)->data[8] = ((v) & 0x00ff00) >> 8), \
65 ((o)->data[9] = ((v) & 0x0000ff)))
Tim Peters2a799bf2002-12-16 20:18:38 +000066
67/* Time accessors for time. */
Antoine Pitrouc83ea132010-05-09 14:46:46 +000068#define TIME_GET_HOUR PyDateTime_TIME_GET_HOUR
69#define TIME_GET_MINUTE PyDateTime_TIME_GET_MINUTE
70#define TIME_GET_SECOND PyDateTime_TIME_GET_SECOND
71#define TIME_GET_MICROSECOND PyDateTime_TIME_GET_MICROSECOND
72#define TIME_SET_HOUR(o, v) (PyDateTime_TIME_GET_HOUR(o) = (v))
73#define TIME_SET_MINUTE(o, v) (PyDateTime_TIME_GET_MINUTE(o) = (v))
74#define TIME_SET_SECOND(o, v) (PyDateTime_TIME_GET_SECOND(o) = (v))
75#define TIME_SET_MICROSECOND(o, v) \
76 (((o)->data[3] = ((v) & 0xff0000) >> 16), \
77 ((o)->data[4] = ((v) & 0x00ff00) >> 8), \
78 ((o)->data[5] = ((v) & 0x0000ff)))
Tim Peters2a799bf2002-12-16 20:18:38 +000079
80/* Delta accessors for timedelta. */
Antoine Pitrouc83ea132010-05-09 14:46:46 +000081#define GET_TD_DAYS(o) (((PyDateTime_Delta *)(o))->days)
82#define GET_TD_SECONDS(o) (((PyDateTime_Delta *)(o))->seconds)
83#define GET_TD_MICROSECONDS(o) (((PyDateTime_Delta *)(o))->microseconds)
Tim Peters2a799bf2002-12-16 20:18:38 +000084
Antoine Pitrouc83ea132010-05-09 14:46:46 +000085#define SET_TD_DAYS(o, v) ((o)->days = (v))
86#define SET_TD_SECONDS(o, v) ((o)->seconds = (v))
Tim Peters2a799bf2002-12-16 20:18:38 +000087#define SET_TD_MICROSECONDS(o, v) ((o)->microseconds = (v))
88
Tim Petersa032d2e2003-01-11 00:15:54 +000089/* p is a pointer to a time or a datetime object; HASTZINFO(p) returns
90 * p->hastzinfo.
91 */
Antoine Pitrouc83ea132010-05-09 14:46:46 +000092#define HASTZINFO(p) (((_PyDateTime_BaseTZInfo *)(p))->hastzinfo)
Tim Petersa032d2e2003-01-11 00:15:54 +000093
Tim Peters3f606292004-03-21 23:38:41 +000094/* M is a char or int claiming to be a valid month. The macro is equivalent
95 * to the two-sided Python test
Antoine Pitrouc83ea132010-05-09 14:46:46 +000096 * 1 <= M <= 12
Tim Peters3f606292004-03-21 23:38:41 +000097 */
98#define MONTH_IS_SANE(M) ((unsigned int)(M) - 1 < 12)
99
Tim Peters2a799bf2002-12-16 20:18:38 +0000100/* Forward declarations. */
101static PyTypeObject PyDateTime_DateType;
102static PyTypeObject PyDateTime_DateTimeType;
Tim Peters2a799bf2002-12-16 20:18:38 +0000103static PyTypeObject PyDateTime_DeltaType;
104static PyTypeObject PyDateTime_TimeType;
105static PyTypeObject PyDateTime_TZInfoType;
Tim Peters2a799bf2002-12-16 20:18:38 +0000106
107/* ---------------------------------------------------------------------------
108 * Math utilities.
109 */
110
111/* k = i+j overflows iff k differs in sign from both inputs,
112 * iff k^i has sign bit set and k^j has sign bit set,
113 * iff (k^i)&(k^j) has sign bit set.
114 */
115#define SIGNED_ADD_OVERFLOWED(RESULT, I, J) \
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000116 ((((RESULT) ^ (I)) & ((RESULT) ^ (J))) < 0)
Tim Peters2a799bf2002-12-16 20:18:38 +0000117
118/* Compute Python divmod(x, y), returning the quotient and storing the
119 * remainder into *r. The quotient is the floor of x/y, and that's
120 * the real point of this. C will probably truncate instead (C99
121 * requires truncation; C89 left it implementation-defined).
122 * Simplification: we *require* that y > 0 here. That's appropriate
123 * for all the uses made of it. This simplifies the code and makes
124 * the overflow case impossible (divmod(LONG_MIN, -1) is the only
125 * overflow case).
126 */
127static int
128divmod(int x, int y, int *r)
129{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000130 int quo;
Tim Peters2a799bf2002-12-16 20:18:38 +0000131
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000132 assert(y > 0);
133 quo = x / y;
134 *r = x - quo * y;
135 if (*r < 0) {
136 --quo;
137 *r += y;
138 }
139 assert(0 <= *r && *r < y);
140 return quo;
Tim Peters2a799bf2002-12-16 20:18:38 +0000141}
142
Tim Peters5d644dd2003-01-02 16:32:54 +0000143/* Round a double to the nearest long. |x| must be small enough to fit
144 * in a C long; this is not checked.
145 */
146static long
147round_to_long(double x)
148{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000149 if (x >= 0.0)
150 x = floor(x + 0.5);
151 else
152 x = ceil(x - 0.5);
153 return (long)x;
Tim Peters5d644dd2003-01-02 16:32:54 +0000154}
155
Tim Peters2a799bf2002-12-16 20:18:38 +0000156/* ---------------------------------------------------------------------------
157 * General calendrical helper functions
158 */
159
160/* For each month ordinal in 1..12, the number of days in that month,
161 * and the number of days before that month in the same year. These
162 * are correct for non-leap years only.
163 */
164static int _days_in_month[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000165 0, /* unused; this vector uses 1-based indexing */
166 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
Tim Peters2a799bf2002-12-16 20:18:38 +0000167};
168
169static int _days_before_month[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000170 0, /* unused; this vector uses 1-based indexing */
171 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
Tim Peters2a799bf2002-12-16 20:18:38 +0000172};
173
174/* year -> 1 if leap year, else 0. */
175static int
176is_leap(int year)
177{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000178 /* Cast year to unsigned. The result is the same either way, but
179 * C can generate faster code for unsigned mod than for signed
180 * mod (especially for % 4 -- a good compiler should just grab
181 * the last 2 bits when the LHS is unsigned).
182 */
183 const unsigned int ayear = (unsigned int)year;
184 return ayear % 4 == 0 && (ayear % 100 != 0 || ayear % 400 == 0);
Tim Peters2a799bf2002-12-16 20:18:38 +0000185}
186
187/* year, month -> number of days in that month in that year */
188static int
189days_in_month(int year, int month)
190{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000191 assert(month >= 1);
192 assert(month <= 12);
193 if (month == 2 && is_leap(year))
194 return 29;
195 else
196 return _days_in_month[month];
Tim Peters2a799bf2002-12-16 20:18:38 +0000197}
198
199/* year, month -> number of days in year preceeding first day of month */
200static int
201days_before_month(int year, int month)
202{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000203 int days;
Tim Peters2a799bf2002-12-16 20:18:38 +0000204
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000205 assert(month >= 1);
206 assert(month <= 12);
207 days = _days_before_month[month];
208 if (month > 2 && is_leap(year))
209 ++days;
210 return days;
Tim Peters2a799bf2002-12-16 20:18:38 +0000211}
212
213/* year -> number of days before January 1st of year. Remember that we
214 * start with year 1, so days_before_year(1) == 0.
215 */
216static int
217days_before_year(int year)
218{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000219 int y = year - 1;
220 /* This is incorrect if year <= 0; we really want the floor
221 * here. But so long as MINYEAR is 1, the smallest year this
222 * can see is 0 (this can happen in some normalization endcases),
223 * so we'll just special-case that.
224 */
225 assert (year >= 0);
226 if (y >= 0)
227 return y*365 + y/4 - y/100 + y/400;
228 else {
229 assert(y == -1);
230 return -366;
231 }
Tim Peters2a799bf2002-12-16 20:18:38 +0000232}
233
234/* Number of days in 4, 100, and 400 year cycles. That these have
235 * the correct values is asserted in the module init function.
236 */
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000237#define DI4Y 1461 /* days_before_year(5); days in 4 years */
238#define DI100Y 36524 /* days_before_year(101); days in 100 years */
239#define DI400Y 146097 /* days_before_year(401); days in 400 years */
Tim Peters2a799bf2002-12-16 20:18:38 +0000240
241/* ordinal -> year, month, day, considering 01-Jan-0001 as day 1. */
242static void
243ord_to_ymd(int ordinal, int *year, int *month, int *day)
244{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000245 int n, n1, n4, n100, n400, leapyear, preceding;
Tim Peters2a799bf2002-12-16 20:18:38 +0000246
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000247 /* ordinal is a 1-based index, starting at 1-Jan-1. The pattern of
248 * leap years repeats exactly every 400 years. The basic strategy is
249 * to find the closest 400-year boundary at or before ordinal, then
250 * work with the offset from that boundary to ordinal. Life is much
251 * clearer if we subtract 1 from ordinal first -- then the values
252 * of ordinal at 400-year boundaries are exactly those divisible
253 * by DI400Y:
254 *
255 * D M Y n n-1
256 * -- --- ---- ---------- ----------------
257 * 31 Dec -400 -DI400Y -DI400Y -1
258 * 1 Jan -399 -DI400Y +1 -DI400Y 400-year boundary
259 * ...
260 * 30 Dec 000 -1 -2
261 * 31 Dec 000 0 -1
262 * 1 Jan 001 1 0 400-year boundary
263 * 2 Jan 001 2 1
264 * 3 Jan 001 3 2
265 * ...
266 * 31 Dec 400 DI400Y DI400Y -1
267 * 1 Jan 401 DI400Y +1 DI400Y 400-year boundary
268 */
269 assert(ordinal >= 1);
270 --ordinal;
271 n400 = ordinal / DI400Y;
272 n = ordinal % DI400Y;
273 *year = n400 * 400 + 1;
Tim Peters2a799bf2002-12-16 20:18:38 +0000274
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000275 /* Now n is the (non-negative) offset, in days, from January 1 of
276 * year, to the desired date. Now compute how many 100-year cycles
277 * precede n.
278 * Note that it's possible for n100 to equal 4! In that case 4 full
279 * 100-year cycles precede the desired day, which implies the
280 * desired day is December 31 at the end of a 400-year cycle.
281 */
282 n100 = n / DI100Y;
283 n = n % DI100Y;
Tim Peters2a799bf2002-12-16 20:18:38 +0000284
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000285 /* Now compute how many 4-year cycles precede it. */
286 n4 = n / DI4Y;
287 n = n % DI4Y;
Tim Peters2a799bf2002-12-16 20:18:38 +0000288
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000289 /* And now how many single years. Again n1 can be 4, and again
290 * meaning that the desired day is December 31 at the end of the
291 * 4-year cycle.
292 */
293 n1 = n / 365;
294 n = n % 365;
Tim Peters2a799bf2002-12-16 20:18:38 +0000295
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000296 *year += n100 * 100 + n4 * 4 + n1;
297 if (n1 == 4 || n100 == 4) {
298 assert(n == 0);
299 *year -= 1;
300 *month = 12;
301 *day = 31;
302 return;
303 }
Tim Peters2a799bf2002-12-16 20:18:38 +0000304
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000305 /* Now the year is correct, and n is the offset from January 1. We
306 * find the month via an estimate that's either exact or one too
307 * large.
308 */
309 leapyear = n1 == 3 && (n4 != 24 || n100 == 3);
310 assert(leapyear == is_leap(*year));
311 *month = (n + 50) >> 5;
312 preceding = (_days_before_month[*month] + (*month > 2 && leapyear));
313 if (preceding > n) {
314 /* estimate is too large */
315 *month -= 1;
316 preceding -= days_in_month(*year, *month);
317 }
318 n -= preceding;
319 assert(0 <= n);
320 assert(n < days_in_month(*year, *month));
Tim Peters2a799bf2002-12-16 20:18:38 +0000321
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000322 *day = n + 1;
Tim Peters2a799bf2002-12-16 20:18:38 +0000323}
324
325/* year, month, day -> ordinal, considering 01-Jan-0001 as day 1. */
326static int
327ymd_to_ord(int year, int month, int day)
328{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000329 return days_before_year(year) + days_before_month(year, month) + day;
Tim Peters2a799bf2002-12-16 20:18:38 +0000330}
331
332/* Day of week, where Monday==0, ..., Sunday==6. 1/1/1 was a Monday. */
333static int
334weekday(int year, int month, int day)
335{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000336 return (ymd_to_ord(year, month, day) + 6) % 7;
Tim Peters2a799bf2002-12-16 20:18:38 +0000337}
338
339/* Ordinal of the Monday starting week 1 of the ISO year. Week 1 is the
340 * first calendar week containing a Thursday.
341 */
342static int
343iso_week1_monday(int year)
344{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000345 int first_day = ymd_to_ord(year, 1, 1); /* ord of 1/1 */
346 /* 0 if 1/1 is a Monday, 1 if a Tue, etc. */
347 int first_weekday = (first_day + 6) % 7;
348 /* ordinal of closest Monday at or before 1/1 */
349 int week1_monday = first_day - first_weekday;
Tim Peters2a799bf2002-12-16 20:18:38 +0000350
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000351 if (first_weekday > 3) /* if 1/1 was Fri, Sat, Sun */
352 week1_monday += 7;
353 return week1_monday;
Tim Peters2a799bf2002-12-16 20:18:38 +0000354}
355
356/* ---------------------------------------------------------------------------
357 * Range checkers.
358 */
359
360/* Check that -MAX_DELTA_DAYS <= days <= MAX_DELTA_DAYS. If so, return 0.
361 * If not, raise OverflowError and return -1.
362 */
363static int
364check_delta_day_range(int days)
365{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000366 if (-MAX_DELTA_DAYS <= days && days <= MAX_DELTA_DAYS)
367 return 0;
368 PyErr_Format(PyExc_OverflowError,
369 "days=%d; must have magnitude <= %d",
370 days, MAX_DELTA_DAYS);
371 return -1;
Tim Peters2a799bf2002-12-16 20:18:38 +0000372}
373
374/* Check that date arguments are in range. Return 0 if they are. If they
375 * aren't, raise ValueError and return -1.
376 */
377static int
378check_date_args(int year, int month, int day)
379{
380
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000381 if (year < MINYEAR || year > MAXYEAR) {
382 PyErr_SetString(PyExc_ValueError,
383 "year is out of range");
384 return -1;
385 }
386 if (month < 1 || month > 12) {
387 PyErr_SetString(PyExc_ValueError,
388 "month must be in 1..12");
389 return -1;
390 }
391 if (day < 1 || day > days_in_month(year, month)) {
392 PyErr_SetString(PyExc_ValueError,
393 "day is out of range for month");
394 return -1;
395 }
396 return 0;
Tim Peters2a799bf2002-12-16 20:18:38 +0000397}
398
399/* Check that time arguments are in range. Return 0 if they are. If they
400 * aren't, raise ValueError and return -1.
401 */
402static int
403check_time_args(int h, int m, int s, int us)
404{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000405 if (h < 0 || h > 23) {
406 PyErr_SetString(PyExc_ValueError,
407 "hour must be in 0..23");
408 return -1;
409 }
410 if (m < 0 || m > 59) {
411 PyErr_SetString(PyExc_ValueError,
412 "minute must be in 0..59");
413 return -1;
414 }
415 if (s < 0 || s > 59) {
416 PyErr_SetString(PyExc_ValueError,
417 "second must be in 0..59");
418 return -1;
419 }
420 if (us < 0 || us > 999999) {
421 PyErr_SetString(PyExc_ValueError,
422 "microsecond must be in 0..999999");
423 return -1;
424 }
425 return 0;
Tim Peters2a799bf2002-12-16 20:18:38 +0000426}
427
428/* ---------------------------------------------------------------------------
429 * Normalization utilities.
430 */
431
432/* One step of a mixed-radix conversion. A "hi" unit is equivalent to
433 * factor "lo" units. factor must be > 0. If *lo is less than 0, or
434 * at least factor, enough of *lo is converted into "hi" units so that
435 * 0 <= *lo < factor. The input values must be such that int overflow
436 * is impossible.
437 */
438static void
439normalize_pair(int *hi, int *lo, int factor)
440{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000441 assert(factor > 0);
442 assert(lo != hi);
443 if (*lo < 0 || *lo >= factor) {
444 const int num_hi = divmod(*lo, factor, lo);
445 const int new_hi = *hi + num_hi;
446 assert(! SIGNED_ADD_OVERFLOWED(new_hi, *hi, num_hi));
447 *hi = new_hi;
448 }
449 assert(0 <= *lo && *lo < factor);
Tim Peters2a799bf2002-12-16 20:18:38 +0000450}
451
452/* Fiddle days (d), seconds (s), and microseconds (us) so that
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000453 * 0 <= *s < 24*3600
454 * 0 <= *us < 1000000
Tim Peters2a799bf2002-12-16 20:18:38 +0000455 * The input values must be such that the internals don't overflow.
456 * The way this routine is used, we don't get close.
457 */
458static void
459normalize_d_s_us(int *d, int *s, int *us)
460{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000461 if (*us < 0 || *us >= 1000000) {
462 normalize_pair(s, us, 1000000);
463 /* |s| can't be bigger than about
464 * |original s| + |original us|/1000000 now.
465 */
Tim Peters2a799bf2002-12-16 20:18:38 +0000466
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000467 }
468 if (*s < 0 || *s >= 24*3600) {
469 normalize_pair(d, s, 24*3600);
470 /* |d| can't be bigger than about
471 * |original d| +
472 * (|original s| + |original us|/1000000) / (24*3600) now.
473 */
474 }
475 assert(0 <= *s && *s < 24*3600);
476 assert(0 <= *us && *us < 1000000);
Tim Peters2a799bf2002-12-16 20:18:38 +0000477}
478
479/* Fiddle years (y), months (m), and days (d) so that
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000480 * 1 <= *m <= 12
481 * 1 <= *d <= days_in_month(*y, *m)
Tim Peters2a799bf2002-12-16 20:18:38 +0000482 * The input values must be such that the internals don't overflow.
483 * The way this routine is used, we don't get close.
484 */
485static void
486normalize_y_m_d(int *y, int *m, int *d)
487{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000488 int dim; /* # of days in month */
Tim Peters2a799bf2002-12-16 20:18:38 +0000489
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000490 /* This gets muddy: the proper range for day can't be determined
491 * without knowing the correct month and year, but if day is, e.g.,
492 * plus or minus a million, the current month and year values make
493 * no sense (and may also be out of bounds themselves).
494 * Saying 12 months == 1 year should be non-controversial.
495 */
496 if (*m < 1 || *m > 12) {
497 --*m;
498 normalize_pair(y, m, 12);
499 ++*m;
500 /* |y| can't be bigger than about
501 * |original y| + |original m|/12 now.
502 */
503 }
504 assert(1 <= *m && *m <= 12);
Tim Peters2a799bf2002-12-16 20:18:38 +0000505
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000506 /* Now only day can be out of bounds (year may also be out of bounds
507 * for a datetime object, but we don't care about that here).
508 * If day is out of bounds, what to do is arguable, but at least the
509 * method here is principled and explainable.
510 */
511 dim = days_in_month(*y, *m);
512 if (*d < 1 || *d > dim) {
513 /* Move day-1 days from the first of the month. First try to
514 * get off cheap if we're only one day out of range
515 * (adjustments for timezone alone can't be worse than that).
516 */
517 if (*d == 0) {
518 --*m;
519 if (*m > 0)
520 *d = days_in_month(*y, *m);
521 else {
522 --*y;
523 *m = 12;
524 *d = 31;
525 }
526 }
527 else if (*d == dim + 1) {
528 /* move forward a day */
529 ++*m;
530 *d = 1;
531 if (*m > 12) {
532 *m = 1;
533 ++*y;
534 }
535 }
536 else {
537 int ordinal = ymd_to_ord(*y, *m, 1) +
538 *d - 1;
539 ord_to_ymd(ordinal, y, m, d);
540 }
541 }
542 assert(*m > 0);
543 assert(*d > 0);
Tim Peters2a799bf2002-12-16 20:18:38 +0000544}
545
546/* Fiddle out-of-bounds months and days so that the result makes some kind
547 * of sense. The parameters are both inputs and outputs. Returns < 0 on
548 * failure, where failure means the adjusted year is out of bounds.
549 */
550static int
551normalize_date(int *year, int *month, int *day)
552{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000553 int result;
Tim Peters2a799bf2002-12-16 20:18:38 +0000554
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000555 normalize_y_m_d(year, month, day);
556 if (MINYEAR <= *year && *year <= MAXYEAR)
557 result = 0;
558 else {
559 PyErr_SetString(PyExc_OverflowError,
560 "date value out of range");
561 result = -1;
562 }
563 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +0000564}
565
566/* Force all the datetime fields into range. The parameters are both
567 * inputs and outputs. Returns < 0 on error.
568 */
569static int
570normalize_datetime(int *year, int *month, int *day,
571 int *hour, int *minute, int *second,
572 int *microsecond)
573{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000574 normalize_pair(second, microsecond, 1000000);
575 normalize_pair(minute, second, 60);
576 normalize_pair(hour, minute, 60);
577 normalize_pair(day, hour, 24);
578 return normalize_date(year, month, day);
Tim Peters2a799bf2002-12-16 20:18:38 +0000579}
580
581/* ---------------------------------------------------------------------------
Tim Petersb0c854d2003-05-17 15:57:00 +0000582 * Basic object allocation: tp_alloc implementations. These allocate
583 * Python objects of the right size and type, and do the Python object-
584 * initialization bit. If there's not enough memory, they return NULL after
585 * setting MemoryError. All data members remain uninitialized trash.
586 *
587 * We abuse the tp_alloc "nitems" argument to communicate whether a tzinfo
Tim Peters03eaf8b2003-05-18 02:24:46 +0000588 * member is needed. This is ugly, imprecise, and possibly insecure.
589 * tp_basicsize for the time and datetime types is set to the size of the
590 * struct that has room for the tzinfo member, so subclasses in Python will
591 * allocate enough space for a tzinfo member whether or not one is actually
592 * needed. That's the "ugly and imprecise" parts. The "possibly insecure"
593 * part is that PyType_GenericAlloc() (which subclasses in Python end up
594 * using) just happens today to effectively ignore the nitems argument
595 * when tp_itemsize is 0, which it is for these type objects. If that
596 * changes, perhaps the callers of tp_alloc slots in this file should
597 * be changed to force a 0 nitems argument unless the type being allocated
598 * is a base type implemented in this file (so that tp_alloc is time_alloc
599 * or datetime_alloc below, which know about the nitems abuse).
Tim Petersb0c854d2003-05-17 15:57:00 +0000600 */
601
602static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000603time_alloc(PyTypeObject *type, Py_ssize_t aware)
Tim Petersb0c854d2003-05-17 15:57:00 +0000604{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000605 PyObject *self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000606
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000607 self = (PyObject *)
608 PyObject_MALLOC(aware ?
609 sizeof(PyDateTime_Time) :
610 sizeof(_PyDateTime_BaseTime));
611 if (self == NULL)
612 return (PyObject *)PyErr_NoMemory();
613 PyObject_INIT(self, type);
614 return self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000615}
616
617static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000618datetime_alloc(PyTypeObject *type, Py_ssize_t aware)
Tim Petersb0c854d2003-05-17 15:57:00 +0000619{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000620 PyObject *self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000621
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000622 self = (PyObject *)
623 PyObject_MALLOC(aware ?
624 sizeof(PyDateTime_DateTime) :
625 sizeof(_PyDateTime_BaseDateTime));
626 if (self == NULL)
627 return (PyObject *)PyErr_NoMemory();
628 PyObject_INIT(self, type);
629 return self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000630}
631
632/* ---------------------------------------------------------------------------
633 * Helpers for setting object fields. These work on pointers to the
634 * appropriate base class.
635 */
636
637/* For date and datetime. */
638static void
639set_date_fields(PyDateTime_Date *self, int y, int m, int d)
640{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000641 self->hashcode = -1;
642 SET_YEAR(self, y);
643 SET_MONTH(self, m);
644 SET_DAY(self, d);
Tim Petersb0c854d2003-05-17 15:57:00 +0000645}
646
647/* ---------------------------------------------------------------------------
648 * Create various objects, mostly without range checking.
649 */
650
651/* Create a date instance with no range checking. */
652static PyObject *
653new_date_ex(int year, int month, int day, PyTypeObject *type)
654{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000655 PyDateTime_Date *self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000656
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000657 self = (PyDateTime_Date *) (type->tp_alloc(type, 0));
658 if (self != NULL)
659 set_date_fields(self, year, month, day);
660 return (PyObject *) self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000661}
662
663#define new_date(year, month, day) \
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000664 new_date_ex(year, month, day, &PyDateTime_DateType)
Tim Petersb0c854d2003-05-17 15:57:00 +0000665
666/* Create a datetime instance with no range checking. */
667static PyObject *
668new_datetime_ex(int year, int month, int day, int hour, int minute,
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000669 int second, int usecond, PyObject *tzinfo, PyTypeObject *type)
Tim Petersb0c854d2003-05-17 15:57:00 +0000670{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000671 PyDateTime_DateTime *self;
672 char aware = tzinfo != Py_None;
Tim Petersb0c854d2003-05-17 15:57:00 +0000673
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000674 self = (PyDateTime_DateTime *) (type->tp_alloc(type, aware));
675 if (self != NULL) {
676 self->hastzinfo = aware;
677 set_date_fields((PyDateTime_Date *)self, year, month, day);
678 DATE_SET_HOUR(self, hour);
679 DATE_SET_MINUTE(self, minute);
680 DATE_SET_SECOND(self, second);
681 DATE_SET_MICROSECOND(self, usecond);
682 if (aware) {
683 Py_INCREF(tzinfo);
684 self->tzinfo = tzinfo;
685 }
686 }
687 return (PyObject *)self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000688}
689
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000690#define new_datetime(y, m, d, hh, mm, ss, us, tzinfo) \
691 new_datetime_ex(y, m, d, hh, mm, ss, us, tzinfo, \
692 &PyDateTime_DateTimeType)
Tim Petersb0c854d2003-05-17 15:57:00 +0000693
694/* Create a time instance with no range checking. */
695static PyObject *
696new_time_ex(int hour, int minute, int second, int usecond,
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000697 PyObject *tzinfo, PyTypeObject *type)
Tim Petersb0c854d2003-05-17 15:57:00 +0000698{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000699 PyDateTime_Time *self;
700 char aware = tzinfo != Py_None;
Tim Petersb0c854d2003-05-17 15:57:00 +0000701
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000702 self = (PyDateTime_Time *) (type->tp_alloc(type, aware));
703 if (self != NULL) {
704 self->hastzinfo = aware;
705 self->hashcode = -1;
706 TIME_SET_HOUR(self, hour);
707 TIME_SET_MINUTE(self, minute);
708 TIME_SET_SECOND(self, second);
709 TIME_SET_MICROSECOND(self, usecond);
710 if (aware) {
711 Py_INCREF(tzinfo);
712 self->tzinfo = tzinfo;
713 }
714 }
715 return (PyObject *)self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000716}
717
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000718#define new_time(hh, mm, ss, us, tzinfo) \
719 new_time_ex(hh, mm, ss, us, tzinfo, &PyDateTime_TimeType)
Tim Petersb0c854d2003-05-17 15:57:00 +0000720
721/* Create a timedelta instance. Normalize the members iff normalize is
722 * true. Passing false is a speed optimization, if you know for sure
723 * that seconds and microseconds are already in their proper ranges. In any
724 * case, raises OverflowError and returns NULL if the normalized days is out
725 * of range).
726 */
727static PyObject *
728new_delta_ex(int days, int seconds, int microseconds, int normalize,
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000729 PyTypeObject *type)
Tim Petersb0c854d2003-05-17 15:57:00 +0000730{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000731 PyDateTime_Delta *self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000732
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000733 if (normalize)
734 normalize_d_s_us(&days, &seconds, &microseconds);
735 assert(0 <= seconds && seconds < 24*3600);
736 assert(0 <= microseconds && microseconds < 1000000);
Tim Petersb0c854d2003-05-17 15:57:00 +0000737
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000738 if (check_delta_day_range(days) < 0)
739 return NULL;
Tim Petersb0c854d2003-05-17 15:57:00 +0000740
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000741 self = (PyDateTime_Delta *) (type->tp_alloc(type, 0));
742 if (self != NULL) {
743 self->hashcode = -1;
744 SET_TD_DAYS(self, days);
745 SET_TD_SECONDS(self, seconds);
746 SET_TD_MICROSECONDS(self, microseconds);
747 }
748 return (PyObject *) self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000749}
750
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000751#define new_delta(d, s, us, normalize) \
752 new_delta_ex(d, s, us, normalize, &PyDateTime_DeltaType)
Tim Petersb0c854d2003-05-17 15:57:00 +0000753
754/* ---------------------------------------------------------------------------
Tim Peters2a799bf2002-12-16 20:18:38 +0000755 * tzinfo helpers.
756 */
757
Tim Peters855fe882002-12-22 03:43:39 +0000758/* Ensure that p is None or of a tzinfo subclass. Return 0 if OK; if not
759 * raise TypeError and return -1.
760 */
761static int
762check_tzinfo_subclass(PyObject *p)
763{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000764 if (p == Py_None || PyTZInfo_Check(p))
765 return 0;
766 PyErr_Format(PyExc_TypeError,
767 "tzinfo argument must be None or of a tzinfo subclass, "
768 "not type '%s'",
769 Py_TYPE(p)->tp_name);
770 return -1;
Tim Peters855fe882002-12-22 03:43:39 +0000771}
772
Tim Petersbad8ff02002-12-30 20:52:32 +0000773/* Return tzinfo.methname(tzinfoarg), without any checking of results.
Tim Peters855fe882002-12-22 03:43:39 +0000774 * If tzinfo is None, returns None.
775 */
776static PyObject *
Tim Petersbad8ff02002-12-30 20:52:32 +0000777call_tzinfo_method(PyObject *tzinfo, char *methname, PyObject *tzinfoarg)
Tim Peters855fe882002-12-22 03:43:39 +0000778{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000779 PyObject *result;
Tim Peters855fe882002-12-22 03:43:39 +0000780
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000781 assert(tzinfo && methname && tzinfoarg);
782 assert(check_tzinfo_subclass(tzinfo) >= 0);
783 if (tzinfo == Py_None) {
784 result = Py_None;
785 Py_INCREF(result);
786 }
787 else
788 result = PyObject_CallMethod(tzinfo, methname, "O", tzinfoarg);
789 return result;
Tim Peters855fe882002-12-22 03:43:39 +0000790}
791
Tim Peters2a799bf2002-12-16 20:18:38 +0000792/* If self has a tzinfo member, return a BORROWED reference to it. Else
793 * return NULL, which is NOT AN ERROR. There are no error returns here,
794 * and the caller must not decref the result.
795 */
796static PyObject *
797get_tzinfo_member(PyObject *self)
798{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000799 PyObject *tzinfo = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +0000800
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000801 if (PyDateTime_Check(self) && HASTZINFO(self))
802 tzinfo = ((PyDateTime_DateTime *)self)->tzinfo;
803 else if (PyTime_Check(self) && HASTZINFO(self))
804 tzinfo = ((PyDateTime_Time *)self)->tzinfo;
Tim Peters2a799bf2002-12-16 20:18:38 +0000805
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000806 return tzinfo;
Tim Peters2a799bf2002-12-16 20:18:38 +0000807}
808
Tim Petersbad8ff02002-12-30 20:52:32 +0000809/* Call getattr(tzinfo, name)(tzinfoarg), and extract an int from the
Tim Peters2a799bf2002-12-16 20:18:38 +0000810 * result. tzinfo must be an instance of the tzinfo class. If the method
811 * returns None, this returns 0 and sets *none to 1. If the method doesn't
Tim Peters397301e2003-01-02 21:28:08 +0000812 * return None or timedelta, TypeError is raised and this returns -1. If it
813 * returnsa timedelta and the value is out of range or isn't a whole number
814 * of minutes, ValueError is raised and this returns -1.
Tim Peters2a799bf2002-12-16 20:18:38 +0000815 * Else *none is set to 0 and the integer method result is returned.
816 */
817static int
818call_utc_tzinfo_method(PyObject *tzinfo, char *name, PyObject *tzinfoarg,
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000819 int *none)
Tim Peters2a799bf2002-12-16 20:18:38 +0000820{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000821 PyObject *u;
822 int result = -1;
Tim Peters2a799bf2002-12-16 20:18:38 +0000823
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000824 assert(tzinfo != NULL);
825 assert(PyTZInfo_Check(tzinfo));
826 assert(tzinfoarg != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +0000827
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000828 *none = 0;
829 u = call_tzinfo_method(tzinfo, name, tzinfoarg);
830 if (u == NULL)
831 return -1;
Tim Peters2a799bf2002-12-16 20:18:38 +0000832
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000833 else if (u == Py_None) {
834 result = 0;
835 *none = 1;
836 }
837 else if (PyDelta_Check(u)) {
838 const int days = GET_TD_DAYS(u);
839 if (days < -1 || days > 0)
840 result = 24*60; /* trigger ValueError below */
841 else {
842 /* next line can't overflow because we know days
843 * is -1 or 0 now
844 */
845 int ss = days * 24 * 3600 + GET_TD_SECONDS(u);
846 result = divmod(ss, 60, &ss);
847 if (ss || GET_TD_MICROSECONDS(u)) {
848 PyErr_Format(PyExc_ValueError,
849 "tzinfo.%s() must return a "
850 "whole number of minutes",
851 name);
852 result = -1;
853 }
854 }
855 }
856 else {
857 PyErr_Format(PyExc_TypeError,
858 "tzinfo.%s() must return None or "
859 "timedelta, not '%s'",
860 name, Py_TYPE(u)->tp_name);
861 }
Tim Peters2a799bf2002-12-16 20:18:38 +0000862
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000863 Py_DECREF(u);
864 if (result < -1439 || result > 1439) {
865 PyErr_Format(PyExc_ValueError,
866 "tzinfo.%s() returned %d; must be in "
867 "-1439 .. 1439",
868 name, result);
869 result = -1;
870 }
871 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +0000872}
873
874/* Call tzinfo.utcoffset(tzinfoarg), and extract an integer from the
875 * result. tzinfo must be an instance of the tzinfo class. If utcoffset()
876 * returns None, call_utcoffset returns 0 and sets *none to 1. If uctoffset()
Tim Peters397301e2003-01-02 21:28:08 +0000877 * doesn't return None or timedelta, TypeError is raised and this returns -1.
878 * If utcoffset() returns an invalid timedelta (out of range, or not a whole
879 * # of minutes), ValueError is raised and this returns -1. Else *none is
880 * set to 0 and the offset is returned (as int # of minutes east of UTC).
Tim Peters2a799bf2002-12-16 20:18:38 +0000881 */
882static int
883call_utcoffset(PyObject *tzinfo, PyObject *tzinfoarg, int *none)
884{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000885 return call_utc_tzinfo_method(tzinfo, "utcoffset", tzinfoarg, none);
Tim Peters2a799bf2002-12-16 20:18:38 +0000886}
887
Tim Petersbad8ff02002-12-30 20:52:32 +0000888/* Call tzinfo.name(tzinfoarg), and return the offset as a timedelta or None.
889 */
Tim Peters855fe882002-12-22 03:43:39 +0000890static PyObject *
Tim Petersbad8ff02002-12-30 20:52:32 +0000891offset_as_timedelta(PyObject *tzinfo, char *name, PyObject *tzinfoarg) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000892 PyObject *result;
Tim Peters855fe882002-12-22 03:43:39 +0000893
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000894 assert(tzinfo && name && tzinfoarg);
895 if (tzinfo == Py_None) {
896 result = Py_None;
897 Py_INCREF(result);
898 }
899 else {
900 int none;
901 int offset = call_utc_tzinfo_method(tzinfo, name, tzinfoarg,
902 &none);
903 if (offset < 0 && PyErr_Occurred())
904 return NULL;
905 if (none) {
906 result = Py_None;
907 Py_INCREF(result);
908 }
909 else
910 result = new_delta(0, offset * 60, 0, 1);
911 }
912 return result;
Tim Peters855fe882002-12-22 03:43:39 +0000913}
914
Tim Peters2a799bf2002-12-16 20:18:38 +0000915/* Call tzinfo.dst(tzinfoarg), and extract an integer from the
916 * result. tzinfo must be an instance of the tzinfo class. If dst()
917 * returns None, call_dst returns 0 and sets *none to 1. If dst()
Tim Peters397301e2003-01-02 21:28:08 +0000918 & doesn't return None or timedelta, TypeError is raised and this
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000919 * returns -1. If dst() returns an invalid timedelta for a UTC offset,
Tim Peters397301e2003-01-02 21:28:08 +0000920 * ValueError is raised and this returns -1. Else *none is set to 0 and
921 * the offset is returned (as an int # of minutes east of UTC).
Tim Peters2a799bf2002-12-16 20:18:38 +0000922 */
923static int
924call_dst(PyObject *tzinfo, PyObject *tzinfoarg, int *none)
925{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000926 return call_utc_tzinfo_method(tzinfo, "dst", tzinfoarg, none);
Tim Peters2a799bf2002-12-16 20:18:38 +0000927}
928
Tim Petersbad8ff02002-12-30 20:52:32 +0000929/* Call tzinfo.tzname(tzinfoarg), and return the result. tzinfo must be
Tim Peters855fe882002-12-22 03:43:39 +0000930 * an instance of the tzinfo class or None. If tzinfo isn't None, and
Tim Petersbad8ff02002-12-30 20:52:32 +0000931 * tzname() doesn't return None or a string, TypeError is raised and this
Tim Peters855fe882002-12-22 03:43:39 +0000932 * returns NULL.
Tim Peters2a799bf2002-12-16 20:18:38 +0000933 */
934static PyObject *
Tim Petersbad8ff02002-12-30 20:52:32 +0000935call_tzname(PyObject *tzinfo, PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +0000936{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000937 PyObject *result;
Tim Peters2a799bf2002-12-16 20:18:38 +0000938
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000939 assert(tzinfo != NULL);
940 assert(check_tzinfo_subclass(tzinfo) >= 0);
941 assert(tzinfoarg != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +0000942
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000943 if (tzinfo == Py_None) {
944 result = Py_None;
945 Py_INCREF(result);
946 }
947 else
948 result = PyObject_CallMethod(tzinfo, "tzname", "O", tzinfoarg);
Tim Peters855fe882002-12-22 03:43:39 +0000949
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000950 if (result != NULL && result != Py_None && ! PyString_Check(result)) {
951 PyErr_Format(PyExc_TypeError, "tzinfo.tzname() must "
952 "return None or a string, not '%s'",
953 Py_TYPE(result)->tp_name);
954 Py_DECREF(result);
955 result = NULL;
956 }
957 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +0000958}
959
960typedef enum {
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000961 /* an exception has been set; the caller should pass it on */
962 OFFSET_ERROR,
Tim Peters2a799bf2002-12-16 20:18:38 +0000963
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000964 /* type isn't date, datetime, or time subclass */
965 OFFSET_UNKNOWN,
Tim Peters2a799bf2002-12-16 20:18:38 +0000966
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000967 /* date,
968 * datetime with !hastzinfo
969 * datetime with None tzinfo,
970 * datetime where utcoffset() returns None
971 * time with !hastzinfo
972 * time with None tzinfo,
973 * time where utcoffset() returns None
974 */
975 OFFSET_NAIVE,
Tim Peters2a799bf2002-12-16 20:18:38 +0000976
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000977 /* time or datetime where utcoffset() doesn't return None */
978 OFFSET_AWARE
Tim Peters2a799bf2002-12-16 20:18:38 +0000979} naivety;
980
Tim Peters14b69412002-12-22 18:10:22 +0000981/* Classify an object as to whether it's naive or offset-aware. See
Tim Peters2a799bf2002-12-16 20:18:38 +0000982 * the "naivety" typedef for details. If the type is aware, *offset is set
983 * to minutes east of UTC (as returned by the tzinfo.utcoffset() method).
Tim Peters14b69412002-12-22 18:10:22 +0000984 * If the type is offset-naive (or unknown, or error), *offset is set to 0.
Tim Peterse39a80c2002-12-30 21:28:52 +0000985 * tzinfoarg is the argument to pass to the tzinfo.utcoffset() method.
Tim Peters2a799bf2002-12-16 20:18:38 +0000986 */
987static naivety
Tim Peterse39a80c2002-12-30 21:28:52 +0000988classify_utcoffset(PyObject *op, PyObject *tzinfoarg, int *offset)
Tim Peters2a799bf2002-12-16 20:18:38 +0000989{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000990 int none;
991 PyObject *tzinfo;
Tim Peters2a799bf2002-12-16 20:18:38 +0000992
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000993 assert(tzinfoarg != NULL);
994 *offset = 0;
995 tzinfo = get_tzinfo_member(op); /* NULL means no tzinfo, not error */
996 if (tzinfo == Py_None)
997 return OFFSET_NAIVE;
998 if (tzinfo == NULL) {
999 /* note that a datetime passes the PyDate_Check test */
1000 return (PyTime_Check(op) || PyDate_Check(op)) ?
1001 OFFSET_NAIVE : OFFSET_UNKNOWN;
1002 }
1003 *offset = call_utcoffset(tzinfo, tzinfoarg, &none);
1004 if (*offset == -1 && PyErr_Occurred())
1005 return OFFSET_ERROR;
1006 return none ? OFFSET_NAIVE : OFFSET_AWARE;
Tim Peters2a799bf2002-12-16 20:18:38 +00001007}
1008
Tim Peters00237032002-12-27 02:21:51 +00001009/* Classify two objects as to whether they're naive or offset-aware.
1010 * This isn't quite the same as calling classify_utcoffset() twice: for
1011 * binary operations (comparison and subtraction), we generally want to
1012 * ignore the tzinfo members if they're identical. This is by design,
1013 * so that results match "naive" expectations when mixing objects from a
1014 * single timezone. So in that case, this sets both offsets to 0 and
1015 * both naiveties to OFFSET_NAIVE.
1016 * The function returns 0 if everything's OK, and -1 on error.
1017 */
1018static int
1019classify_two_utcoffsets(PyObject *o1, int *offset1, naivety *n1,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001020 PyObject *tzinfoarg1,
1021 PyObject *o2, int *offset2, naivety *n2,
1022 PyObject *tzinfoarg2)
Tim Peters00237032002-12-27 02:21:51 +00001023{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001024 if (get_tzinfo_member(o1) == get_tzinfo_member(o2)) {
1025 *offset1 = *offset2 = 0;
1026 *n1 = *n2 = OFFSET_NAIVE;
1027 }
1028 else {
1029 *n1 = classify_utcoffset(o1, tzinfoarg1, offset1);
1030 if (*n1 == OFFSET_ERROR)
1031 return -1;
1032 *n2 = classify_utcoffset(o2, tzinfoarg2, offset2);
1033 if (*n2 == OFFSET_ERROR)
1034 return -1;
1035 }
1036 return 0;
Tim Peters00237032002-12-27 02:21:51 +00001037}
1038
Tim Peters2a799bf2002-12-16 20:18:38 +00001039/* repr is like "someclass(arg1, arg2)". If tzinfo isn't None,
1040 * stuff
1041 * ", tzinfo=" + repr(tzinfo)
1042 * before the closing ")".
1043 */
1044static PyObject *
1045append_keyword_tzinfo(PyObject *repr, PyObject *tzinfo)
1046{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001047 PyObject *temp;
Tim Peters2a799bf2002-12-16 20:18:38 +00001048
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001049 assert(PyString_Check(repr));
1050 assert(tzinfo);
1051 if (tzinfo == Py_None)
1052 return repr;
1053 /* Get rid of the trailing ')'. */
1054 assert(PyString_AsString(repr)[PyString_Size(repr)-1] == ')');
1055 temp = PyString_FromStringAndSize(PyString_AsString(repr),
1056 PyString_Size(repr) - 1);
1057 Py_DECREF(repr);
1058 if (temp == NULL)
1059 return NULL;
1060 repr = temp;
Tim Peters2a799bf2002-12-16 20:18:38 +00001061
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001062 /* Append ", tzinfo=". */
1063 PyString_ConcatAndDel(&repr, PyString_FromString(", tzinfo="));
Tim Peters2a799bf2002-12-16 20:18:38 +00001064
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001065 /* Append repr(tzinfo). */
1066 PyString_ConcatAndDel(&repr, PyObject_Repr(tzinfo));
Tim Peters2a799bf2002-12-16 20:18:38 +00001067
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001068 /* Add a closing paren. */
1069 PyString_ConcatAndDel(&repr, PyString_FromString(")"));
1070 return repr;
Tim Peters2a799bf2002-12-16 20:18:38 +00001071}
1072
1073/* ---------------------------------------------------------------------------
1074 * String format helpers.
1075 */
1076
1077static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00001078format_ctime(PyDateTime_Date *date, int hours, int minutes, int seconds)
Tim Peters2a799bf2002-12-16 20:18:38 +00001079{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001080 static const char *DayNames[] = {
1081 "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"
1082 };
1083 static const char *MonthNames[] = {
1084 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
1085 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
1086 };
Tim Peters2a799bf2002-12-16 20:18:38 +00001087
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001088 char buffer[128];
1089 int wday = weekday(GET_YEAR(date), GET_MONTH(date), GET_DAY(date));
Tim Peters2a799bf2002-12-16 20:18:38 +00001090
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001091 PyOS_snprintf(buffer, sizeof(buffer), "%s %s %2d %02d:%02d:%02d %04d",
1092 DayNames[wday], MonthNames[GET_MONTH(date) - 1],
1093 GET_DAY(date), hours, minutes, seconds,
1094 GET_YEAR(date));
1095 return PyString_FromString(buffer);
Tim Peters2a799bf2002-12-16 20:18:38 +00001096}
1097
1098/* Add an hours & minutes UTC offset string to buf. buf has no more than
1099 * buflen bytes remaining. The UTC offset is gotten by calling
1100 * tzinfo.uctoffset(tzinfoarg). If that returns None, \0 is stored into
1101 * *buf, and that's all. Else the returned value is checked for sanity (an
1102 * integer in range), and if that's OK it's converted to an hours & minutes
1103 * string of the form
1104 * sign HH sep MM
1105 * Returns 0 if everything is OK. If the return value from utcoffset() is
1106 * bogus, an appropriate exception is set and -1 is returned.
1107 */
1108static int
Tim Peters328fff72002-12-20 01:31:27 +00001109format_utcoffset(char *buf, size_t buflen, const char *sep,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001110 PyObject *tzinfo, PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +00001111{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001112 int offset;
1113 int hours;
1114 int minutes;
1115 char sign;
1116 int none;
Tim Peters2a799bf2002-12-16 20:18:38 +00001117
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001118 assert(buflen >= 1);
Gregory P. Smith9d534572008-06-11 07:41:16 +00001119
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001120 offset = call_utcoffset(tzinfo, tzinfoarg, &none);
1121 if (offset == -1 && PyErr_Occurred())
1122 return -1;
1123 if (none) {
1124 *buf = '\0';
1125 return 0;
1126 }
1127 sign = '+';
1128 if (offset < 0) {
1129 sign = '-';
1130 offset = - offset;
1131 }
1132 hours = divmod(offset, 60, &minutes);
1133 PyOS_snprintf(buf, buflen, "%c%02d%s%02d", sign, hours, sep, minutes);
1134 return 0;
Tim Peters2a799bf2002-12-16 20:18:38 +00001135}
1136
Skip Montanarofc070d22008-03-15 16:04:45 +00001137static PyObject *
1138make_freplacement(PyObject *object)
1139{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001140 char freplacement[64];
1141 if (PyTime_Check(object))
1142 sprintf(freplacement, "%06d", TIME_GET_MICROSECOND(object));
1143 else if (PyDateTime_Check(object))
1144 sprintf(freplacement, "%06d", DATE_GET_MICROSECOND(object));
1145 else
1146 sprintf(freplacement, "%06d", 0);
Skip Montanarofc070d22008-03-15 16:04:45 +00001147
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001148 return PyString_FromStringAndSize(freplacement, strlen(freplacement));
Skip Montanarofc070d22008-03-15 16:04:45 +00001149}
1150
Tim Peters2a799bf2002-12-16 20:18:38 +00001151/* I sure don't want to reproduce the strftime code from the time module,
1152 * so this imports the module and calls it. All the hair is due to
Skip Montanarofc070d22008-03-15 16:04:45 +00001153 * giving special meanings to the %z, %Z and %f format codes via a
1154 * preprocessing step on the format string.
Tim Petersbad8ff02002-12-30 20:52:32 +00001155 * tzinfoarg is the argument to pass to the object's tzinfo method, if
1156 * needed.
Tim Peters2a799bf2002-12-16 20:18:38 +00001157 */
1158static PyObject *
Gregory P. Smith137d8242008-06-02 04:05:52 +00001159wrap_strftime(PyObject *object, const char *format, size_t format_len,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001160 PyObject *timetuple, PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +00001161{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001162 PyObject *result = NULL; /* guilty until proved innocent */
Tim Peters2a799bf2002-12-16 20:18:38 +00001163
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001164 PyObject *zreplacement = NULL; /* py string, replacement for %z */
1165 PyObject *Zreplacement = NULL; /* py string, replacement for %Z */
1166 PyObject *freplacement = NULL; /* py string, replacement for %f */
Tim Peters2a799bf2002-12-16 20:18:38 +00001167
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001168 const char *pin; /* pointer to next char in input format */
1169 char ch; /* next char in input format */
Tim Peters2a799bf2002-12-16 20:18:38 +00001170
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001171 PyObject *newfmt = NULL; /* py string, the output format */
1172 char *pnew; /* pointer to available byte in output format */
1173 size_t totalnew; /* number bytes total in output format buffer,
1174 exclusive of trailing \0 */
1175 size_t usednew; /* number bytes used so far in output format buffer */
Tim Peters2a799bf2002-12-16 20:18:38 +00001176
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001177 const char *ptoappend; /* ptr to string to append to output buffer */
1178 size_t ntoappend; /* # of bytes to append to output buffer */
Tim Peters2a799bf2002-12-16 20:18:38 +00001179
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001180 assert(object && format && timetuple);
Tim Peters2a799bf2002-12-16 20:18:38 +00001181
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001182 /* Give up if the year is before 1900.
1183 * Python strftime() plays games with the year, and different
1184 * games depending on whether envar PYTHON2K is set. This makes
1185 * years before 1900 a nightmare, even if the platform strftime
1186 * supports them (and not all do).
1187 * We could get a lot farther here by avoiding Python's strftime
1188 * wrapper and calling the C strftime() directly, but that isn't
1189 * an option in the Python implementation of this module.
1190 */
1191 {
1192 long year;
1193 PyObject *pyyear = PySequence_GetItem(timetuple, 0);
1194 if (pyyear == NULL) return NULL;
1195 assert(PyInt_Check(pyyear));
1196 year = PyInt_AsLong(pyyear);
1197 Py_DECREF(pyyear);
1198 if (year < 1900) {
1199 PyErr_Format(PyExc_ValueError, "year=%ld is before "
1200 "1900; the datetime strftime() "
1201 "methods require year >= 1900",
1202 year);
1203 return NULL;
1204 }
1205 }
Tim Petersd6844152002-12-22 20:58:42 +00001206
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001207 /* Scan the input format, looking for %z/%Z/%f escapes, building
1208 * a new format. Since computing the replacements for those codes
1209 * is expensive, don't unless they're actually used.
1210 */
1211 if (format_len > INT_MAX - 1) {
1212 PyErr_NoMemory();
1213 goto Done;
1214 }
Gregory P. Smith9d534572008-06-11 07:41:16 +00001215
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001216 totalnew = format_len + 1; /* realistic if no %z/%Z/%f */
1217 newfmt = PyString_FromStringAndSize(NULL, totalnew);
1218 if (newfmt == NULL) goto Done;
1219 pnew = PyString_AsString(newfmt);
1220 usednew = 0;
Tim Peters2a799bf2002-12-16 20:18:38 +00001221
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001222 pin = format;
1223 while ((ch = *pin++) != '\0') {
1224 if (ch != '%') {
1225 ptoappend = pin - 1;
1226 ntoappend = 1;
1227 }
1228 else if ((ch = *pin++) == '\0') {
1229 /* There's a lone trailing %; doesn't make sense. */
1230 PyErr_SetString(PyExc_ValueError, "strftime format "
1231 "ends with raw %");
1232 goto Done;
1233 }
1234 /* A % has been seen and ch is the character after it. */
1235 else if (ch == 'z') {
1236 if (zreplacement == NULL) {
1237 /* format utcoffset */
1238 char buf[100];
1239 PyObject *tzinfo = get_tzinfo_member(object);
1240 zreplacement = PyString_FromString("");
1241 if (zreplacement == NULL) goto Done;
1242 if (tzinfo != Py_None && tzinfo != NULL) {
1243 assert(tzinfoarg != NULL);
1244 if (format_utcoffset(buf,
1245 sizeof(buf),
1246 "",
1247 tzinfo,
1248 tzinfoarg) < 0)
1249 goto Done;
1250 Py_DECREF(zreplacement);
1251 zreplacement = PyString_FromString(buf);
1252 if (zreplacement == NULL) goto Done;
1253 }
1254 }
1255 assert(zreplacement != NULL);
1256 ptoappend = PyString_AS_STRING(zreplacement);
1257 ntoappend = PyString_GET_SIZE(zreplacement);
1258 }
1259 else if (ch == 'Z') {
1260 /* format tzname */
1261 if (Zreplacement == NULL) {
1262 PyObject *tzinfo = get_tzinfo_member(object);
1263 Zreplacement = PyString_FromString("");
1264 if (Zreplacement == NULL) goto Done;
1265 if (tzinfo != Py_None && tzinfo != NULL) {
1266 PyObject *temp;
1267 assert(tzinfoarg != NULL);
1268 temp = call_tzname(tzinfo, tzinfoarg);
1269 if (temp == NULL) goto Done;
1270 if (temp != Py_None) {
1271 assert(PyString_Check(temp));
1272 /* Since the tzname is getting
1273 * stuffed into the format, we
1274 * have to double any % signs
1275 * so that strftime doesn't
1276 * treat them as format codes.
1277 */
1278 Py_DECREF(Zreplacement);
1279 Zreplacement = PyObject_CallMethod(
1280 temp, "replace",
1281 "ss", "%", "%%");
1282 Py_DECREF(temp);
1283 if (Zreplacement == NULL)
1284 goto Done;
1285 if (!PyString_Check(Zreplacement)) {
1286 PyErr_SetString(PyExc_TypeError, "tzname.replace() did not return a string");
1287 goto Done;
1288 }
1289 }
1290 else
1291 Py_DECREF(temp);
1292 }
1293 }
1294 assert(Zreplacement != NULL);
1295 ptoappend = PyString_AS_STRING(Zreplacement);
1296 ntoappend = PyString_GET_SIZE(Zreplacement);
1297 }
1298 else if (ch == 'f') {
1299 /* format microseconds */
1300 if (freplacement == NULL) {
1301 freplacement = make_freplacement(object);
1302 if (freplacement == NULL)
1303 goto Done;
1304 }
1305 assert(freplacement != NULL);
1306 assert(PyString_Check(freplacement));
1307 ptoappend = PyString_AS_STRING(freplacement);
1308 ntoappend = PyString_GET_SIZE(freplacement);
1309 }
1310 else {
1311 /* percent followed by neither z nor Z */
1312 ptoappend = pin - 2;
1313 ntoappend = 2;
1314 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001315
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001316 /* Append the ntoappend chars starting at ptoappend to
1317 * the new format.
1318 */
1319 assert(ptoappend != NULL);
1320 assert(ntoappend >= 0);
1321 if (ntoappend == 0)
1322 continue;
1323 while (usednew + ntoappend > totalnew) {
1324 size_t bigger = totalnew << 1;
1325 if ((bigger >> 1) != totalnew) { /* overflow */
1326 PyErr_NoMemory();
1327 goto Done;
1328 }
1329 if (_PyString_Resize(&newfmt, bigger) < 0)
1330 goto Done;
1331 totalnew = bigger;
1332 pnew = PyString_AsString(newfmt) + usednew;
1333 }
1334 memcpy(pnew, ptoappend, ntoappend);
1335 pnew += ntoappend;
1336 usednew += ntoappend;
1337 assert(usednew <= totalnew);
1338 } /* end while() */
Tim Peters2a799bf2002-12-16 20:18:38 +00001339
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001340 if (_PyString_Resize(&newfmt, usednew) < 0)
1341 goto Done;
1342 {
1343 PyObject *time = PyImport_ImportModuleNoBlock("time");
1344 if (time == NULL)
1345 goto Done;
1346 result = PyObject_CallMethod(time, "strftime", "OO",
1347 newfmt, timetuple);
1348 Py_DECREF(time);
1349 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001350 Done:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001351 Py_XDECREF(freplacement);
1352 Py_XDECREF(zreplacement);
1353 Py_XDECREF(Zreplacement);
1354 Py_XDECREF(newfmt);
1355 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001356}
1357
1358static char *
1359isoformat_date(PyDateTime_Date *dt, char buffer[], int bufflen)
1360{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001361 int x;
1362 x = PyOS_snprintf(buffer, bufflen,
1363 "%04d-%02d-%02d",
1364 GET_YEAR(dt), GET_MONTH(dt), GET_DAY(dt));
1365 assert(bufflen >= x);
1366 return buffer + x;
Tim Peters2a799bf2002-12-16 20:18:38 +00001367}
1368
Amaury Forgeot d'Arc8645a5c2009-12-29 22:03:38 +00001369static char *
Tim Peters2a799bf2002-12-16 20:18:38 +00001370isoformat_time(PyDateTime_DateTime *dt, char buffer[], int bufflen)
1371{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001372 int x;
1373 int us = DATE_GET_MICROSECOND(dt);
Tim Peters2a799bf2002-12-16 20:18:38 +00001374
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001375 x = PyOS_snprintf(buffer, bufflen,
1376 "%02d:%02d:%02d",
1377 DATE_GET_HOUR(dt),
1378 DATE_GET_MINUTE(dt),
1379 DATE_GET_SECOND(dt));
1380 assert(bufflen >= x);
1381 if (us)
1382 x += PyOS_snprintf(buffer + x, bufflen - x, ".%06d", us);
1383 assert(bufflen >= x);
1384 return buffer + x;
Tim Peters2a799bf2002-12-16 20:18:38 +00001385}
1386
1387/* ---------------------------------------------------------------------------
1388 * Wrap functions from the time module. These aren't directly available
1389 * from C. Perhaps they should be.
1390 */
1391
1392/* Call time.time() and return its result (a Python float). */
1393static PyObject *
Guido van Rossumbd43e912002-12-16 20:34:55 +00001394time_time(void)
Tim Peters2a799bf2002-12-16 20:18:38 +00001395{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001396 PyObject *result = NULL;
1397 PyObject *time = PyImport_ImportModuleNoBlock("time");
Tim Peters2a799bf2002-12-16 20:18:38 +00001398
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001399 if (time != NULL) {
1400 result = PyObject_CallMethod(time, "time", "()");
1401 Py_DECREF(time);
1402 }
1403 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001404}
1405
1406/* Build a time.struct_time. The weekday and day number are automatically
1407 * computed from the y,m,d args.
1408 */
1409static PyObject *
1410build_struct_time(int y, int m, int d, int hh, int mm, int ss, int dstflag)
1411{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001412 PyObject *time;
1413 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001414
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001415 time = PyImport_ImportModuleNoBlock("time");
1416 if (time != NULL) {
1417 result = PyObject_CallMethod(time, "struct_time",
1418 "((iiiiiiiii))",
1419 y, m, d,
1420 hh, mm, ss,
1421 weekday(y, m, d),
1422 days_before_month(y, m) + d,
1423 dstflag);
1424 Py_DECREF(time);
1425 }
1426 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001427}
1428
1429/* ---------------------------------------------------------------------------
1430 * Miscellaneous helpers.
1431 */
1432
1433/* For obscure reasons, we need to use tp_richcompare instead of tp_compare.
1434 * The comparisons here all most naturally compute a cmp()-like result.
1435 * This little helper turns that into a bool result for rich comparisons.
1436 */
1437static PyObject *
1438diff_to_bool(int diff, int op)
1439{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001440 PyObject *result;
1441 int istrue;
Tim Peters2a799bf2002-12-16 20:18:38 +00001442
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001443 switch (op) {
1444 case Py_EQ: istrue = diff == 0; break;
1445 case Py_NE: istrue = diff != 0; break;
1446 case Py_LE: istrue = diff <= 0; break;
1447 case Py_GE: istrue = diff >= 0; break;
1448 case Py_LT: istrue = diff < 0; break;
1449 case Py_GT: istrue = diff > 0; break;
1450 default:
1451 assert(! "op unknown");
1452 istrue = 0; /* To shut up compiler */
1453 }
1454 result = istrue ? Py_True : Py_False;
1455 Py_INCREF(result);
1456 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001457}
1458
Tim Peters07534a62003-02-07 22:50:28 +00001459/* Raises a "can't compare" TypeError and returns NULL. */
1460static PyObject *
1461cmperror(PyObject *a, PyObject *b)
1462{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001463 PyErr_Format(PyExc_TypeError,
1464 "can't compare %s to %s",
1465 Py_TYPE(a)->tp_name, Py_TYPE(b)->tp_name);
1466 return NULL;
Tim Peters07534a62003-02-07 22:50:28 +00001467}
1468
Tim Peters2a799bf2002-12-16 20:18:38 +00001469/* ---------------------------------------------------------------------------
Tim Peters2a799bf2002-12-16 20:18:38 +00001470 * Cached Python objects; these are set by the module init function.
1471 */
1472
1473/* Conversion factors. */
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001474static PyObject *us_per_us = NULL; /* 1 */
1475static PyObject *us_per_ms = NULL; /* 1000 */
1476static PyObject *us_per_second = NULL; /* 1000000 */
1477static PyObject *us_per_minute = NULL; /* 1e6 * 60 as Python int */
1478static PyObject *us_per_hour = NULL; /* 1e6 * 3600 as Python long */
1479static PyObject *us_per_day = NULL; /* 1e6 * 3600 * 24 as Python long */
1480static PyObject *us_per_week = NULL; /* 1e6*3600*24*7 as Python long */
Tim Peters2a799bf2002-12-16 20:18:38 +00001481static PyObject *seconds_per_day = NULL; /* 3600*24 as Python int */
1482
Tim Peters2a799bf2002-12-16 20:18:38 +00001483/* ---------------------------------------------------------------------------
1484 * Class implementations.
1485 */
1486
1487/*
1488 * PyDateTime_Delta implementation.
1489 */
1490
1491/* Convert a timedelta to a number of us,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001492 * (24*3600*self.days + self.seconds)*1000000 + self.microseconds
Tim Peters2a799bf2002-12-16 20:18:38 +00001493 * as a Python int or long.
1494 * Doing mixed-radix arithmetic by hand instead is excruciating in C,
1495 * due to ubiquitous overflow possibilities.
1496 */
1497static PyObject *
1498delta_to_microseconds(PyDateTime_Delta *self)
1499{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001500 PyObject *x1 = NULL;
1501 PyObject *x2 = NULL;
1502 PyObject *x3 = NULL;
1503 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001504
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001505 x1 = PyInt_FromLong(GET_TD_DAYS(self));
1506 if (x1 == NULL)
1507 goto Done;
1508 x2 = PyNumber_Multiply(x1, seconds_per_day); /* days in seconds */
1509 if (x2 == NULL)
1510 goto Done;
1511 Py_DECREF(x1);
1512 x1 = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001513
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001514 /* x2 has days in seconds */
1515 x1 = PyInt_FromLong(GET_TD_SECONDS(self)); /* seconds */
1516 if (x1 == NULL)
1517 goto Done;
1518 x3 = PyNumber_Add(x1, x2); /* days and seconds in seconds */
1519 if (x3 == NULL)
1520 goto Done;
1521 Py_DECREF(x1);
1522 Py_DECREF(x2);
1523 x2 = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001524
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001525 /* x3 has days+seconds in seconds */
1526 x1 = PyNumber_Multiply(x3, us_per_second); /* us */
1527 if (x1 == NULL)
1528 goto Done;
1529 Py_DECREF(x3);
1530 x3 = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001531
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001532 /* x1 has days+seconds in us */
1533 x2 = PyInt_FromLong(GET_TD_MICROSECONDS(self));
1534 if (x2 == NULL)
1535 goto Done;
1536 result = PyNumber_Add(x1, x2);
Tim Peters2a799bf2002-12-16 20:18:38 +00001537
1538Done:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001539 Py_XDECREF(x1);
1540 Py_XDECREF(x2);
1541 Py_XDECREF(x3);
1542 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001543}
1544
1545/* Convert a number of us (as a Python int or long) to a timedelta.
1546 */
1547static PyObject *
Tim Petersb0c854d2003-05-17 15:57:00 +00001548microseconds_to_delta_ex(PyObject *pyus, PyTypeObject *type)
Tim Peters2a799bf2002-12-16 20:18:38 +00001549{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001550 int us;
1551 int s;
1552 int d;
1553 long temp;
Tim Peters2a799bf2002-12-16 20:18:38 +00001554
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001555 PyObject *tuple = NULL;
1556 PyObject *num = NULL;
1557 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001558
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001559 tuple = PyNumber_Divmod(pyus, us_per_second);
1560 if (tuple == NULL)
1561 goto Done;
Tim Peters2a799bf2002-12-16 20:18:38 +00001562
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001563 num = PyTuple_GetItem(tuple, 1); /* us */
1564 if (num == NULL)
1565 goto Done;
1566 temp = PyLong_AsLong(num);
1567 num = NULL;
1568 if (temp == -1 && PyErr_Occurred())
1569 goto Done;
1570 assert(0 <= temp && temp < 1000000);
1571 us = (int)temp;
1572 if (us < 0) {
1573 /* The divisor was positive, so this must be an error. */
1574 assert(PyErr_Occurred());
1575 goto Done;
1576 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001577
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001578 num = PyTuple_GetItem(tuple, 0); /* leftover seconds */
1579 if (num == NULL)
1580 goto Done;
1581 Py_INCREF(num);
1582 Py_DECREF(tuple);
Tim Peters2a799bf2002-12-16 20:18:38 +00001583
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001584 tuple = PyNumber_Divmod(num, seconds_per_day);
1585 if (tuple == NULL)
1586 goto Done;
1587 Py_DECREF(num);
Tim Peters2a799bf2002-12-16 20:18:38 +00001588
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001589 num = PyTuple_GetItem(tuple, 1); /* seconds */
1590 if (num == NULL)
1591 goto Done;
1592 temp = PyLong_AsLong(num);
1593 num = NULL;
1594 if (temp == -1 && PyErr_Occurred())
1595 goto Done;
1596 assert(0 <= temp && temp < 24*3600);
1597 s = (int)temp;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001598
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001599 if (s < 0) {
1600 /* The divisor was positive, so this must be an error. */
1601 assert(PyErr_Occurred());
1602 goto Done;
1603 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001604
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001605 num = PyTuple_GetItem(tuple, 0); /* leftover days */
1606 if (num == NULL)
1607 goto Done;
1608 Py_INCREF(num);
1609 temp = PyLong_AsLong(num);
1610 if (temp == -1 && PyErr_Occurred())
1611 goto Done;
1612 d = (int)temp;
1613 if ((long)d != temp) {
1614 PyErr_SetString(PyExc_OverflowError, "normalized days too "
1615 "large to fit in a C int");
1616 goto Done;
1617 }
1618 result = new_delta_ex(d, s, us, 0, type);
Tim Peters2a799bf2002-12-16 20:18:38 +00001619
1620Done:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001621 Py_XDECREF(tuple);
1622 Py_XDECREF(num);
1623 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001624}
1625
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001626#define microseconds_to_delta(pymicros) \
1627 microseconds_to_delta_ex(pymicros, &PyDateTime_DeltaType)
Tim Petersb0c854d2003-05-17 15:57:00 +00001628
Tim Peters2a799bf2002-12-16 20:18:38 +00001629static PyObject *
1630multiply_int_timedelta(PyObject *intobj, PyDateTime_Delta *delta)
1631{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001632 PyObject *pyus_in;
1633 PyObject *pyus_out;
1634 PyObject *result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001635
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001636 pyus_in = delta_to_microseconds(delta);
1637 if (pyus_in == NULL)
1638 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001639
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001640 pyus_out = PyNumber_Multiply(pyus_in, intobj);
1641 Py_DECREF(pyus_in);
1642 if (pyus_out == NULL)
1643 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001644
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001645 result = microseconds_to_delta(pyus_out);
1646 Py_DECREF(pyus_out);
1647 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001648}
1649
1650static PyObject *
1651divide_timedelta_int(PyDateTime_Delta *delta, PyObject *intobj)
1652{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001653 PyObject *pyus_in;
1654 PyObject *pyus_out;
1655 PyObject *result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001656
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001657 pyus_in = delta_to_microseconds(delta);
1658 if (pyus_in == NULL)
1659 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001660
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001661 pyus_out = PyNumber_FloorDivide(pyus_in, intobj);
1662 Py_DECREF(pyus_in);
1663 if (pyus_out == NULL)
1664 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001665
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001666 result = microseconds_to_delta(pyus_out);
1667 Py_DECREF(pyus_out);
1668 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001669}
1670
1671static PyObject *
1672delta_add(PyObject *left, PyObject *right)
1673{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001674 PyObject *result = Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00001675
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001676 if (PyDelta_Check(left) && PyDelta_Check(right)) {
1677 /* delta + delta */
1678 /* The C-level additions can't overflow because of the
1679 * invariant bounds.
1680 */
1681 int days = GET_TD_DAYS(left) + GET_TD_DAYS(right);
1682 int seconds = GET_TD_SECONDS(left) + GET_TD_SECONDS(right);
1683 int microseconds = GET_TD_MICROSECONDS(left) +
1684 GET_TD_MICROSECONDS(right);
1685 result = new_delta(days, seconds, microseconds, 1);
1686 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001687
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001688 if (result == Py_NotImplemented)
1689 Py_INCREF(result);
1690 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001691}
1692
1693static PyObject *
1694delta_negative(PyDateTime_Delta *self)
1695{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001696 return new_delta(-GET_TD_DAYS(self),
1697 -GET_TD_SECONDS(self),
1698 -GET_TD_MICROSECONDS(self),
1699 1);
Tim Peters2a799bf2002-12-16 20:18:38 +00001700}
1701
1702static PyObject *
1703delta_positive(PyDateTime_Delta *self)
1704{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001705 /* Could optimize this (by returning self) if this isn't a
1706 * subclass -- but who uses unary + ? Approximately nobody.
1707 */
1708 return new_delta(GET_TD_DAYS(self),
1709 GET_TD_SECONDS(self),
1710 GET_TD_MICROSECONDS(self),
1711 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00001712}
1713
1714static PyObject *
1715delta_abs(PyDateTime_Delta *self)
1716{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001717 PyObject *result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001718
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001719 assert(GET_TD_MICROSECONDS(self) >= 0);
1720 assert(GET_TD_SECONDS(self) >= 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00001721
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001722 if (GET_TD_DAYS(self) < 0)
1723 result = delta_negative(self);
1724 else
1725 result = delta_positive(self);
Tim Peters2a799bf2002-12-16 20:18:38 +00001726
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001727 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001728}
1729
1730static PyObject *
1731delta_subtract(PyObject *left, PyObject *right)
1732{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001733 PyObject *result = Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00001734
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001735 if (PyDelta_Check(left) && PyDelta_Check(right)) {
1736 /* delta - delta */
1737 PyObject *minus_right = PyNumber_Negative(right);
1738 if (minus_right) {
1739 result = delta_add(left, minus_right);
1740 Py_DECREF(minus_right);
1741 }
1742 else
1743 result = NULL;
1744 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001745
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001746 if (result == Py_NotImplemented)
1747 Py_INCREF(result);
1748 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001749}
1750
1751/* This is more natural as a tp_compare, but doesn't work then: for whatever
1752 * reason, Python's try_3way_compare ignores tp_compare unless
1753 * PyInstance_Check returns true, but these aren't old-style classes.
1754 */
1755static PyObject *
1756delta_richcompare(PyDateTime_Delta *self, PyObject *other, int op)
1757{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001758 int diff = 42; /* nonsense */
Tim Peters2a799bf2002-12-16 20:18:38 +00001759
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001760 if (PyDelta_Check(other)) {
1761 diff = GET_TD_DAYS(self) - GET_TD_DAYS(other);
1762 if (diff == 0) {
1763 diff = GET_TD_SECONDS(self) - GET_TD_SECONDS(other);
1764 if (diff == 0)
1765 diff = GET_TD_MICROSECONDS(self) -
1766 GET_TD_MICROSECONDS(other);
1767 }
1768 }
1769 else if (op == Py_EQ || op == Py_NE)
1770 diff = 1; /* any non-zero value will do */
Tim Peters07534a62003-02-07 22:50:28 +00001771
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001772 else /* stop this from falling back to address comparison */
1773 return cmperror((PyObject *)self, other);
Tim Peters07534a62003-02-07 22:50:28 +00001774
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001775 return diff_to_bool(diff, op);
Tim Peters2a799bf2002-12-16 20:18:38 +00001776}
1777
1778static PyObject *delta_getstate(PyDateTime_Delta *self);
1779
1780static long
1781delta_hash(PyDateTime_Delta *self)
1782{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001783 if (self->hashcode == -1) {
1784 PyObject *temp = delta_getstate(self);
1785 if (temp != NULL) {
1786 self->hashcode = PyObject_Hash(temp);
1787 Py_DECREF(temp);
1788 }
1789 }
1790 return self->hashcode;
Tim Peters2a799bf2002-12-16 20:18:38 +00001791}
1792
1793static PyObject *
1794delta_multiply(PyObject *left, PyObject *right)
1795{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001796 PyObject *result = Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00001797
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001798 if (PyDelta_Check(left)) {
1799 /* delta * ??? */
1800 if (PyInt_Check(right) || PyLong_Check(right))
1801 result = multiply_int_timedelta(right,
1802 (PyDateTime_Delta *) left);
1803 }
1804 else if (PyInt_Check(left) || PyLong_Check(left))
1805 result = multiply_int_timedelta(left,
1806 (PyDateTime_Delta *) right);
Tim Peters2a799bf2002-12-16 20:18:38 +00001807
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001808 if (result == Py_NotImplemented)
1809 Py_INCREF(result);
1810 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001811}
1812
1813static PyObject *
1814delta_divide(PyObject *left, PyObject *right)
1815{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001816 PyObject *result = Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00001817
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001818 if (PyDelta_Check(left)) {
1819 /* delta * ??? */
1820 if (PyInt_Check(right) || PyLong_Check(right))
1821 result = divide_timedelta_int(
1822 (PyDateTime_Delta *)left,
1823 right);
1824 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001825
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001826 if (result == Py_NotImplemented)
1827 Py_INCREF(result);
1828 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001829}
1830
1831/* Fold in the value of the tag ("seconds", "weeks", etc) component of a
1832 * timedelta constructor. sofar is the # of microseconds accounted for
1833 * so far, and there are factor microseconds per current unit, the number
1834 * of which is given by num. num * factor is added to sofar in a
1835 * numerically careful way, and that's the result. Any fractional
1836 * microseconds left over (this can happen if num is a float type) are
1837 * added into *leftover.
1838 * Note that there are many ways this can give an error (NULL) return.
1839 */
1840static PyObject *
1841accum(const char* tag, PyObject *sofar, PyObject *num, PyObject *factor,
1842 double *leftover)
1843{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001844 PyObject *prod;
1845 PyObject *sum;
Tim Peters2a799bf2002-12-16 20:18:38 +00001846
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001847 assert(num != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +00001848
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001849 if (PyInt_Check(num) || PyLong_Check(num)) {
1850 prod = PyNumber_Multiply(num, factor);
1851 if (prod == NULL)
1852 return NULL;
1853 sum = PyNumber_Add(sofar, prod);
1854 Py_DECREF(prod);
1855 return sum;
1856 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001857
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001858 if (PyFloat_Check(num)) {
1859 double dnum;
1860 double fracpart;
1861 double intpart;
1862 PyObject *x;
1863 PyObject *y;
Tim Peters2a799bf2002-12-16 20:18:38 +00001864
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001865 /* The Plan: decompose num into an integer part and a
1866 * fractional part, num = intpart + fracpart.
1867 * Then num * factor ==
1868 * intpart * factor + fracpart * factor
1869 * and the LHS can be computed exactly in long arithmetic.
1870 * The RHS is again broken into an int part and frac part.
1871 * and the frac part is added into *leftover.
1872 */
1873 dnum = PyFloat_AsDouble(num);
1874 if (dnum == -1.0 && PyErr_Occurred())
1875 return NULL;
1876 fracpart = modf(dnum, &intpart);
1877 x = PyLong_FromDouble(intpart);
1878 if (x == NULL)
1879 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001880
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001881 prod = PyNumber_Multiply(x, factor);
1882 Py_DECREF(x);
1883 if (prod == NULL)
1884 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001885
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001886 sum = PyNumber_Add(sofar, prod);
1887 Py_DECREF(prod);
1888 if (sum == NULL)
1889 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001890
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001891 if (fracpart == 0.0)
1892 return sum;
1893 /* So far we've lost no information. Dealing with the
1894 * fractional part requires float arithmetic, and may
1895 * lose a little info.
1896 */
1897 assert(PyInt_Check(factor) || PyLong_Check(factor));
1898 if (PyInt_Check(factor))
1899 dnum = (double)PyInt_AsLong(factor);
1900 else
1901 dnum = PyLong_AsDouble(factor);
Tim Peters2a799bf2002-12-16 20:18:38 +00001902
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001903 dnum *= fracpart;
1904 fracpart = modf(dnum, &intpart);
1905 x = PyLong_FromDouble(intpart);
1906 if (x == NULL) {
1907 Py_DECREF(sum);
1908 return NULL;
1909 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001910
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001911 y = PyNumber_Add(sum, x);
1912 Py_DECREF(sum);
1913 Py_DECREF(x);
1914 *leftover += fracpart;
1915 return y;
1916 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001917
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001918 PyErr_Format(PyExc_TypeError,
1919 "unsupported type for timedelta %s component: %s",
1920 tag, Py_TYPE(num)->tp_name);
1921 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001922}
1923
1924static PyObject *
1925delta_new(PyTypeObject *type, PyObject *args, PyObject *kw)
1926{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001927 PyObject *self = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001928
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001929 /* Argument objects. */
1930 PyObject *day = NULL;
1931 PyObject *second = NULL;
1932 PyObject *us = NULL;
1933 PyObject *ms = NULL;
1934 PyObject *minute = NULL;
1935 PyObject *hour = NULL;
1936 PyObject *week = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001937
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001938 PyObject *x = NULL; /* running sum of microseconds */
1939 PyObject *y = NULL; /* temp sum of microseconds */
1940 double leftover_us = 0.0;
Tim Peters2a799bf2002-12-16 20:18:38 +00001941
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001942 static char *keywords[] = {
1943 "days", "seconds", "microseconds", "milliseconds",
1944 "minutes", "hours", "weeks", NULL
1945 };
Tim Peters2a799bf2002-12-16 20:18:38 +00001946
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001947 if (PyArg_ParseTupleAndKeywords(args, kw, "|OOOOOOO:__new__",
1948 keywords,
1949 &day, &second, &us,
1950 &ms, &minute, &hour, &week) == 0)
1951 goto Done;
Tim Peters2a799bf2002-12-16 20:18:38 +00001952
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001953 x = PyInt_FromLong(0);
1954 if (x == NULL)
1955 goto Done;
Tim Peters2a799bf2002-12-16 20:18:38 +00001956
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001957#define CLEANUP \
1958 Py_DECREF(x); \
1959 x = y; \
1960 if (x == NULL) \
1961 goto Done
Tim Peters2a799bf2002-12-16 20:18:38 +00001962
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001963 if (us) {
1964 y = accum("microseconds", x, us, us_per_us, &leftover_us);
1965 CLEANUP;
1966 }
1967 if (ms) {
1968 y = accum("milliseconds", x, ms, us_per_ms, &leftover_us);
1969 CLEANUP;
1970 }
1971 if (second) {
1972 y = accum("seconds", x, second, us_per_second, &leftover_us);
1973 CLEANUP;
1974 }
1975 if (minute) {
1976 y = accum("minutes", x, minute, us_per_minute, &leftover_us);
1977 CLEANUP;
1978 }
1979 if (hour) {
1980 y = accum("hours", x, hour, us_per_hour, &leftover_us);
1981 CLEANUP;
1982 }
1983 if (day) {
1984 y = accum("days", x, day, us_per_day, &leftover_us);
1985 CLEANUP;
1986 }
1987 if (week) {
1988 y = accum("weeks", x, week, us_per_week, &leftover_us);
1989 CLEANUP;
1990 }
1991 if (leftover_us) {
1992 /* Round to nearest whole # of us, and add into x. */
1993 PyObject *temp = PyLong_FromLong(round_to_long(leftover_us));
1994 if (temp == NULL) {
1995 Py_DECREF(x);
1996 goto Done;
1997 }
1998 y = PyNumber_Add(x, temp);
1999 Py_DECREF(temp);
2000 CLEANUP;
2001 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002002
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002003 self = microseconds_to_delta_ex(x, type);
2004 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00002005Done:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002006 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00002007
2008#undef CLEANUP
2009}
2010
2011static int
2012delta_nonzero(PyDateTime_Delta *self)
2013{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002014 return (GET_TD_DAYS(self) != 0
2015 || GET_TD_SECONDS(self) != 0
2016 || GET_TD_MICROSECONDS(self) != 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00002017}
2018
2019static PyObject *
2020delta_repr(PyDateTime_Delta *self)
2021{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002022 if (GET_TD_MICROSECONDS(self) != 0)
2023 return PyString_FromFormat("%s(%d, %d, %d)",
2024 Py_TYPE(self)->tp_name,
2025 GET_TD_DAYS(self),
2026 GET_TD_SECONDS(self),
2027 GET_TD_MICROSECONDS(self));
2028 if (GET_TD_SECONDS(self) != 0)
2029 return PyString_FromFormat("%s(%d, %d)",
2030 Py_TYPE(self)->tp_name,
2031 GET_TD_DAYS(self),
2032 GET_TD_SECONDS(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002033
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002034 return PyString_FromFormat("%s(%d)",
2035 Py_TYPE(self)->tp_name,
2036 GET_TD_DAYS(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002037}
2038
2039static PyObject *
2040delta_str(PyDateTime_Delta *self)
2041{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002042 int days = GET_TD_DAYS(self);
2043 int seconds = GET_TD_SECONDS(self);
2044 int us = GET_TD_MICROSECONDS(self);
2045 int hours;
2046 int minutes;
2047 char buf[100];
2048 char *pbuf = buf;
2049 size_t buflen = sizeof(buf);
2050 int n;
Tim Peters2a799bf2002-12-16 20:18:38 +00002051
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002052 minutes = divmod(seconds, 60, &seconds);
2053 hours = divmod(minutes, 60, &minutes);
Tim Peters2a799bf2002-12-16 20:18:38 +00002054
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002055 if (days) {
2056 n = PyOS_snprintf(pbuf, buflen, "%d day%s, ", days,
2057 (days == 1 || days == -1) ? "" : "s");
2058 if (n < 0 || (size_t)n >= buflen)
2059 goto Fail;
2060 pbuf += n;
2061 buflen -= (size_t)n;
2062 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002063
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002064 n = PyOS_snprintf(pbuf, buflen, "%d:%02d:%02d",
2065 hours, minutes, seconds);
2066 if (n < 0 || (size_t)n >= buflen)
2067 goto Fail;
2068 pbuf += n;
2069 buflen -= (size_t)n;
Tim Peters2a799bf2002-12-16 20:18:38 +00002070
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002071 if (us) {
2072 n = PyOS_snprintf(pbuf, buflen, ".%06d", us);
2073 if (n < 0 || (size_t)n >= buflen)
2074 goto Fail;
2075 pbuf += n;
2076 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002077
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002078 return PyString_FromStringAndSize(buf, pbuf - buf);
Tim Petersba873472002-12-18 20:19:21 +00002079
2080 Fail:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002081 PyErr_SetString(PyExc_SystemError, "goofy result from PyOS_snprintf");
2082 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002083}
2084
Tim Peters371935f2003-02-01 01:52:50 +00002085/* Pickle support, a simple use of __reduce__. */
2086
Tim Petersb57f8f02003-02-01 02:54:15 +00002087/* __getstate__ isn't exposed */
Tim Peters2a799bf2002-12-16 20:18:38 +00002088static PyObject *
2089delta_getstate(PyDateTime_Delta *self)
2090{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002091 return Py_BuildValue("iii", GET_TD_DAYS(self),
2092 GET_TD_SECONDS(self),
2093 GET_TD_MICROSECONDS(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002094}
2095
Tim Peters2a799bf2002-12-16 20:18:38 +00002096static PyObject *
Antoine Pitroubcfaf802009-11-25 22:59:36 +00002097delta_total_seconds(PyObject *self)
2098{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002099 PyObject *total_seconds;
2100 PyObject *total_microseconds;
2101 PyObject *one_million;
Mark Dickinson7000e9e2010-05-09 09:30:06 +00002102
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002103 total_microseconds = delta_to_microseconds((PyDateTime_Delta *)self);
2104 if (total_microseconds == NULL)
2105 return NULL;
Mark Dickinson7000e9e2010-05-09 09:30:06 +00002106
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002107 one_million = PyLong_FromLong(1000000L);
2108 if (one_million == NULL) {
2109 Py_DECREF(total_microseconds);
2110 return NULL;
2111 }
Mark Dickinson7000e9e2010-05-09 09:30:06 +00002112
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002113 total_seconds = PyNumber_TrueDivide(total_microseconds, one_million);
Mark Dickinson7000e9e2010-05-09 09:30:06 +00002114
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002115 Py_DECREF(total_microseconds);
2116 Py_DECREF(one_million);
2117 return total_seconds;
Antoine Pitroubcfaf802009-11-25 22:59:36 +00002118}
2119
2120static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002121delta_reduce(PyDateTime_Delta* self)
2122{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002123 return Py_BuildValue("ON", Py_TYPE(self), delta_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002124}
2125
2126#define OFFSET(field) offsetof(PyDateTime_Delta, field)
2127
2128static PyMemberDef delta_members[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002129
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002130 {"days", T_INT, OFFSET(days), READONLY,
2131 PyDoc_STR("Number of days.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002132
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002133 {"seconds", T_INT, OFFSET(seconds), READONLY,
2134 PyDoc_STR("Number of seconds (>= 0 and less than 1 day).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002135
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002136 {"microseconds", T_INT, OFFSET(microseconds), READONLY,
2137 PyDoc_STR("Number of microseconds (>= 0 and less than 1 second).")},
2138 {NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00002139};
2140
2141static PyMethodDef delta_methods[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002142 {"total_seconds", (PyCFunction)delta_total_seconds, METH_NOARGS,
2143 PyDoc_STR("Total seconds in the duration.")},
Antoine Pitroubcfaf802009-11-25 22:59:36 +00002144
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002145 {"__reduce__", (PyCFunction)delta_reduce, METH_NOARGS,
2146 PyDoc_STR("__reduce__() -> (cls, state)")},
Guido van Rossum177e41a2003-01-30 22:06:23 +00002147
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002148 {NULL, NULL},
Tim Peters2a799bf2002-12-16 20:18:38 +00002149};
2150
2151static char delta_doc[] =
2152PyDoc_STR("Difference between two datetime values.");
2153
2154static PyNumberMethods delta_as_number = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002155 delta_add, /* nb_add */
2156 delta_subtract, /* nb_subtract */
2157 delta_multiply, /* nb_multiply */
2158 delta_divide, /* nb_divide */
2159 0, /* nb_remainder */
2160 0, /* nb_divmod */
2161 0, /* nb_power */
2162 (unaryfunc)delta_negative, /* nb_negative */
2163 (unaryfunc)delta_positive, /* nb_positive */
2164 (unaryfunc)delta_abs, /* nb_absolute */
2165 (inquiry)delta_nonzero, /* nb_nonzero */
2166 0, /*nb_invert*/
2167 0, /*nb_lshift*/
2168 0, /*nb_rshift*/
2169 0, /*nb_and*/
2170 0, /*nb_xor*/
2171 0, /*nb_or*/
2172 0, /*nb_coerce*/
2173 0, /*nb_int*/
2174 0, /*nb_long*/
2175 0, /*nb_float*/
2176 0, /*nb_oct*/
2177 0, /*nb_hex*/
2178 0, /*nb_inplace_add*/
2179 0, /*nb_inplace_subtract*/
2180 0, /*nb_inplace_multiply*/
2181 0, /*nb_inplace_divide*/
2182 0, /*nb_inplace_remainder*/
2183 0, /*nb_inplace_power*/
2184 0, /*nb_inplace_lshift*/
2185 0, /*nb_inplace_rshift*/
2186 0, /*nb_inplace_and*/
2187 0, /*nb_inplace_xor*/
2188 0, /*nb_inplace_or*/
2189 delta_divide, /* nb_floor_divide */
2190 0, /* nb_true_divide */
2191 0, /* nb_inplace_floor_divide */
2192 0, /* nb_inplace_true_divide */
Tim Peters2a799bf2002-12-16 20:18:38 +00002193};
2194
2195static PyTypeObject PyDateTime_DeltaType = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002196 PyVarObject_HEAD_INIT(NULL, 0)
2197 "datetime.timedelta", /* tp_name */
2198 sizeof(PyDateTime_Delta), /* tp_basicsize */
2199 0, /* tp_itemsize */
2200 0, /* tp_dealloc */
2201 0, /* tp_print */
2202 0, /* tp_getattr */
2203 0, /* tp_setattr */
2204 0, /* tp_compare */
2205 (reprfunc)delta_repr, /* tp_repr */
2206 &delta_as_number, /* tp_as_number */
2207 0, /* tp_as_sequence */
2208 0, /* tp_as_mapping */
2209 (hashfunc)delta_hash, /* tp_hash */
2210 0, /* tp_call */
2211 (reprfunc)delta_str, /* tp_str */
2212 PyObject_GenericGetAttr, /* tp_getattro */
2213 0, /* tp_setattro */
2214 0, /* tp_as_buffer */
2215 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
2216 Py_TPFLAGS_BASETYPE, /* tp_flags */
2217 delta_doc, /* tp_doc */
2218 0, /* tp_traverse */
2219 0, /* tp_clear */
2220 (richcmpfunc)delta_richcompare, /* tp_richcompare */
2221 0, /* tp_weaklistoffset */
2222 0, /* tp_iter */
2223 0, /* tp_iternext */
2224 delta_methods, /* tp_methods */
2225 delta_members, /* tp_members */
2226 0, /* tp_getset */
2227 0, /* tp_base */
2228 0, /* tp_dict */
2229 0, /* tp_descr_get */
2230 0, /* tp_descr_set */
2231 0, /* tp_dictoffset */
2232 0, /* tp_init */
2233 0, /* tp_alloc */
2234 delta_new, /* tp_new */
2235 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00002236};
2237
2238/*
2239 * PyDateTime_Date implementation.
2240 */
2241
2242/* Accessor properties. */
2243
2244static PyObject *
2245date_year(PyDateTime_Date *self, void *unused)
2246{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002247 return PyInt_FromLong(GET_YEAR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002248}
2249
2250static PyObject *
2251date_month(PyDateTime_Date *self, void *unused)
2252{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002253 return PyInt_FromLong(GET_MONTH(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002254}
2255
2256static PyObject *
2257date_day(PyDateTime_Date *self, void *unused)
2258{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002259 return PyInt_FromLong(GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002260}
2261
2262static PyGetSetDef date_getset[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002263 {"year", (getter)date_year},
2264 {"month", (getter)date_month},
2265 {"day", (getter)date_day},
2266 {NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00002267};
2268
2269/* Constructors. */
2270
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00002271static char *date_kws[] = {"year", "month", "day", NULL};
Tim Peters12bf3392002-12-24 05:41:27 +00002272
Tim Peters2a799bf2002-12-16 20:18:38 +00002273static PyObject *
2274date_new(PyTypeObject *type, PyObject *args, PyObject *kw)
2275{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002276 PyObject *self = NULL;
2277 PyObject *state;
2278 int year;
2279 int month;
2280 int day;
Tim Peters2a799bf2002-12-16 20:18:38 +00002281
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002282 /* Check for invocation from pickle with __getstate__ state */
2283 if (PyTuple_GET_SIZE(args) == 1 &&
2284 PyString_Check(state = PyTuple_GET_ITEM(args, 0)) &&
2285 PyString_GET_SIZE(state) == _PyDateTime_DATE_DATASIZE &&
2286 MONTH_IS_SANE(PyString_AS_STRING(state)[2]))
2287 {
2288 PyDateTime_Date *me;
Tim Peters70533e22003-02-01 04:40:04 +00002289
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002290 me = (PyDateTime_Date *) (type->tp_alloc(type, 0));
2291 if (me != NULL) {
2292 char *pdata = PyString_AS_STRING(state);
2293 memcpy(me->data, pdata, _PyDateTime_DATE_DATASIZE);
2294 me->hashcode = -1;
2295 }
2296 return (PyObject *)me;
2297 }
Guido van Rossum177e41a2003-01-30 22:06:23 +00002298
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002299 if (PyArg_ParseTupleAndKeywords(args, kw, "iii", date_kws,
2300 &year, &month, &day)) {
2301 if (check_date_args(year, month, day) < 0)
2302 return NULL;
2303 self = new_date_ex(year, month, day, type);
2304 }
2305 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00002306}
2307
2308/* Return new date from localtime(t). */
2309static PyObject *
Tim Peters1b6f7a92004-06-20 02:50:16 +00002310date_local_from_time_t(PyObject *cls, double ts)
Tim Peters2a799bf2002-12-16 20:18:38 +00002311{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002312 struct tm *tm;
2313 time_t t;
2314 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002315
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002316 t = _PyTime_DoubleToTimet(ts);
2317 if (t == (time_t)-1 && PyErr_Occurred())
2318 return NULL;
2319 tm = localtime(&t);
2320 if (tm)
2321 result = PyObject_CallFunction(cls, "iii",
2322 tm->tm_year + 1900,
2323 tm->tm_mon + 1,
2324 tm->tm_mday);
2325 else
2326 PyErr_SetString(PyExc_ValueError,
2327 "timestamp out of range for "
2328 "platform localtime() function");
2329 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002330}
2331
2332/* Return new date from current time.
2333 * We say this is equivalent to fromtimestamp(time.time()), and the
2334 * only way to be sure of that is to *call* time.time(). That's not
2335 * generally the same as calling C's time.
2336 */
2337static PyObject *
2338date_today(PyObject *cls, PyObject *dummy)
2339{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002340 PyObject *time;
2341 PyObject *result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002342
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002343 time = time_time();
2344 if (time == NULL)
2345 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002346
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002347 /* Note well: today() is a class method, so this may not call
2348 * date.fromtimestamp. For example, it may call
2349 * datetime.fromtimestamp. That's why we need all the accuracy
2350 * time.time() delivers; if someone were gonzo about optimization,
2351 * date.today() could get away with plain C time().
2352 */
2353 result = PyObject_CallMethod(cls, "fromtimestamp", "O", time);
2354 Py_DECREF(time);
2355 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002356}
2357
2358/* Return new date from given timestamp (Python timestamp -- a double). */
2359static PyObject *
2360date_fromtimestamp(PyObject *cls, PyObject *args)
2361{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002362 double timestamp;
2363 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002364
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002365 if (PyArg_ParseTuple(args, "d:fromtimestamp", &timestamp))
2366 result = date_local_from_time_t(cls, timestamp);
2367 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002368}
2369
2370/* Return new date from proleptic Gregorian ordinal. Raises ValueError if
2371 * the ordinal is out of range.
2372 */
2373static PyObject *
2374date_fromordinal(PyObject *cls, PyObject *args)
2375{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002376 PyObject *result = NULL;
2377 int ordinal;
Tim Peters2a799bf2002-12-16 20:18:38 +00002378
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002379 if (PyArg_ParseTuple(args, "i:fromordinal", &ordinal)) {
2380 int year;
2381 int month;
2382 int day;
Tim Peters2a799bf2002-12-16 20:18:38 +00002383
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002384 if (ordinal < 1)
2385 PyErr_SetString(PyExc_ValueError, "ordinal must be "
2386 ">= 1");
2387 else {
2388 ord_to_ymd(ordinal, &year, &month, &day);
2389 result = PyObject_CallFunction(cls, "iii",
2390 year, month, day);
2391 }
2392 }
2393 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002394}
2395
2396/*
2397 * Date arithmetic.
2398 */
2399
2400/* date + timedelta -> date. If arg negate is true, subtract the timedelta
2401 * instead.
2402 */
2403static PyObject *
2404add_date_timedelta(PyDateTime_Date *date, PyDateTime_Delta *delta, int negate)
2405{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002406 PyObject *result = NULL;
2407 int year = GET_YEAR(date);
2408 int month = GET_MONTH(date);
2409 int deltadays = GET_TD_DAYS(delta);
2410 /* C-level overflow is impossible because |deltadays| < 1e9. */
2411 int day = GET_DAY(date) + (negate ? -deltadays : deltadays);
Tim Peters2a799bf2002-12-16 20:18:38 +00002412
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002413 if (normalize_date(&year, &month, &day) >= 0)
2414 result = new_date(year, month, day);
2415 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002416}
2417
2418static PyObject *
2419date_add(PyObject *left, PyObject *right)
2420{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002421 if (PyDateTime_Check(left) || PyDateTime_Check(right)) {
2422 Py_INCREF(Py_NotImplemented);
2423 return Py_NotImplemented;
2424 }
2425 if (PyDate_Check(left)) {
2426 /* date + ??? */
2427 if (PyDelta_Check(right))
2428 /* date + delta */
2429 return add_date_timedelta((PyDateTime_Date *) left,
2430 (PyDateTime_Delta *) right,
2431 0);
2432 }
2433 else {
2434 /* ??? + date
2435 * 'right' must be one of us, or we wouldn't have been called
2436 */
2437 if (PyDelta_Check(left))
2438 /* delta + date */
2439 return add_date_timedelta((PyDateTime_Date *) right,
2440 (PyDateTime_Delta *) left,
2441 0);
2442 }
2443 Py_INCREF(Py_NotImplemented);
2444 return Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00002445}
2446
2447static PyObject *
2448date_subtract(PyObject *left, PyObject *right)
2449{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002450 if (PyDateTime_Check(left) || PyDateTime_Check(right)) {
2451 Py_INCREF(Py_NotImplemented);
2452 return Py_NotImplemented;
2453 }
2454 if (PyDate_Check(left)) {
2455 if (PyDate_Check(right)) {
2456 /* date - date */
2457 int left_ord = ymd_to_ord(GET_YEAR(left),
2458 GET_MONTH(left),
2459 GET_DAY(left));
2460 int right_ord = ymd_to_ord(GET_YEAR(right),
2461 GET_MONTH(right),
2462 GET_DAY(right));
2463 return new_delta(left_ord - right_ord, 0, 0, 0);
2464 }
2465 if (PyDelta_Check(right)) {
2466 /* date - delta */
2467 return add_date_timedelta((PyDateTime_Date *) left,
2468 (PyDateTime_Delta *) right,
2469 1);
2470 }
2471 }
2472 Py_INCREF(Py_NotImplemented);
2473 return Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00002474}
2475
2476
2477/* Various ways to turn a date into a string. */
2478
2479static PyObject *
2480date_repr(PyDateTime_Date *self)
2481{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002482 char buffer[1028];
2483 const char *type_name;
Tim Peters2a799bf2002-12-16 20:18:38 +00002484
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002485 type_name = Py_TYPE(self)->tp_name;
2486 PyOS_snprintf(buffer, sizeof(buffer), "%s(%d, %d, %d)",
2487 type_name,
2488 GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002489
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002490 return PyString_FromString(buffer);
Tim Peters2a799bf2002-12-16 20:18:38 +00002491}
2492
2493static PyObject *
2494date_isoformat(PyDateTime_Date *self)
2495{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002496 char buffer[128];
Tim Peters2a799bf2002-12-16 20:18:38 +00002497
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002498 isoformat_date(self, buffer, sizeof(buffer));
2499 return PyString_FromString(buffer);
Tim Peters2a799bf2002-12-16 20:18:38 +00002500}
2501
Tim Peterse2df5ff2003-05-02 18:39:55 +00002502/* str() calls the appropriate isoformat() method. */
Tim Peters2a799bf2002-12-16 20:18:38 +00002503static PyObject *
2504date_str(PyDateTime_Date *self)
2505{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002506 return PyObject_CallMethod((PyObject *)self, "isoformat", "()");
Tim Peters2a799bf2002-12-16 20:18:38 +00002507}
2508
2509
2510static PyObject *
2511date_ctime(PyDateTime_Date *self)
2512{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002513 return format_ctime(self, 0, 0, 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00002514}
2515
2516static PyObject *
2517date_strftime(PyDateTime_Date *self, PyObject *args, PyObject *kw)
2518{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002519 /* This method can be inherited, and needs to call the
2520 * timetuple() method appropriate to self's class.
2521 */
2522 PyObject *result;
2523 PyObject *tuple;
2524 const char *format;
2525 Py_ssize_t format_len;
2526 static char *keywords[] = {"format", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00002527
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002528 if (! PyArg_ParseTupleAndKeywords(args, kw, "s#:strftime", keywords,
2529 &format, &format_len))
2530 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002531
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002532 tuple = PyObject_CallMethod((PyObject *)self, "timetuple", "()");
2533 if (tuple == NULL)
2534 return NULL;
2535 result = wrap_strftime((PyObject *)self, format, format_len, tuple,
2536 (PyObject *)self);
2537 Py_DECREF(tuple);
2538 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002539}
2540
Eric Smitha9f7d622008-02-17 19:46:49 +00002541static PyObject *
2542date_format(PyDateTime_Date *self, PyObject *args)
2543{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002544 PyObject *format;
Eric Smitha9f7d622008-02-17 19:46:49 +00002545
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002546 if (!PyArg_ParseTuple(args, "O:__format__", &format))
2547 return NULL;
Eric Smitha9f7d622008-02-17 19:46:49 +00002548
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002549 /* Check for str or unicode */
2550 if (PyString_Check(format)) {
2551 /* If format is zero length, return str(self) */
2552 if (PyString_GET_SIZE(format) == 0)
2553 return PyObject_Str((PyObject *)self);
2554 } else if (PyUnicode_Check(format)) {
2555 /* If format is zero length, return str(self) */
2556 if (PyUnicode_GET_SIZE(format) == 0)
2557 return PyObject_Unicode((PyObject *)self);
2558 } else {
2559 PyErr_Format(PyExc_ValueError,
2560 "__format__ expects str or unicode, not %.200s",
2561 Py_TYPE(format)->tp_name);
2562 return NULL;
2563 }
2564 return PyObject_CallMethod((PyObject *)self, "strftime", "O", format);
Eric Smitha9f7d622008-02-17 19:46:49 +00002565}
2566
Tim Peters2a799bf2002-12-16 20:18:38 +00002567/* ISO methods. */
2568
2569static PyObject *
2570date_isoweekday(PyDateTime_Date *self)
2571{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002572 int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002573
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002574 return PyInt_FromLong(dow + 1);
Tim Peters2a799bf2002-12-16 20:18:38 +00002575}
2576
2577static PyObject *
2578date_isocalendar(PyDateTime_Date *self)
2579{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002580 int year = GET_YEAR(self);
2581 int week1_monday = iso_week1_monday(year);
2582 int today = ymd_to_ord(year, GET_MONTH(self), GET_DAY(self));
2583 int week;
2584 int day;
Tim Peters2a799bf2002-12-16 20:18:38 +00002585
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002586 week = divmod(today - week1_monday, 7, &day);
2587 if (week < 0) {
2588 --year;
2589 week1_monday = iso_week1_monday(year);
2590 week = divmod(today - week1_monday, 7, &day);
2591 }
2592 else if (week >= 52 && today >= iso_week1_monday(year + 1)) {
2593 ++year;
2594 week = 0;
2595 }
2596 return Py_BuildValue("iii", year, week + 1, day + 1);
Tim Peters2a799bf2002-12-16 20:18:38 +00002597}
2598
2599/* Miscellaneous methods. */
2600
2601/* This is more natural as a tp_compare, but doesn't work then: for whatever
2602 * reason, Python's try_3way_compare ignores tp_compare unless
2603 * PyInstance_Check returns true, but these aren't old-style classes.
2604 */
2605static PyObject *
2606date_richcompare(PyDateTime_Date *self, PyObject *other, int op)
2607{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002608 int diff = 42; /* nonsense */
Tim Peters2a799bf2002-12-16 20:18:38 +00002609
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002610 if (PyDate_Check(other))
2611 diff = memcmp(self->data, ((PyDateTime_Date *)other)->data,
2612 _PyDateTime_DATE_DATASIZE);
Tim Peters07534a62003-02-07 22:50:28 +00002613
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002614 else if (PyObject_HasAttrString(other, "timetuple")) {
2615 /* A hook for other kinds of date objects. */
2616 Py_INCREF(Py_NotImplemented);
2617 return Py_NotImplemented;
2618 }
2619 else if (op == Py_EQ || op == Py_NE)
2620 diff = 1; /* any non-zero value will do */
Tim Peters07534a62003-02-07 22:50:28 +00002621
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002622 else /* stop this from falling back to address comparison */
2623 return cmperror((PyObject *)self, other);
Tim Peters07534a62003-02-07 22:50:28 +00002624
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002625 return diff_to_bool(diff, op);
Tim Peters2a799bf2002-12-16 20:18:38 +00002626}
2627
2628static PyObject *
2629date_timetuple(PyDateTime_Date *self)
2630{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002631 return build_struct_time(GET_YEAR(self),
2632 GET_MONTH(self),
2633 GET_DAY(self),
2634 0, 0, 0, -1);
Tim Peters2a799bf2002-12-16 20:18:38 +00002635}
2636
Tim Peters12bf3392002-12-24 05:41:27 +00002637static PyObject *
2638date_replace(PyDateTime_Date *self, PyObject *args, PyObject *kw)
2639{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002640 PyObject *clone;
2641 PyObject *tuple;
2642 int year = GET_YEAR(self);
2643 int month = GET_MONTH(self);
2644 int day = GET_DAY(self);
Tim Peters12bf3392002-12-24 05:41:27 +00002645
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002646 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iii:replace", date_kws,
2647 &year, &month, &day))
2648 return NULL;
2649 tuple = Py_BuildValue("iii", year, month, day);
2650 if (tuple == NULL)
2651 return NULL;
2652 clone = date_new(Py_TYPE(self), tuple, NULL);
2653 Py_DECREF(tuple);
2654 return clone;
Tim Peters12bf3392002-12-24 05:41:27 +00002655}
2656
Tim Peters2a799bf2002-12-16 20:18:38 +00002657static PyObject *date_getstate(PyDateTime_Date *self);
2658
2659static long
2660date_hash(PyDateTime_Date *self)
2661{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002662 if (self->hashcode == -1) {
2663 PyObject *temp = date_getstate(self);
2664 if (temp != NULL) {
2665 self->hashcode = PyObject_Hash(temp);
2666 Py_DECREF(temp);
2667 }
2668 }
2669 return self->hashcode;
Tim Peters2a799bf2002-12-16 20:18:38 +00002670}
2671
2672static PyObject *
2673date_toordinal(PyDateTime_Date *self)
2674{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002675 return PyInt_FromLong(ymd_to_ord(GET_YEAR(self), GET_MONTH(self),
2676 GET_DAY(self)));
Tim Peters2a799bf2002-12-16 20:18:38 +00002677}
2678
2679static PyObject *
2680date_weekday(PyDateTime_Date *self)
2681{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002682 int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002683
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002684 return PyInt_FromLong(dow);
Tim Peters2a799bf2002-12-16 20:18:38 +00002685}
2686
Tim Peters371935f2003-02-01 01:52:50 +00002687/* Pickle support, a simple use of __reduce__. */
Tim Peters2a799bf2002-12-16 20:18:38 +00002688
Tim Petersb57f8f02003-02-01 02:54:15 +00002689/* __getstate__ isn't exposed */
Tim Peters2a799bf2002-12-16 20:18:38 +00002690static PyObject *
2691date_getstate(PyDateTime_Date *self)
2692{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002693 return Py_BuildValue(
2694 "(N)",
2695 PyString_FromStringAndSize((char *)self->data,
2696 _PyDateTime_DATE_DATASIZE));
Tim Peters2a799bf2002-12-16 20:18:38 +00002697}
2698
2699static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00002700date_reduce(PyDateTime_Date *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00002701{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002702 return Py_BuildValue("(ON)", Py_TYPE(self), date_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002703}
2704
2705static PyMethodDef date_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002706
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002707 /* Class methods: */
Guido van Rossum177e41a2003-01-30 22:06:23 +00002708
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002709 {"fromtimestamp", (PyCFunction)date_fromtimestamp, METH_VARARGS |
2710 METH_CLASS,
2711 PyDoc_STR("timestamp -> local date from a POSIX timestamp (like "
2712 "time.time()).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002713
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002714 {"fromordinal", (PyCFunction)date_fromordinal, METH_VARARGS |
2715 METH_CLASS,
2716 PyDoc_STR("int -> date corresponding to a proleptic Gregorian "
2717 "ordinal.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002718
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002719 {"today", (PyCFunction)date_today, METH_NOARGS | METH_CLASS,
2720 PyDoc_STR("Current date or datetime: same as "
2721 "self.__class__.fromtimestamp(time.time()).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002722
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002723 /* Instance methods: */
Tim Peters2a799bf2002-12-16 20:18:38 +00002724
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002725 {"ctime", (PyCFunction)date_ctime, METH_NOARGS,
2726 PyDoc_STR("Return ctime() style string.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002727
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002728 {"strftime", (PyCFunction)date_strftime, METH_VARARGS | METH_KEYWORDS,
2729 PyDoc_STR("format -> strftime() style string.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002730
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002731 {"__format__", (PyCFunction)date_format, METH_VARARGS,
2732 PyDoc_STR("Formats self with strftime.")},
Eric Smitha9f7d622008-02-17 19:46:49 +00002733
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002734 {"timetuple", (PyCFunction)date_timetuple, METH_NOARGS,
2735 PyDoc_STR("Return time tuple, compatible with time.localtime().")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002736
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002737 {"isocalendar", (PyCFunction)date_isocalendar, METH_NOARGS,
2738 PyDoc_STR("Return a 3-tuple containing ISO year, week number, and "
2739 "weekday.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002740
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002741 {"isoformat", (PyCFunction)date_isoformat, METH_NOARGS,
2742 PyDoc_STR("Return string in ISO 8601 format, YYYY-MM-DD.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002743
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002744 {"isoweekday", (PyCFunction)date_isoweekday, METH_NOARGS,
2745 PyDoc_STR("Return the day of the week represented by the date.\n"
2746 "Monday == 1 ... Sunday == 7")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002747
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002748 {"toordinal", (PyCFunction)date_toordinal, METH_NOARGS,
2749 PyDoc_STR("Return proleptic Gregorian ordinal. January 1 of year "
2750 "1 is day 1.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002751
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002752 {"weekday", (PyCFunction)date_weekday, METH_NOARGS,
2753 PyDoc_STR("Return the day of the week represented by the date.\n"
2754 "Monday == 0 ... Sunday == 6")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002755
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002756 {"replace", (PyCFunction)date_replace, METH_VARARGS | METH_KEYWORDS,
2757 PyDoc_STR("Return date with new specified fields.")},
Tim Peters12bf3392002-12-24 05:41:27 +00002758
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002759 {"__reduce__", (PyCFunction)date_reduce, METH_NOARGS,
2760 PyDoc_STR("__reduce__() -> (cls, state)")},
Guido van Rossum177e41a2003-01-30 22:06:23 +00002761
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002762 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00002763};
2764
2765static char date_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00002766PyDoc_STR("date(year, month, day) --> date object");
Tim Peters2a799bf2002-12-16 20:18:38 +00002767
2768static PyNumberMethods date_as_number = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002769 date_add, /* nb_add */
2770 date_subtract, /* nb_subtract */
2771 0, /* nb_multiply */
2772 0, /* nb_divide */
2773 0, /* nb_remainder */
2774 0, /* nb_divmod */
2775 0, /* nb_power */
2776 0, /* nb_negative */
2777 0, /* nb_positive */
2778 0, /* nb_absolute */
2779 0, /* nb_nonzero */
Tim Peters2a799bf2002-12-16 20:18:38 +00002780};
2781
2782static PyTypeObject PyDateTime_DateType = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002783 PyVarObject_HEAD_INIT(NULL, 0)
2784 "datetime.date", /* tp_name */
2785 sizeof(PyDateTime_Date), /* tp_basicsize */
2786 0, /* tp_itemsize */
2787 0, /* tp_dealloc */
2788 0, /* tp_print */
2789 0, /* tp_getattr */
2790 0, /* tp_setattr */
2791 0, /* tp_compare */
2792 (reprfunc)date_repr, /* tp_repr */
2793 &date_as_number, /* tp_as_number */
2794 0, /* tp_as_sequence */
2795 0, /* tp_as_mapping */
2796 (hashfunc)date_hash, /* tp_hash */
2797 0, /* tp_call */
2798 (reprfunc)date_str, /* tp_str */
2799 PyObject_GenericGetAttr, /* tp_getattro */
2800 0, /* tp_setattro */
2801 0, /* tp_as_buffer */
2802 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
2803 Py_TPFLAGS_BASETYPE, /* tp_flags */
2804 date_doc, /* tp_doc */
2805 0, /* tp_traverse */
2806 0, /* tp_clear */
2807 (richcmpfunc)date_richcompare, /* tp_richcompare */
2808 0, /* tp_weaklistoffset */
2809 0, /* tp_iter */
2810 0, /* tp_iternext */
2811 date_methods, /* tp_methods */
2812 0, /* tp_members */
2813 date_getset, /* tp_getset */
2814 0, /* tp_base */
2815 0, /* tp_dict */
2816 0, /* tp_descr_get */
2817 0, /* tp_descr_set */
2818 0, /* tp_dictoffset */
2819 0, /* tp_init */
2820 0, /* tp_alloc */
2821 date_new, /* tp_new */
2822 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00002823};
2824
2825/*
Tim Peters2a799bf2002-12-16 20:18:38 +00002826 * PyDateTime_TZInfo implementation.
2827 */
2828
2829/* This is a pure abstract base class, so doesn't do anything beyond
2830 * raising NotImplemented exceptions. Real tzinfo classes need
2831 * to derive from this. This is mostly for clarity, and for efficiency in
Tim Petersa9bc1682003-01-11 03:39:11 +00002832 * datetime and time constructors (their tzinfo arguments need to
Tim Peters2a799bf2002-12-16 20:18:38 +00002833 * be subclasses of this tzinfo class, which is easy and quick to check).
2834 *
2835 * Note: For reasons having to do with pickling of subclasses, we have
2836 * to allow tzinfo objects to be instantiated. This wasn't an issue
2837 * in the Python implementation (__init__() could raise NotImplementedError
2838 * there without ill effect), but doing so in the C implementation hit a
2839 * brick wall.
2840 */
2841
2842static PyObject *
2843tzinfo_nogo(const char* methodname)
2844{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002845 PyErr_Format(PyExc_NotImplementedError,
2846 "a tzinfo subclass must implement %s()",
2847 methodname);
2848 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002849}
2850
2851/* Methods. A subclass must implement these. */
2852
Tim Peters52dcce22003-01-23 16:36:11 +00002853static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002854tzinfo_tzname(PyDateTime_TZInfo *self, PyObject *dt)
2855{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002856 return tzinfo_nogo("tzname");
Tim Peters2a799bf2002-12-16 20:18:38 +00002857}
2858
Tim Peters52dcce22003-01-23 16:36:11 +00002859static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002860tzinfo_utcoffset(PyDateTime_TZInfo *self, PyObject *dt)
2861{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002862 return tzinfo_nogo("utcoffset");
Tim Peters2a799bf2002-12-16 20:18:38 +00002863}
2864
Tim Peters52dcce22003-01-23 16:36:11 +00002865static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002866tzinfo_dst(PyDateTime_TZInfo *self, PyObject *dt)
2867{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002868 return tzinfo_nogo("dst");
Tim Peters2a799bf2002-12-16 20:18:38 +00002869}
2870
Tim Peters52dcce22003-01-23 16:36:11 +00002871static PyObject *
2872tzinfo_fromutc(PyDateTime_TZInfo *self, PyDateTime_DateTime *dt)
2873{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002874 int y, m, d, hh, mm, ss, us;
Tim Peters52dcce22003-01-23 16:36:11 +00002875
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002876 PyObject *result;
2877 int off, dst;
2878 int none;
2879 int delta;
Tim Peters52dcce22003-01-23 16:36:11 +00002880
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002881 if (! PyDateTime_Check(dt)) {
2882 PyErr_SetString(PyExc_TypeError,
2883 "fromutc: argument must be a datetime");
2884 return NULL;
2885 }
2886 if (! HASTZINFO(dt) || dt->tzinfo != (PyObject *)self) {
2887 PyErr_SetString(PyExc_ValueError, "fromutc: dt.tzinfo "
2888 "is not self");
2889 return NULL;
2890 }
Tim Peters52dcce22003-01-23 16:36:11 +00002891
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002892 off = call_utcoffset(dt->tzinfo, (PyObject *)dt, &none);
2893 if (off == -1 && PyErr_Occurred())
2894 return NULL;
2895 if (none) {
2896 PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
2897 "utcoffset() result required");
2898 return NULL;
2899 }
Tim Peters52dcce22003-01-23 16:36:11 +00002900
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002901 dst = call_dst(dt->tzinfo, (PyObject *)dt, &none);
2902 if (dst == -1 && PyErr_Occurred())
2903 return NULL;
2904 if (none) {
2905 PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
2906 "dst() result required");
2907 return NULL;
2908 }
Tim Peters52dcce22003-01-23 16:36:11 +00002909
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002910 y = GET_YEAR(dt);
2911 m = GET_MONTH(dt);
2912 d = GET_DAY(dt);
2913 hh = DATE_GET_HOUR(dt);
2914 mm = DATE_GET_MINUTE(dt);
2915 ss = DATE_GET_SECOND(dt);
2916 us = DATE_GET_MICROSECOND(dt);
Tim Peters52dcce22003-01-23 16:36:11 +00002917
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002918 delta = off - dst;
2919 mm += delta;
2920 if ((mm < 0 || mm >= 60) &&
2921 normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
2922 return NULL;
2923 result = new_datetime(y, m, d, hh, mm, ss, us, dt->tzinfo);
2924 if (result == NULL)
2925 return result;
Tim Peters52dcce22003-01-23 16:36:11 +00002926
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002927 dst = call_dst(dt->tzinfo, result, &none);
2928 if (dst == -1 && PyErr_Occurred())
2929 goto Fail;
2930 if (none)
2931 goto Inconsistent;
2932 if (dst == 0)
2933 return result;
Tim Peters52dcce22003-01-23 16:36:11 +00002934
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002935 mm += dst;
2936 if ((mm < 0 || mm >= 60) &&
2937 normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
2938 goto Fail;
2939 Py_DECREF(result);
2940 result = new_datetime(y, m, d, hh, mm, ss, us, dt->tzinfo);
2941 return result;
Tim Peters52dcce22003-01-23 16:36:11 +00002942
2943Inconsistent:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002944 PyErr_SetString(PyExc_ValueError, "fromutc: tz.dst() gave"
2945 "inconsistent results; cannot convert");
Tim Peters52dcce22003-01-23 16:36:11 +00002946
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002947 /* fall thru to failure */
Tim Peters52dcce22003-01-23 16:36:11 +00002948Fail:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002949 Py_DECREF(result);
2950 return NULL;
Tim Peters52dcce22003-01-23 16:36:11 +00002951}
2952
Tim Peters2a799bf2002-12-16 20:18:38 +00002953/*
2954 * Pickle support. This is solely so that tzinfo subclasses can use
Guido van Rossum177e41a2003-01-30 22:06:23 +00002955 * pickling -- tzinfo itself is supposed to be uninstantiable.
Tim Peters2a799bf2002-12-16 20:18:38 +00002956 */
2957
Guido van Rossum177e41a2003-01-30 22:06:23 +00002958static PyObject *
2959tzinfo_reduce(PyObject *self)
2960{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002961 PyObject *args, *state, *tmp;
2962 PyObject *getinitargs, *getstate;
Tim Peters2a799bf2002-12-16 20:18:38 +00002963
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002964 tmp = PyTuple_New(0);
2965 if (tmp == NULL)
2966 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002967
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002968 getinitargs = PyObject_GetAttrString(self, "__getinitargs__");
2969 if (getinitargs != NULL) {
2970 args = PyObject_CallObject(getinitargs, tmp);
2971 Py_DECREF(getinitargs);
2972 if (args == NULL) {
2973 Py_DECREF(tmp);
2974 return NULL;
2975 }
2976 }
2977 else {
2978 PyErr_Clear();
2979 args = tmp;
2980 Py_INCREF(args);
2981 }
Guido van Rossum177e41a2003-01-30 22:06:23 +00002982
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002983 getstate = PyObject_GetAttrString(self, "__getstate__");
2984 if (getstate != NULL) {
2985 state = PyObject_CallObject(getstate, tmp);
2986 Py_DECREF(getstate);
2987 if (state == NULL) {
2988 Py_DECREF(args);
2989 Py_DECREF(tmp);
2990 return NULL;
2991 }
2992 }
2993 else {
2994 PyObject **dictptr;
2995 PyErr_Clear();
2996 state = Py_None;
2997 dictptr = _PyObject_GetDictPtr(self);
2998 if (dictptr && *dictptr && PyDict_Size(*dictptr))
2999 state = *dictptr;
3000 Py_INCREF(state);
3001 }
Guido van Rossum177e41a2003-01-30 22:06:23 +00003002
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003003 Py_DECREF(tmp);
Guido van Rossum177e41a2003-01-30 22:06:23 +00003004
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003005 if (state == Py_None) {
3006 Py_DECREF(state);
3007 return Py_BuildValue("(ON)", Py_TYPE(self), args);
3008 }
3009 else
3010 return Py_BuildValue("(ONN)", Py_TYPE(self), args, state);
Guido van Rossum177e41a2003-01-30 22:06:23 +00003011}
Tim Peters2a799bf2002-12-16 20:18:38 +00003012
3013static PyMethodDef tzinfo_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00003014
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003015 {"tzname", (PyCFunction)tzinfo_tzname, METH_O,
3016 PyDoc_STR("datetime -> string name of time zone.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003017
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003018 {"utcoffset", (PyCFunction)tzinfo_utcoffset, METH_O,
3019 PyDoc_STR("datetime -> minutes east of UTC (negative for "
3020 "west of UTC).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003021
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003022 {"dst", (PyCFunction)tzinfo_dst, METH_O,
3023 PyDoc_STR("datetime -> DST offset in minutes east of UTC.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003024
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003025 {"fromutc", (PyCFunction)tzinfo_fromutc, METH_O,
3026 PyDoc_STR("datetime in UTC -> datetime in local time.")},
Tim Peters52dcce22003-01-23 16:36:11 +00003027
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003028 {"__reduce__", (PyCFunction)tzinfo_reduce, METH_NOARGS,
3029 PyDoc_STR("-> (cls, state)")},
Guido van Rossum177e41a2003-01-30 22:06:23 +00003030
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003031 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00003032};
3033
3034static char tzinfo_doc[] =
3035PyDoc_STR("Abstract base class for time zone info objects.");
3036
Neal Norwitzce3d34d2003-02-04 20:45:17 +00003037statichere PyTypeObject PyDateTime_TZInfoType = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003038 PyObject_HEAD_INIT(NULL)
3039 0, /* ob_size */
3040 "datetime.tzinfo", /* tp_name */
3041 sizeof(PyDateTime_TZInfo), /* tp_basicsize */
3042 0, /* tp_itemsize */
3043 0, /* tp_dealloc */
3044 0, /* tp_print */
3045 0, /* tp_getattr */
3046 0, /* tp_setattr */
3047 0, /* tp_compare */
3048 0, /* tp_repr */
3049 0, /* tp_as_number */
3050 0, /* tp_as_sequence */
3051 0, /* tp_as_mapping */
3052 0, /* tp_hash */
3053 0, /* tp_call */
3054 0, /* tp_str */
3055 PyObject_GenericGetAttr, /* tp_getattro */
3056 0, /* tp_setattro */
3057 0, /* tp_as_buffer */
3058 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
3059 Py_TPFLAGS_BASETYPE, /* tp_flags */
3060 tzinfo_doc, /* tp_doc */
3061 0, /* tp_traverse */
3062 0, /* tp_clear */
3063 0, /* tp_richcompare */
3064 0, /* tp_weaklistoffset */
3065 0, /* tp_iter */
3066 0, /* tp_iternext */
3067 tzinfo_methods, /* tp_methods */
3068 0, /* tp_members */
3069 0, /* tp_getset */
3070 0, /* tp_base */
3071 0, /* tp_dict */
3072 0, /* tp_descr_get */
3073 0, /* tp_descr_set */
3074 0, /* tp_dictoffset */
3075 0, /* tp_init */
3076 0, /* tp_alloc */
3077 PyType_GenericNew, /* tp_new */
3078 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00003079};
3080
3081/*
Tim Peters37f39822003-01-10 03:49:02 +00003082 * PyDateTime_Time implementation.
Tim Peters2a799bf2002-12-16 20:18:38 +00003083 */
3084
Tim Peters37f39822003-01-10 03:49:02 +00003085/* Accessor properties.
Tim Peters2a799bf2002-12-16 20:18:38 +00003086 */
3087
3088static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003089time_hour(PyDateTime_Time *self, void *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00003090{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003091 return PyInt_FromLong(TIME_GET_HOUR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00003092}
3093
Tim Peters37f39822003-01-10 03:49:02 +00003094static PyObject *
3095time_minute(PyDateTime_Time *self, void *unused)
3096{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003097 return PyInt_FromLong(TIME_GET_MINUTE(self));
Tim Peters37f39822003-01-10 03:49:02 +00003098}
3099
3100/* The name time_second conflicted with some platform header file. */
3101static PyObject *
3102py_time_second(PyDateTime_Time *self, void *unused)
3103{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003104 return PyInt_FromLong(TIME_GET_SECOND(self));
Tim Peters37f39822003-01-10 03:49:02 +00003105}
3106
3107static PyObject *
3108time_microsecond(PyDateTime_Time *self, void *unused)
3109{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003110 return PyInt_FromLong(TIME_GET_MICROSECOND(self));
Tim Peters37f39822003-01-10 03:49:02 +00003111}
3112
3113static PyObject *
3114time_tzinfo(PyDateTime_Time *self, void *unused)
3115{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003116 PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
3117 Py_INCREF(result);
3118 return result;
Tim Peters37f39822003-01-10 03:49:02 +00003119}
3120
3121static PyGetSetDef time_getset[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003122 {"hour", (getter)time_hour},
3123 {"minute", (getter)time_minute},
3124 {"second", (getter)py_time_second},
3125 {"microsecond", (getter)time_microsecond},
3126 {"tzinfo", (getter)time_tzinfo},
3127 {NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00003128};
3129
3130/*
3131 * Constructors.
3132 */
3133
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003134static char *time_kws[] = {"hour", "minute", "second", "microsecond",
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003135 "tzinfo", NULL};
Tim Peters12bf3392002-12-24 05:41:27 +00003136
Tim Peters2a799bf2002-12-16 20:18:38 +00003137static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003138time_new(PyTypeObject *type, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003139{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003140 PyObject *self = NULL;
3141 PyObject *state;
3142 int hour = 0;
3143 int minute = 0;
3144 int second = 0;
3145 int usecond = 0;
3146 PyObject *tzinfo = Py_None;
Tim Peters2a799bf2002-12-16 20:18:38 +00003147
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003148 /* Check for invocation from pickle with __getstate__ state */
3149 if (PyTuple_GET_SIZE(args) >= 1 &&
3150 PyTuple_GET_SIZE(args) <= 2 &&
3151 PyString_Check(state = PyTuple_GET_ITEM(args, 0)) &&
3152 PyString_GET_SIZE(state) == _PyDateTime_TIME_DATASIZE &&
3153 ((unsigned char) (PyString_AS_STRING(state)[0])) < 24)
3154 {
3155 PyDateTime_Time *me;
3156 char aware;
Tim Peters70533e22003-02-01 04:40:04 +00003157
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003158 if (PyTuple_GET_SIZE(args) == 2) {
3159 tzinfo = PyTuple_GET_ITEM(args, 1);
3160 if (check_tzinfo_subclass(tzinfo) < 0) {
3161 PyErr_SetString(PyExc_TypeError, "bad "
3162 "tzinfo state arg");
3163 return NULL;
3164 }
3165 }
3166 aware = (char)(tzinfo != Py_None);
3167 me = (PyDateTime_Time *) (type->tp_alloc(type, aware));
3168 if (me != NULL) {
3169 char *pdata = PyString_AS_STRING(state);
Tim Peters70533e22003-02-01 04:40:04 +00003170
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003171 memcpy(me->data, pdata, _PyDateTime_TIME_DATASIZE);
3172 me->hashcode = -1;
3173 me->hastzinfo = aware;
3174 if (aware) {
3175 Py_INCREF(tzinfo);
3176 me->tzinfo = tzinfo;
3177 }
3178 }
3179 return (PyObject *)me;
3180 }
Guido van Rossum177e41a2003-01-30 22:06:23 +00003181
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003182 if (PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO", time_kws,
3183 &hour, &minute, &second, &usecond,
3184 &tzinfo)) {
3185 if (check_time_args(hour, minute, second, usecond) < 0)
3186 return NULL;
3187 if (check_tzinfo_subclass(tzinfo) < 0)
3188 return NULL;
3189 self = new_time_ex(hour, minute, second, usecond, tzinfo,
3190 type);
3191 }
3192 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00003193}
3194
3195/*
3196 * Destructor.
3197 */
3198
3199static void
Tim Peters37f39822003-01-10 03:49:02 +00003200time_dealloc(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003201{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003202 if (HASTZINFO(self)) {
3203 Py_XDECREF(self->tzinfo);
3204 }
3205 Py_TYPE(self)->tp_free((PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00003206}
3207
3208/*
Tim Peters855fe882002-12-22 03:43:39 +00003209 * Indirect access to tzinfo methods.
Tim Peters2a799bf2002-12-16 20:18:38 +00003210 */
3211
Tim Peters2a799bf2002-12-16 20:18:38 +00003212/* These are all METH_NOARGS, so don't need to check the arglist. */
3213static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003214time_utcoffset(PyDateTime_Time *self, PyObject *unused) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003215 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
3216 "utcoffset", Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00003217}
3218
3219static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003220time_dst(PyDateTime_Time *self, PyObject *unused) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003221 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
3222 "dst", Py_None);
Tim Peters855fe882002-12-22 03:43:39 +00003223}
3224
3225static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003226time_tzname(PyDateTime_Time *self, PyObject *unused) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003227 return call_tzname(HASTZINFO(self) ? self->tzinfo : Py_None,
3228 Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00003229}
3230
3231/*
Tim Peters37f39822003-01-10 03:49:02 +00003232 * Various ways to turn a time into a string.
Tim Peters2a799bf2002-12-16 20:18:38 +00003233 */
3234
3235static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003236time_repr(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003237{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003238 char buffer[100];
3239 const char *type_name = Py_TYPE(self)->tp_name;
3240 int h = TIME_GET_HOUR(self);
3241 int m = TIME_GET_MINUTE(self);
3242 int s = TIME_GET_SECOND(self);
3243 int us = TIME_GET_MICROSECOND(self);
3244 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00003245
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003246 if (us)
3247 PyOS_snprintf(buffer, sizeof(buffer),
3248 "%s(%d, %d, %d, %d)", type_name, h, m, s, us);
3249 else if (s)
3250 PyOS_snprintf(buffer, sizeof(buffer),
3251 "%s(%d, %d, %d)", type_name, h, m, s);
3252 else
3253 PyOS_snprintf(buffer, sizeof(buffer),
3254 "%s(%d, %d)", type_name, h, m);
3255 result = PyString_FromString(buffer);
3256 if (result != NULL && HASTZINFO(self))
3257 result = append_keyword_tzinfo(result, self->tzinfo);
3258 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00003259}
3260
Tim Peters37f39822003-01-10 03:49:02 +00003261static PyObject *
3262time_str(PyDateTime_Time *self)
3263{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003264 return PyObject_CallMethod((PyObject *)self, "isoformat", "()");
Tim Peters37f39822003-01-10 03:49:02 +00003265}
Tim Peters2a799bf2002-12-16 20:18:38 +00003266
3267static PyObject *
Martin v. Löwis4c11a922007-02-08 09:13:36 +00003268time_isoformat(PyDateTime_Time *self, PyObject *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00003269{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003270 char buf[100];
3271 PyObject *result;
3272 /* Reuse the time format code from the datetime type. */
3273 PyDateTime_DateTime datetime;
3274 PyDateTime_DateTime *pdatetime = &datetime;
Tim Peters2a799bf2002-12-16 20:18:38 +00003275
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003276 /* Copy over just the time bytes. */
3277 memcpy(pdatetime->data + _PyDateTime_DATE_DATASIZE,
3278 self->data,
3279 _PyDateTime_TIME_DATASIZE);
Tim Peters37f39822003-01-10 03:49:02 +00003280
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003281 isoformat_time(pdatetime, buf, sizeof(buf));
3282 result = PyString_FromString(buf);
3283 if (result == NULL || ! HASTZINFO(self) || self->tzinfo == Py_None)
3284 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00003285
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003286 /* We need to append the UTC offset. */
3287 if (format_utcoffset(buf, sizeof(buf), ":", self->tzinfo,
3288 Py_None) < 0) {
3289 Py_DECREF(result);
3290 return NULL;
3291 }
3292 PyString_ConcatAndDel(&result, PyString_FromString(buf));
3293 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00003294}
3295
Tim Peters37f39822003-01-10 03:49:02 +00003296static PyObject *
3297time_strftime(PyDateTime_Time *self, PyObject *args, PyObject *kw)
3298{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003299 PyObject *result;
3300 PyObject *tuple;
3301 const char *format;
3302 Py_ssize_t format_len;
3303 static char *keywords[] = {"format", NULL};
Tim Peters37f39822003-01-10 03:49:02 +00003304
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003305 if (! PyArg_ParseTupleAndKeywords(args, kw, "s#:strftime", keywords,
3306 &format, &format_len))
3307 return NULL;
Tim Peters37f39822003-01-10 03:49:02 +00003308
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003309 /* Python's strftime does insane things with the year part of the
3310 * timetuple. The year is forced to (the otherwise nonsensical)
3311 * 1900 to worm around that.
3312 */
3313 tuple = Py_BuildValue("iiiiiiiii",
3314 1900, 1, 1, /* year, month, day */
3315 TIME_GET_HOUR(self),
3316 TIME_GET_MINUTE(self),
3317 TIME_GET_SECOND(self),
3318 0, 1, -1); /* weekday, daynum, dst */
3319 if (tuple == NULL)
3320 return NULL;
3321 assert(PyTuple_Size(tuple) == 9);
3322 result = wrap_strftime((PyObject *)self, format, format_len, tuple,
3323 Py_None);
3324 Py_DECREF(tuple);
3325 return result;
Tim Peters37f39822003-01-10 03:49:02 +00003326}
Tim Peters2a799bf2002-12-16 20:18:38 +00003327
3328/*
3329 * Miscellaneous methods.
3330 */
3331
Tim Peters37f39822003-01-10 03:49:02 +00003332/* This is more natural as a tp_compare, but doesn't work then: for whatever
3333 * reason, Python's try_3way_compare ignores tp_compare unless
3334 * PyInstance_Check returns true, but these aren't old-style classes.
3335 */
3336static PyObject *
3337time_richcompare(PyDateTime_Time *self, PyObject *other, int op)
3338{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003339 int diff;
3340 naivety n1, n2;
3341 int offset1, offset2;
Tim Peters37f39822003-01-10 03:49:02 +00003342
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003343 if (! PyTime_Check(other)) {
3344 if (op == Py_EQ || op == Py_NE) {
3345 PyObject *result = op == Py_EQ ? Py_False : Py_True;
3346 Py_INCREF(result);
3347 return result;
3348 }
3349 /* Stop this from falling back to address comparison. */
3350 return cmperror((PyObject *)self, other);
3351 }
3352 if (classify_two_utcoffsets((PyObject *)self, &offset1, &n1, Py_None,
3353 other, &offset2, &n2, Py_None) < 0)
3354 return NULL;
3355 assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
3356 /* If they're both naive, or both aware and have the same offsets,
3357 * we get off cheap. Note that if they're both naive, offset1 ==
3358 * offset2 == 0 at this point.
3359 */
3360 if (n1 == n2 && offset1 == offset2) {
3361 diff = memcmp(self->data, ((PyDateTime_Time *)other)->data,
3362 _PyDateTime_TIME_DATASIZE);
3363 return diff_to_bool(diff, op);
3364 }
Tim Peters37f39822003-01-10 03:49:02 +00003365
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003366 if (n1 == OFFSET_AWARE && n2 == OFFSET_AWARE) {
3367 assert(offset1 != offset2); /* else last "if" handled it */
3368 /* Convert everything except microseconds to seconds. These
3369 * can't overflow (no more than the # of seconds in 2 days).
3370 */
3371 offset1 = TIME_GET_HOUR(self) * 3600 +
3372 (TIME_GET_MINUTE(self) - offset1) * 60 +
3373 TIME_GET_SECOND(self);
3374 offset2 = TIME_GET_HOUR(other) * 3600 +
3375 (TIME_GET_MINUTE(other) - offset2) * 60 +
3376 TIME_GET_SECOND(other);
3377 diff = offset1 - offset2;
3378 if (diff == 0)
3379 diff = TIME_GET_MICROSECOND(self) -
3380 TIME_GET_MICROSECOND(other);
3381 return diff_to_bool(diff, op);
3382 }
Tim Peters37f39822003-01-10 03:49:02 +00003383
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003384 assert(n1 != n2);
3385 PyErr_SetString(PyExc_TypeError,
3386 "can't compare offset-naive and "
3387 "offset-aware times");
3388 return NULL;
Tim Peters37f39822003-01-10 03:49:02 +00003389}
3390
3391static long
3392time_hash(PyDateTime_Time *self)
3393{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003394 if (self->hashcode == -1) {
3395 naivety n;
3396 int offset;
3397 PyObject *temp;
Tim Peters37f39822003-01-10 03:49:02 +00003398
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003399 n = classify_utcoffset((PyObject *)self, Py_None, &offset);
3400 assert(n != OFFSET_UNKNOWN);
3401 if (n == OFFSET_ERROR)
3402 return -1;
Tim Peters37f39822003-01-10 03:49:02 +00003403
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003404 /* Reduce this to a hash of another object. */
3405 if (offset == 0)
3406 temp = PyString_FromStringAndSize((char *)self->data,
3407 _PyDateTime_TIME_DATASIZE);
3408 else {
3409 int hour;
3410 int minute;
Tim Peters37f39822003-01-10 03:49:02 +00003411
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003412 assert(n == OFFSET_AWARE);
3413 assert(HASTZINFO(self));
3414 hour = divmod(TIME_GET_HOUR(self) * 60 +
3415 TIME_GET_MINUTE(self) - offset,
3416 60,
3417 &minute);
3418 if (0 <= hour && hour < 24)
3419 temp = new_time(hour, minute,
3420 TIME_GET_SECOND(self),
3421 TIME_GET_MICROSECOND(self),
3422 Py_None);
3423 else
3424 temp = Py_BuildValue("iiii",
3425 hour, minute,
3426 TIME_GET_SECOND(self),
3427 TIME_GET_MICROSECOND(self));
3428 }
3429 if (temp != NULL) {
3430 self->hashcode = PyObject_Hash(temp);
3431 Py_DECREF(temp);
3432 }
3433 }
3434 return self->hashcode;
Tim Peters37f39822003-01-10 03:49:02 +00003435}
Tim Peters2a799bf2002-12-16 20:18:38 +00003436
Tim Peters12bf3392002-12-24 05:41:27 +00003437static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003438time_replace(PyDateTime_Time *self, PyObject *args, PyObject *kw)
Tim Peters12bf3392002-12-24 05:41:27 +00003439{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003440 PyObject *clone;
3441 PyObject *tuple;
3442 int hh = TIME_GET_HOUR(self);
3443 int mm = TIME_GET_MINUTE(self);
3444 int ss = TIME_GET_SECOND(self);
3445 int us = TIME_GET_MICROSECOND(self);
3446 PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
Tim Peters12bf3392002-12-24 05:41:27 +00003447
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003448 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO:replace",
3449 time_kws,
3450 &hh, &mm, &ss, &us, &tzinfo))
3451 return NULL;
3452 tuple = Py_BuildValue("iiiiO", hh, mm, ss, us, tzinfo);
3453 if (tuple == NULL)
3454 return NULL;
3455 clone = time_new(Py_TYPE(self), tuple, NULL);
3456 Py_DECREF(tuple);
3457 return clone;
Tim Peters12bf3392002-12-24 05:41:27 +00003458}
3459
Tim Peters2a799bf2002-12-16 20:18:38 +00003460static int
Tim Peters37f39822003-01-10 03:49:02 +00003461time_nonzero(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003462{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003463 int offset;
3464 int none;
Tim Peters2a799bf2002-12-16 20:18:38 +00003465
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003466 if (TIME_GET_SECOND(self) || TIME_GET_MICROSECOND(self)) {
3467 /* Since utcoffset is in whole minutes, nothing can
3468 * alter the conclusion that this is nonzero.
3469 */
3470 return 1;
3471 }
3472 offset = 0;
3473 if (HASTZINFO(self) && self->tzinfo != Py_None) {
3474 offset = call_utcoffset(self->tzinfo, Py_None, &none);
3475 if (offset == -1 && PyErr_Occurred())
3476 return -1;
3477 }
3478 return (TIME_GET_MINUTE(self) - offset + TIME_GET_HOUR(self)*60) != 0;
Tim Peters2a799bf2002-12-16 20:18:38 +00003479}
3480
Tim Peters371935f2003-02-01 01:52:50 +00003481/* Pickle support, a simple use of __reduce__. */
Tim Peters2a799bf2002-12-16 20:18:38 +00003482
Tim Peters33e0f382003-01-10 02:05:14 +00003483/* Let basestate be the non-tzinfo data string.
Tim Peters2a799bf2002-12-16 20:18:38 +00003484 * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
3485 * So it's a tuple in any (non-error) case.
Tim Petersb57f8f02003-02-01 02:54:15 +00003486 * __getstate__ isn't exposed.
Tim Peters2a799bf2002-12-16 20:18:38 +00003487 */
3488static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003489time_getstate(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003490{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003491 PyObject *basestate;
3492 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00003493
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003494 basestate = PyString_FromStringAndSize((char *)self->data,
3495 _PyDateTime_TIME_DATASIZE);
3496 if (basestate != NULL) {
3497 if (! HASTZINFO(self) || self->tzinfo == Py_None)
3498 result = PyTuple_Pack(1, basestate);
3499 else
3500 result = PyTuple_Pack(2, basestate, self->tzinfo);
3501 Py_DECREF(basestate);
3502 }
3503 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00003504}
3505
3506static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00003507time_reduce(PyDateTime_Time *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00003508{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003509 return Py_BuildValue("(ON)", Py_TYPE(self), time_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00003510}
3511
Tim Peters37f39822003-01-10 03:49:02 +00003512static PyMethodDef time_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00003513
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003514 {"isoformat", (PyCFunction)time_isoformat, METH_NOARGS,
3515 PyDoc_STR("Return string in ISO 8601 format, HH:MM:SS[.mmmmmm]"
3516 "[+HH:MM].")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003517
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003518 {"strftime", (PyCFunction)time_strftime, METH_VARARGS | METH_KEYWORDS,
3519 PyDoc_STR("format -> strftime() style string.")},
Tim Peters37f39822003-01-10 03:49:02 +00003520
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003521 {"__format__", (PyCFunction)date_format, METH_VARARGS,
3522 PyDoc_STR("Formats self with strftime.")},
Eric Smitha9f7d622008-02-17 19:46:49 +00003523
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003524 {"utcoffset", (PyCFunction)time_utcoffset, METH_NOARGS,
3525 PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003526
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003527 {"tzname", (PyCFunction)time_tzname, METH_NOARGS,
3528 PyDoc_STR("Return self.tzinfo.tzname(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003529
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003530 {"dst", (PyCFunction)time_dst, METH_NOARGS,
3531 PyDoc_STR("Return self.tzinfo.dst(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003532
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003533 {"replace", (PyCFunction)time_replace, METH_VARARGS | METH_KEYWORDS,
3534 PyDoc_STR("Return time with new specified fields.")},
Tim Peters12bf3392002-12-24 05:41:27 +00003535
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003536 {"__reduce__", (PyCFunction)time_reduce, METH_NOARGS,
3537 PyDoc_STR("__reduce__() -> (cls, state)")},
Guido van Rossum177e41a2003-01-30 22:06:23 +00003538
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003539 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00003540};
3541
Tim Peters37f39822003-01-10 03:49:02 +00003542static char time_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00003543PyDoc_STR("time([hour[, minute[, second[, microsecond[, tzinfo]]]]]) --> a time object\n\
3544\n\
3545All arguments are optional. tzinfo may be None, or an instance of\n\
3546a tzinfo subclass. The remaining arguments may be ints or longs.\n");
Tim Peters2a799bf2002-12-16 20:18:38 +00003547
Tim Peters37f39822003-01-10 03:49:02 +00003548static PyNumberMethods time_as_number = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003549 0, /* nb_add */
3550 0, /* nb_subtract */
3551 0, /* nb_multiply */
3552 0, /* nb_divide */
3553 0, /* nb_remainder */
3554 0, /* nb_divmod */
3555 0, /* nb_power */
3556 0, /* nb_negative */
3557 0, /* nb_positive */
3558 0, /* nb_absolute */
3559 (inquiry)time_nonzero, /* nb_nonzero */
Tim Peters2a799bf2002-12-16 20:18:38 +00003560};
3561
Tim Peters37f39822003-01-10 03:49:02 +00003562statichere PyTypeObject PyDateTime_TimeType = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003563 PyObject_HEAD_INIT(NULL)
3564 0, /* ob_size */
3565 "datetime.time", /* tp_name */
3566 sizeof(PyDateTime_Time), /* tp_basicsize */
3567 0, /* tp_itemsize */
3568 (destructor)time_dealloc, /* tp_dealloc */
3569 0, /* tp_print */
3570 0, /* tp_getattr */
3571 0, /* tp_setattr */
3572 0, /* tp_compare */
3573 (reprfunc)time_repr, /* tp_repr */
3574 &time_as_number, /* tp_as_number */
3575 0, /* tp_as_sequence */
3576 0, /* tp_as_mapping */
3577 (hashfunc)time_hash, /* tp_hash */
3578 0, /* tp_call */
3579 (reprfunc)time_str, /* tp_str */
3580 PyObject_GenericGetAttr, /* tp_getattro */
3581 0, /* tp_setattro */
3582 0, /* tp_as_buffer */
3583 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
3584 Py_TPFLAGS_BASETYPE, /* tp_flags */
3585 time_doc, /* tp_doc */
3586 0, /* tp_traverse */
3587 0, /* tp_clear */
3588 (richcmpfunc)time_richcompare, /* tp_richcompare */
3589 0, /* tp_weaklistoffset */
3590 0, /* tp_iter */
3591 0, /* tp_iternext */
3592 time_methods, /* tp_methods */
3593 0, /* tp_members */
3594 time_getset, /* tp_getset */
3595 0, /* tp_base */
3596 0, /* tp_dict */
3597 0, /* tp_descr_get */
3598 0, /* tp_descr_set */
3599 0, /* tp_dictoffset */
3600 0, /* tp_init */
3601 time_alloc, /* tp_alloc */
3602 time_new, /* tp_new */
3603 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00003604};
3605
3606/*
Tim Petersa9bc1682003-01-11 03:39:11 +00003607 * PyDateTime_DateTime implementation.
Tim Peters2a799bf2002-12-16 20:18:38 +00003608 */
3609
Tim Petersa9bc1682003-01-11 03:39:11 +00003610/* Accessor properties. Properties for day, month, and year are inherited
3611 * from date.
Tim Peters2a799bf2002-12-16 20:18:38 +00003612 */
3613
3614static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003615datetime_hour(PyDateTime_DateTime *self, void *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00003616{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003617 return PyInt_FromLong(DATE_GET_HOUR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00003618}
3619
Tim Petersa9bc1682003-01-11 03:39:11 +00003620static PyObject *
3621datetime_minute(PyDateTime_DateTime *self, void *unused)
3622{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003623 return PyInt_FromLong(DATE_GET_MINUTE(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00003624}
3625
3626static PyObject *
3627datetime_second(PyDateTime_DateTime *self, void *unused)
3628{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003629 return PyInt_FromLong(DATE_GET_SECOND(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00003630}
3631
3632static PyObject *
3633datetime_microsecond(PyDateTime_DateTime *self, void *unused)
3634{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003635 return PyInt_FromLong(DATE_GET_MICROSECOND(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00003636}
3637
3638static PyObject *
3639datetime_tzinfo(PyDateTime_DateTime *self, void *unused)
3640{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003641 PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
3642 Py_INCREF(result);
3643 return result;
Tim Petersa9bc1682003-01-11 03:39:11 +00003644}
3645
3646static PyGetSetDef datetime_getset[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003647 {"hour", (getter)datetime_hour},
3648 {"minute", (getter)datetime_minute},
3649 {"second", (getter)datetime_second},
3650 {"microsecond", (getter)datetime_microsecond},
3651 {"tzinfo", (getter)datetime_tzinfo},
3652 {NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00003653};
3654
3655/*
3656 * Constructors.
Tim Peters2a799bf2002-12-16 20:18:38 +00003657 */
3658
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003659static char *datetime_kws[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003660 "year", "month", "day", "hour", "minute", "second",
3661 "microsecond", "tzinfo", NULL
Tim Peters12bf3392002-12-24 05:41:27 +00003662};
3663
Tim Peters2a799bf2002-12-16 20:18:38 +00003664static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003665datetime_new(PyTypeObject *type, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003666{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003667 PyObject *self = NULL;
3668 PyObject *state;
3669 int year;
3670 int month;
3671 int day;
3672 int hour = 0;
3673 int minute = 0;
3674 int second = 0;
3675 int usecond = 0;
3676 PyObject *tzinfo = Py_None;
Tim Peters2a799bf2002-12-16 20:18:38 +00003677
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003678 /* Check for invocation from pickle with __getstate__ state */
3679 if (PyTuple_GET_SIZE(args) >= 1 &&
3680 PyTuple_GET_SIZE(args) <= 2 &&
3681 PyString_Check(state = PyTuple_GET_ITEM(args, 0)) &&
3682 PyString_GET_SIZE(state) == _PyDateTime_DATETIME_DATASIZE &&
3683 MONTH_IS_SANE(PyString_AS_STRING(state)[2]))
3684 {
3685 PyDateTime_DateTime *me;
3686 char aware;
Tim Peters70533e22003-02-01 04:40:04 +00003687
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003688 if (PyTuple_GET_SIZE(args) == 2) {
3689 tzinfo = PyTuple_GET_ITEM(args, 1);
3690 if (check_tzinfo_subclass(tzinfo) < 0) {
3691 PyErr_SetString(PyExc_TypeError, "bad "
3692 "tzinfo state arg");
3693 return NULL;
3694 }
3695 }
3696 aware = (char)(tzinfo != Py_None);
3697 me = (PyDateTime_DateTime *) (type->tp_alloc(type , aware));
3698 if (me != NULL) {
3699 char *pdata = PyString_AS_STRING(state);
Tim Peters70533e22003-02-01 04:40:04 +00003700
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003701 memcpy(me->data, pdata, _PyDateTime_DATETIME_DATASIZE);
3702 me->hashcode = -1;
3703 me->hastzinfo = aware;
3704 if (aware) {
3705 Py_INCREF(tzinfo);
3706 me->tzinfo = tzinfo;
3707 }
3708 }
3709 return (PyObject *)me;
3710 }
Guido van Rossum177e41a2003-01-30 22:06:23 +00003711
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003712 if (PyArg_ParseTupleAndKeywords(args, kw, "iii|iiiiO", datetime_kws,
3713 &year, &month, &day, &hour, &minute,
3714 &second, &usecond, &tzinfo)) {
3715 if (check_date_args(year, month, day) < 0)
3716 return NULL;
3717 if (check_time_args(hour, minute, second, usecond) < 0)
3718 return NULL;
3719 if (check_tzinfo_subclass(tzinfo) < 0)
3720 return NULL;
3721 self = new_datetime_ex(year, month, day,
3722 hour, minute, second, usecond,
3723 tzinfo, type);
3724 }
3725 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00003726}
3727
Tim Petersa9bc1682003-01-11 03:39:11 +00003728/* TM_FUNC is the shared type of localtime() and gmtime(). */
3729typedef struct tm *(*TM_FUNC)(const time_t *timer);
3730
3731/* Internal helper.
3732 * Build datetime from a time_t and a distinct count of microseconds.
3733 * Pass localtime or gmtime for f, to control the interpretation of timet.
3734 */
3735static PyObject *
3736datetime_from_timet_and_us(PyObject *cls, TM_FUNC f, time_t timet, int us,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003737 PyObject *tzinfo)
Tim Petersa9bc1682003-01-11 03:39:11 +00003738{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003739 struct tm *tm;
3740 PyObject *result = NULL;
Tim Petersa9bc1682003-01-11 03:39:11 +00003741
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003742 tm = f(&timet);
3743 if (tm) {
3744 /* The platform localtime/gmtime may insert leap seconds,
3745 * indicated by tm->tm_sec > 59. We don't care about them,
3746 * except to the extent that passing them on to the datetime
3747 * constructor would raise ValueError for a reason that
3748 * made no sense to the user.
3749 */
3750 if (tm->tm_sec > 59)
3751 tm->tm_sec = 59;
3752 result = PyObject_CallFunction(cls, "iiiiiiiO",
3753 tm->tm_year + 1900,
3754 tm->tm_mon + 1,
3755 tm->tm_mday,
3756 tm->tm_hour,
3757 tm->tm_min,
3758 tm->tm_sec,
3759 us,
3760 tzinfo);
3761 }
3762 else
3763 PyErr_SetString(PyExc_ValueError,
3764 "timestamp out of range for "
3765 "platform localtime()/gmtime() function");
3766 return result;
Tim Petersa9bc1682003-01-11 03:39:11 +00003767}
3768
3769/* Internal helper.
3770 * Build datetime from a Python timestamp. Pass localtime or gmtime for f,
3771 * to control the interpretation of the timestamp. Since a double doesn't
3772 * have enough bits to cover a datetime's full range of precision, it's
3773 * better to call datetime_from_timet_and_us provided you have a way
3774 * to get that much precision (e.g., C time() isn't good enough).
3775 */
3776static PyObject *
3777datetime_from_timestamp(PyObject *cls, TM_FUNC f, double timestamp,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003778 PyObject *tzinfo)
Tim Petersa9bc1682003-01-11 03:39:11 +00003779{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003780 time_t timet;
3781 double fraction;
3782 int us;
Tim Petersa9bc1682003-01-11 03:39:11 +00003783
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003784 timet = _PyTime_DoubleToTimet(timestamp);
3785 if (timet == (time_t)-1 && PyErr_Occurred())
3786 return NULL;
3787 fraction = timestamp - (double)timet;
3788 us = (int)round_to_long(fraction * 1e6);
3789 if (us < 0) {
3790 /* Truncation towards zero is not what we wanted
3791 for negative numbers (Python's mod semantics) */
3792 timet -= 1;
3793 us += 1000000;
3794 }
3795 /* If timestamp is less than one microsecond smaller than a
3796 * full second, round up. Otherwise, ValueErrors are raised
3797 * for some floats. */
3798 if (us == 1000000) {
3799 timet += 1;
3800 us = 0;
3801 }
3802 return datetime_from_timet_and_us(cls, f, timet, us, tzinfo);
Tim Petersa9bc1682003-01-11 03:39:11 +00003803}
3804
3805/* Internal helper.
3806 * Build most accurate possible datetime for current time. Pass localtime or
3807 * gmtime for f as appropriate.
3808 */
3809static PyObject *
3810datetime_best_possible(PyObject *cls, TM_FUNC f, PyObject *tzinfo)
3811{
3812#ifdef HAVE_GETTIMEOFDAY
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003813 struct timeval t;
Tim Petersa9bc1682003-01-11 03:39:11 +00003814
3815#ifdef GETTIMEOFDAY_NO_TZ
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003816 gettimeofday(&t);
Tim Petersa9bc1682003-01-11 03:39:11 +00003817#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003818 gettimeofday(&t, (struct timezone *)NULL);
Tim Petersa9bc1682003-01-11 03:39:11 +00003819#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003820 return datetime_from_timet_and_us(cls, f, t.tv_sec, (int)t.tv_usec,
3821 tzinfo);
Tim Petersa9bc1682003-01-11 03:39:11 +00003822
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003823#else /* ! HAVE_GETTIMEOFDAY */
3824 /* No flavor of gettimeofday exists on this platform. Python's
3825 * time.time() does a lot of other platform tricks to get the
3826 * best time it can on the platform, and we're not going to do
3827 * better than that (if we could, the better code would belong
3828 * in time.time()!) We're limited by the precision of a double,
3829 * though.
3830 */
3831 PyObject *time;
3832 double dtime;
Tim Petersa9bc1682003-01-11 03:39:11 +00003833
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003834 time = time_time();
3835 if (time == NULL)
3836 return NULL;
3837 dtime = PyFloat_AsDouble(time);
3838 Py_DECREF(time);
3839 if (dtime == -1.0 && PyErr_Occurred())
3840 return NULL;
3841 return datetime_from_timestamp(cls, f, dtime, tzinfo);
3842#endif /* ! HAVE_GETTIMEOFDAY */
Tim Petersa9bc1682003-01-11 03:39:11 +00003843}
3844
Tim Peters2a799bf2002-12-16 20:18:38 +00003845/* Return best possible local time -- this isn't constrained by the
3846 * precision of a timestamp.
3847 */
3848static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003849datetime_now(PyObject *cls, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003850{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003851 PyObject *self;
3852 PyObject *tzinfo = Py_None;
3853 static char *keywords[] = {"tz", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00003854
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003855 if (! PyArg_ParseTupleAndKeywords(args, kw, "|O:now", keywords,
3856 &tzinfo))
3857 return NULL;
3858 if (check_tzinfo_subclass(tzinfo) < 0)
3859 return NULL;
Tim Peters10cadce2003-01-23 19:58:02 +00003860
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003861 self = datetime_best_possible(cls,
3862 tzinfo == Py_None ? localtime : gmtime,
3863 tzinfo);
3864 if (self != NULL && tzinfo != Py_None) {
3865 /* Convert UTC to tzinfo's zone. */
3866 PyObject *temp = self;
3867 self = PyObject_CallMethod(tzinfo, "fromutc", "O", self);
3868 Py_DECREF(temp);
3869 }
3870 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00003871}
3872
Tim Petersa9bc1682003-01-11 03:39:11 +00003873/* Return best possible UTC time -- this isn't constrained by the
3874 * precision of a timestamp.
3875 */
3876static PyObject *
3877datetime_utcnow(PyObject *cls, PyObject *dummy)
3878{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003879 return datetime_best_possible(cls, gmtime, Py_None);
Tim Petersa9bc1682003-01-11 03:39:11 +00003880}
3881
Tim Peters2a799bf2002-12-16 20:18:38 +00003882/* Return new local datetime from timestamp (Python timestamp -- a double). */
3883static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003884datetime_fromtimestamp(PyObject *cls, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003885{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003886 PyObject *self;
3887 double timestamp;
3888 PyObject *tzinfo = Py_None;
3889 static char *keywords[] = {"timestamp", "tz", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00003890
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003891 if (! PyArg_ParseTupleAndKeywords(args, kw, "d|O:fromtimestamp",
3892 keywords, &timestamp, &tzinfo))
3893 return NULL;
3894 if (check_tzinfo_subclass(tzinfo) < 0)
3895 return NULL;
Tim Peters2a44a8d2003-01-23 20:53:10 +00003896
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003897 self = datetime_from_timestamp(cls,
3898 tzinfo == Py_None ? localtime : gmtime,
3899 timestamp,
3900 tzinfo);
3901 if (self != NULL && tzinfo != Py_None) {
3902 /* Convert UTC to tzinfo's zone. */
3903 PyObject *temp = self;
3904 self = PyObject_CallMethod(tzinfo, "fromutc", "O", self);
3905 Py_DECREF(temp);
3906 }
3907 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00003908}
3909
Tim Petersa9bc1682003-01-11 03:39:11 +00003910/* Return new UTC datetime from timestamp (Python timestamp -- a double). */
3911static PyObject *
3912datetime_utcfromtimestamp(PyObject *cls, PyObject *args)
3913{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003914 double timestamp;
3915 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00003916
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003917 if (PyArg_ParseTuple(args, "d:utcfromtimestamp", &timestamp))
3918 result = datetime_from_timestamp(cls, gmtime, timestamp,
3919 Py_None);
3920 return result;
Tim Petersa9bc1682003-01-11 03:39:11 +00003921}
3922
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003923/* Return new datetime from time.strptime(). */
3924static PyObject *
3925datetime_strptime(PyObject *cls, PyObject *args)
3926{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003927 static PyObject *module = NULL;
3928 PyObject *result = NULL, *obj, *st = NULL, *frac = NULL;
3929 const char *string, *format;
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003930
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003931 if (!PyArg_ParseTuple(args, "ss:strptime", &string, &format))
3932 return NULL;
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003933
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003934 if (module == NULL &&
3935 (module = PyImport_ImportModuleNoBlock("_strptime")) == NULL)
3936 return NULL;
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003937
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003938 /* _strptime._strptime returns a two-element tuple. The first
3939 element is a time.struct_time object. The second is the
3940 microseconds (which are not defined for time.struct_time). */
3941 obj = PyObject_CallMethod(module, "_strptime", "ss", string, format);
3942 if (obj != NULL) {
3943 int i, good_timetuple = 1;
3944 long int ia[7];
3945 if (PySequence_Check(obj) && PySequence_Size(obj) == 2) {
3946 st = PySequence_GetItem(obj, 0);
3947 frac = PySequence_GetItem(obj, 1);
3948 if (st == NULL || frac == NULL)
3949 good_timetuple = 0;
3950 /* copy y/m/d/h/m/s values out of the
3951 time.struct_time */
3952 if (good_timetuple &&
3953 PySequence_Check(st) &&
3954 PySequence_Size(st) >= 6) {
3955 for (i=0; i < 6; i++) {
3956 PyObject *p = PySequence_GetItem(st, i);
3957 if (p == NULL) {
3958 good_timetuple = 0;
3959 break;
3960 }
3961 if (PyInt_Check(p))
3962 ia[i] = PyInt_AsLong(p);
3963 else
3964 good_timetuple = 0;
3965 Py_DECREF(p);
3966 }
3967 }
3968 else
3969 good_timetuple = 0;
3970 /* follow that up with a little dose of microseconds */
3971 if (good_timetuple && PyInt_Check(frac))
3972 ia[6] = PyInt_AsLong(frac);
3973 else
3974 good_timetuple = 0;
3975 }
3976 else
3977 good_timetuple = 0;
3978 if (good_timetuple)
3979 result = PyObject_CallFunction(cls, "iiiiiii",
3980 ia[0], ia[1], ia[2],
3981 ia[3], ia[4], ia[5],
3982 ia[6]);
3983 else
3984 PyErr_SetString(PyExc_ValueError,
3985 "unexpected value from _strptime._strptime");
3986 }
3987 Py_XDECREF(obj);
3988 Py_XDECREF(st);
3989 Py_XDECREF(frac);
3990 return result;
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003991}
3992
Tim Petersa9bc1682003-01-11 03:39:11 +00003993/* Return new datetime from date/datetime and time arguments. */
3994static PyObject *
3995datetime_combine(PyObject *cls, PyObject *args, PyObject *kw)
3996{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003997 static char *keywords[] = {"date", "time", NULL};
3998 PyObject *date;
3999 PyObject *time;
4000 PyObject *result = NULL;
Tim Petersa9bc1682003-01-11 03:39:11 +00004001
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004002 if (PyArg_ParseTupleAndKeywords(args, kw, "O!O!:combine", keywords,
4003 &PyDateTime_DateType, &date,
4004 &PyDateTime_TimeType, &time)) {
4005 PyObject *tzinfo = Py_None;
Tim Petersa9bc1682003-01-11 03:39:11 +00004006
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004007 if (HASTZINFO(time))
4008 tzinfo = ((PyDateTime_Time *)time)->tzinfo;
4009 result = PyObject_CallFunction(cls, "iiiiiiiO",
4010 GET_YEAR(date),
4011 GET_MONTH(date),
4012 GET_DAY(date),
4013 TIME_GET_HOUR(time),
4014 TIME_GET_MINUTE(time),
4015 TIME_GET_SECOND(time),
4016 TIME_GET_MICROSECOND(time),
4017 tzinfo);
4018 }
4019 return result;
Tim Petersa9bc1682003-01-11 03:39:11 +00004020}
Tim Peters2a799bf2002-12-16 20:18:38 +00004021
4022/*
4023 * Destructor.
4024 */
4025
4026static void
Tim Petersa9bc1682003-01-11 03:39:11 +00004027datetime_dealloc(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004028{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004029 if (HASTZINFO(self)) {
4030 Py_XDECREF(self->tzinfo);
4031 }
4032 Py_TYPE(self)->tp_free((PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00004033}
4034
4035/*
4036 * Indirect access to tzinfo methods.
4037 */
4038
Tim Peters2a799bf2002-12-16 20:18:38 +00004039/* These are all METH_NOARGS, so don't need to check the arglist. */
4040static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004041datetime_utcoffset(PyDateTime_DateTime *self, PyObject *unused) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004042 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
4043 "utcoffset", (PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00004044}
4045
4046static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004047datetime_dst(PyDateTime_DateTime *self, PyObject *unused) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004048 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
4049 "dst", (PyObject *)self);
Tim Peters855fe882002-12-22 03:43:39 +00004050}
4051
4052static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004053datetime_tzname(PyDateTime_DateTime *self, PyObject *unused) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004054 return call_tzname(HASTZINFO(self) ? self->tzinfo : Py_None,
4055 (PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00004056}
4057
4058/*
Tim Petersa9bc1682003-01-11 03:39:11 +00004059 * datetime arithmetic.
Tim Peters2a799bf2002-12-16 20:18:38 +00004060 */
4061
Tim Petersa9bc1682003-01-11 03:39:11 +00004062/* factor must be 1 (to add) or -1 (to subtract). The result inherits
4063 * the tzinfo state of date.
Tim Peters2a799bf2002-12-16 20:18:38 +00004064 */
4065static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004066add_datetime_timedelta(PyDateTime_DateTime *date, PyDateTime_Delta *delta,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004067 int factor)
Tim Peters2a799bf2002-12-16 20:18:38 +00004068{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004069 /* Note that the C-level additions can't overflow, because of
4070 * invariant bounds on the member values.
4071 */
4072 int year = GET_YEAR(date);
4073 int month = GET_MONTH(date);
4074 int day = GET_DAY(date) + GET_TD_DAYS(delta) * factor;
4075 int hour = DATE_GET_HOUR(date);
4076 int minute = DATE_GET_MINUTE(date);
4077 int second = DATE_GET_SECOND(date) + GET_TD_SECONDS(delta) * factor;
4078 int microsecond = DATE_GET_MICROSECOND(date) +
4079 GET_TD_MICROSECONDS(delta) * factor;
Tim Peters2a799bf2002-12-16 20:18:38 +00004080
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004081 assert(factor == 1 || factor == -1);
4082 if (normalize_datetime(&year, &month, &day,
4083 &hour, &minute, &second, &microsecond) < 0)
4084 return NULL;
4085 else
4086 return new_datetime(year, month, day,
4087 hour, minute, second, microsecond,
4088 HASTZINFO(date) ? date->tzinfo : Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004089}
4090
4091static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004092datetime_add(PyObject *left, PyObject *right)
Tim Peters2a799bf2002-12-16 20:18:38 +00004093{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004094 if (PyDateTime_Check(left)) {
4095 /* datetime + ??? */
4096 if (PyDelta_Check(right))
4097 /* datetime + delta */
4098 return add_datetime_timedelta(
4099 (PyDateTime_DateTime *)left,
4100 (PyDateTime_Delta *)right,
4101 1);
4102 }
4103 else if (PyDelta_Check(left)) {
4104 /* delta + datetime */
4105 return add_datetime_timedelta((PyDateTime_DateTime *) right,
4106 (PyDateTime_Delta *) left,
4107 1);
4108 }
4109 Py_INCREF(Py_NotImplemented);
4110 return Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00004111}
4112
4113static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004114datetime_subtract(PyObject *left, PyObject *right)
Tim Peters2a799bf2002-12-16 20:18:38 +00004115{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004116 PyObject *result = Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00004117
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004118 if (PyDateTime_Check(left)) {
4119 /* datetime - ??? */
4120 if (PyDateTime_Check(right)) {
4121 /* datetime - datetime */
4122 naivety n1, n2;
4123 int offset1, offset2;
4124 int delta_d, delta_s, delta_us;
Tim Peters2a799bf2002-12-16 20:18:38 +00004125
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004126 if (classify_two_utcoffsets(left, &offset1, &n1, left,
4127 right, &offset2, &n2,
4128 right) < 0)
4129 return NULL;
4130 assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
4131 if (n1 != n2) {
4132 PyErr_SetString(PyExc_TypeError,
4133 "can't subtract offset-naive and "
4134 "offset-aware datetimes");
4135 return NULL;
4136 }
4137 delta_d = ymd_to_ord(GET_YEAR(left),
4138 GET_MONTH(left),
4139 GET_DAY(left)) -
4140 ymd_to_ord(GET_YEAR(right),
4141 GET_MONTH(right),
4142 GET_DAY(right));
4143 /* These can't overflow, since the values are
4144 * normalized. At most this gives the number of
4145 * seconds in one day.
4146 */
4147 delta_s = (DATE_GET_HOUR(left) -
4148 DATE_GET_HOUR(right)) * 3600 +
4149 (DATE_GET_MINUTE(left) -
4150 DATE_GET_MINUTE(right)) * 60 +
4151 (DATE_GET_SECOND(left) -
4152 DATE_GET_SECOND(right));
4153 delta_us = DATE_GET_MICROSECOND(left) -
4154 DATE_GET_MICROSECOND(right);
4155 /* (left - offset1) - (right - offset2) =
4156 * (left - right) + (offset2 - offset1)
4157 */
4158 delta_s += (offset2 - offset1) * 60;
4159 result = new_delta(delta_d, delta_s, delta_us, 1);
4160 }
4161 else if (PyDelta_Check(right)) {
4162 /* datetime - delta */
4163 result = add_datetime_timedelta(
4164 (PyDateTime_DateTime *)left,
4165 (PyDateTime_Delta *)right,
4166 -1);
4167 }
4168 }
Tim Peters2a799bf2002-12-16 20:18:38 +00004169
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004170 if (result == Py_NotImplemented)
4171 Py_INCREF(result);
4172 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00004173}
4174
4175/* Various ways to turn a datetime into a string. */
4176
4177static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004178datetime_repr(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004179{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004180 char buffer[1000];
4181 const char *type_name = Py_TYPE(self)->tp_name;
4182 PyObject *baserepr;
Tim Peters2a799bf2002-12-16 20:18:38 +00004183
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004184 if (DATE_GET_MICROSECOND(self)) {
4185 PyOS_snprintf(buffer, sizeof(buffer),
4186 "%s(%d, %d, %d, %d, %d, %d, %d)",
4187 type_name,
4188 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4189 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4190 DATE_GET_SECOND(self),
4191 DATE_GET_MICROSECOND(self));
4192 }
4193 else if (DATE_GET_SECOND(self)) {
4194 PyOS_snprintf(buffer, sizeof(buffer),
4195 "%s(%d, %d, %d, %d, %d, %d)",
4196 type_name,
4197 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4198 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4199 DATE_GET_SECOND(self));
4200 }
4201 else {
4202 PyOS_snprintf(buffer, sizeof(buffer),
4203 "%s(%d, %d, %d, %d, %d)",
4204 type_name,
4205 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4206 DATE_GET_HOUR(self), DATE_GET_MINUTE(self));
4207 }
4208 baserepr = PyString_FromString(buffer);
4209 if (baserepr == NULL || ! HASTZINFO(self))
4210 return baserepr;
4211 return append_keyword_tzinfo(baserepr, self->tzinfo);
Tim Peters2a799bf2002-12-16 20:18:38 +00004212}
4213
Tim Petersa9bc1682003-01-11 03:39:11 +00004214static PyObject *
4215datetime_str(PyDateTime_DateTime *self)
4216{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004217 return PyObject_CallMethod((PyObject *)self, "isoformat", "(s)", " ");
Tim Petersa9bc1682003-01-11 03:39:11 +00004218}
Tim Peters2a799bf2002-12-16 20:18:38 +00004219
4220static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004221datetime_isoformat(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00004222{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004223 char sep = 'T';
4224 static char *keywords[] = {"sep", NULL};
4225 char buffer[100];
4226 char *cp;
4227 PyObject *result;
Tim Peters2a799bf2002-12-16 20:18:38 +00004228
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004229 if (!PyArg_ParseTupleAndKeywords(args, kw, "|c:isoformat", keywords,
4230 &sep))
4231 return NULL;
4232 cp = isoformat_date((PyDateTime_Date *)self, buffer, sizeof(buffer));
4233 assert(cp != NULL);
4234 *cp++ = sep;
4235 cp = isoformat_time(self, cp, sizeof(buffer) - (cp - buffer));
4236 result = PyString_FromStringAndSize(buffer, cp - buffer);
4237 if (result == NULL || ! HASTZINFO(self))
4238 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00004239
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004240 /* We need to append the UTC offset. */
4241 if (format_utcoffset(buffer, sizeof(buffer), ":", self->tzinfo,
4242 (PyObject *)self) < 0) {
4243 Py_DECREF(result);
4244 return NULL;
4245 }
4246 PyString_ConcatAndDel(&result, PyString_FromString(buffer));
4247 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00004248}
4249
Tim Petersa9bc1682003-01-11 03:39:11 +00004250static PyObject *
4251datetime_ctime(PyDateTime_DateTime *self)
4252{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004253 return format_ctime((PyDateTime_Date *)self,
4254 DATE_GET_HOUR(self),
4255 DATE_GET_MINUTE(self),
4256 DATE_GET_SECOND(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00004257}
4258
Tim Peters2a799bf2002-12-16 20:18:38 +00004259/* Miscellaneous methods. */
4260
Tim Petersa9bc1682003-01-11 03:39:11 +00004261/* This is more natural as a tp_compare, but doesn't work then: for whatever
4262 * reason, Python's try_3way_compare ignores tp_compare unless
4263 * PyInstance_Check returns true, but these aren't old-style classes.
4264 */
4265static PyObject *
4266datetime_richcompare(PyDateTime_DateTime *self, PyObject *other, int op)
4267{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004268 int diff;
4269 naivety n1, n2;
4270 int offset1, offset2;
Tim Petersa9bc1682003-01-11 03:39:11 +00004271
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004272 if (! PyDateTime_Check(other)) {
4273 /* If other has a "timetuple" attr, that's an advertised
4274 * hook for other classes to ask to get comparison control.
4275 * However, date instances have a timetuple attr, and we
4276 * don't want to allow that comparison. Because datetime
4277 * is a subclass of date, when mixing date and datetime
4278 * in a comparison, Python gives datetime the first shot
4279 * (it's the more specific subtype). So we can stop that
4280 * combination here reliably.
4281 */
4282 if (PyObject_HasAttrString(other, "timetuple") &&
4283 ! PyDate_Check(other)) {
4284 /* A hook for other kinds of datetime objects. */
4285 Py_INCREF(Py_NotImplemented);
4286 return Py_NotImplemented;
4287 }
4288 if (op == Py_EQ || op == Py_NE) {
4289 PyObject *result = op == Py_EQ ? Py_False : Py_True;
4290 Py_INCREF(result);
4291 return result;
4292 }
4293 /* Stop this from falling back to address comparison. */
4294 return cmperror((PyObject *)self, other);
4295 }
Tim Petersa9bc1682003-01-11 03:39:11 +00004296
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004297 if (classify_two_utcoffsets((PyObject *)self, &offset1, &n1,
4298 (PyObject *)self,
4299 other, &offset2, &n2,
4300 other) < 0)
4301 return NULL;
4302 assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
4303 /* If they're both naive, or both aware and have the same offsets,
4304 * we get off cheap. Note that if they're both naive, offset1 ==
4305 * offset2 == 0 at this point.
4306 */
4307 if (n1 == n2 && offset1 == offset2) {
4308 diff = memcmp(self->data, ((PyDateTime_DateTime *)other)->data,
4309 _PyDateTime_DATETIME_DATASIZE);
4310 return diff_to_bool(diff, op);
4311 }
Tim Petersa9bc1682003-01-11 03:39:11 +00004312
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004313 if (n1 == OFFSET_AWARE && n2 == OFFSET_AWARE) {
4314 PyDateTime_Delta *delta;
Tim Petersa9bc1682003-01-11 03:39:11 +00004315
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004316 assert(offset1 != offset2); /* else last "if" handled it */
4317 delta = (PyDateTime_Delta *)datetime_subtract((PyObject *)self,
4318 other);
4319 if (delta == NULL)
4320 return NULL;
4321 diff = GET_TD_DAYS(delta);
4322 if (diff == 0)
4323 diff = GET_TD_SECONDS(delta) |
4324 GET_TD_MICROSECONDS(delta);
4325 Py_DECREF(delta);
4326 return diff_to_bool(diff, op);
4327 }
Tim Petersa9bc1682003-01-11 03:39:11 +00004328
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004329 assert(n1 != n2);
4330 PyErr_SetString(PyExc_TypeError,
4331 "can't compare offset-naive and "
4332 "offset-aware datetimes");
4333 return NULL;
Tim Petersa9bc1682003-01-11 03:39:11 +00004334}
4335
4336static long
4337datetime_hash(PyDateTime_DateTime *self)
4338{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004339 if (self->hashcode == -1) {
4340 naivety n;
4341 int offset;
4342 PyObject *temp;
Tim Petersa9bc1682003-01-11 03:39:11 +00004343
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004344 n = classify_utcoffset((PyObject *)self, (PyObject *)self,
4345 &offset);
4346 assert(n != OFFSET_UNKNOWN);
4347 if (n == OFFSET_ERROR)
4348 return -1;
Tim Petersa9bc1682003-01-11 03:39:11 +00004349
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004350 /* Reduce this to a hash of another object. */
4351 if (n == OFFSET_NAIVE)
4352 temp = PyString_FromStringAndSize(
4353 (char *)self->data,
4354 _PyDateTime_DATETIME_DATASIZE);
4355 else {
4356 int days;
4357 int seconds;
Tim Petersa9bc1682003-01-11 03:39:11 +00004358
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004359 assert(n == OFFSET_AWARE);
4360 assert(HASTZINFO(self));
4361 days = ymd_to_ord(GET_YEAR(self),
4362 GET_MONTH(self),
4363 GET_DAY(self));
4364 seconds = DATE_GET_HOUR(self) * 3600 +
4365 (DATE_GET_MINUTE(self) - offset) * 60 +
4366 DATE_GET_SECOND(self);
4367 temp = new_delta(days,
4368 seconds,
4369 DATE_GET_MICROSECOND(self),
4370 1);
4371 }
4372 if (temp != NULL) {
4373 self->hashcode = PyObject_Hash(temp);
4374 Py_DECREF(temp);
4375 }
4376 }
4377 return self->hashcode;
Tim Petersa9bc1682003-01-11 03:39:11 +00004378}
Tim Peters2a799bf2002-12-16 20:18:38 +00004379
4380static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004381datetime_replace(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters12bf3392002-12-24 05:41:27 +00004382{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004383 PyObject *clone;
4384 PyObject *tuple;
4385 int y = GET_YEAR(self);
4386 int m = GET_MONTH(self);
4387 int d = GET_DAY(self);
4388 int hh = DATE_GET_HOUR(self);
4389 int mm = DATE_GET_MINUTE(self);
4390 int ss = DATE_GET_SECOND(self);
4391 int us = DATE_GET_MICROSECOND(self);
4392 PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
Tim Peters12bf3392002-12-24 05:41:27 +00004393
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004394 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiiiiO:replace",
4395 datetime_kws,
4396 &y, &m, &d, &hh, &mm, &ss, &us,
4397 &tzinfo))
4398 return NULL;
4399 tuple = Py_BuildValue("iiiiiiiO", y, m, d, hh, mm, ss, us, tzinfo);
4400 if (tuple == NULL)
4401 return NULL;
4402 clone = datetime_new(Py_TYPE(self), tuple, NULL);
4403 Py_DECREF(tuple);
4404 return clone;
Tim Peters12bf3392002-12-24 05:41:27 +00004405}
4406
4407static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004408datetime_astimezone(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters80475bb2002-12-25 07:40:55 +00004409{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004410 int y, m, d, hh, mm, ss, us;
4411 PyObject *result;
4412 int offset, none;
Tim Peters521fc152002-12-31 17:36:56 +00004413
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004414 PyObject *tzinfo;
4415 static char *keywords[] = {"tz", NULL};
Tim Peters80475bb2002-12-25 07:40:55 +00004416
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004417 if (! PyArg_ParseTupleAndKeywords(args, kw, "O!:astimezone", keywords,
4418 &PyDateTime_TZInfoType, &tzinfo))
4419 return NULL;
Tim Peters80475bb2002-12-25 07:40:55 +00004420
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004421 if (!HASTZINFO(self) || self->tzinfo == Py_None)
4422 goto NeedAware;
Tim Peters521fc152002-12-31 17:36:56 +00004423
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004424 /* Conversion to self's own time zone is a NOP. */
4425 if (self->tzinfo == tzinfo) {
4426 Py_INCREF(self);
4427 return (PyObject *)self;
4428 }
Tim Peters521fc152002-12-31 17:36:56 +00004429
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004430 /* Convert self to UTC. */
4431 offset = call_utcoffset(self->tzinfo, (PyObject *)self, &none);
4432 if (offset == -1 && PyErr_Occurred())
4433 return NULL;
4434 if (none)
4435 goto NeedAware;
Tim Petersf3615152003-01-01 21:51:37 +00004436
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004437 y = GET_YEAR(self);
4438 m = GET_MONTH(self);
4439 d = GET_DAY(self);
4440 hh = DATE_GET_HOUR(self);
4441 mm = DATE_GET_MINUTE(self);
4442 ss = DATE_GET_SECOND(self);
4443 us = DATE_GET_MICROSECOND(self);
Tim Peters52dcce22003-01-23 16:36:11 +00004444
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004445 mm -= offset;
4446 if ((mm < 0 || mm >= 60) &&
4447 normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
4448 return NULL;
Tim Peters52dcce22003-01-23 16:36:11 +00004449
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004450 /* Attach new tzinfo and let fromutc() do the rest. */
4451 result = new_datetime(y, m, d, hh, mm, ss, us, tzinfo);
4452 if (result != NULL) {
4453 PyObject *temp = result;
Tim Peters52dcce22003-01-23 16:36:11 +00004454
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004455 result = PyObject_CallMethod(tzinfo, "fromutc", "O", temp);
4456 Py_DECREF(temp);
4457 }
4458 return result;
Tim Peters521fc152002-12-31 17:36:56 +00004459
Tim Peters52dcce22003-01-23 16:36:11 +00004460NeedAware:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004461 PyErr_SetString(PyExc_ValueError, "astimezone() cannot be applied to "
4462 "a naive datetime");
4463 return NULL;
Tim Peters80475bb2002-12-25 07:40:55 +00004464}
4465
4466static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004467datetime_timetuple(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004468{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004469 int dstflag = -1;
Tim Peters2a799bf2002-12-16 20:18:38 +00004470
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004471 if (HASTZINFO(self) && self->tzinfo != Py_None) {
4472 int none;
Tim Peters2a799bf2002-12-16 20:18:38 +00004473
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004474 dstflag = call_dst(self->tzinfo, (PyObject *)self, &none);
4475 if (dstflag == -1 && PyErr_Occurred())
4476 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004477
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004478 if (none)
4479 dstflag = -1;
4480 else if (dstflag != 0)
4481 dstflag = 1;
Tim Peters2a799bf2002-12-16 20:18:38 +00004482
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004483 }
4484 return build_struct_time(GET_YEAR(self),
4485 GET_MONTH(self),
4486 GET_DAY(self),
4487 DATE_GET_HOUR(self),
4488 DATE_GET_MINUTE(self),
4489 DATE_GET_SECOND(self),
4490 dstflag);
Tim Peters2a799bf2002-12-16 20:18:38 +00004491}
4492
4493static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004494datetime_getdate(PyDateTime_DateTime *self)
4495{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004496 return new_date(GET_YEAR(self),
4497 GET_MONTH(self),
4498 GET_DAY(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00004499}
4500
4501static PyObject *
4502datetime_gettime(PyDateTime_DateTime *self)
4503{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004504 return new_time(DATE_GET_HOUR(self),
4505 DATE_GET_MINUTE(self),
4506 DATE_GET_SECOND(self),
4507 DATE_GET_MICROSECOND(self),
4508 Py_None);
Tim Petersa9bc1682003-01-11 03:39:11 +00004509}
4510
4511static PyObject *
4512datetime_gettimetz(PyDateTime_DateTime *self)
4513{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004514 return new_time(DATE_GET_HOUR(self),
4515 DATE_GET_MINUTE(self),
4516 DATE_GET_SECOND(self),
4517 DATE_GET_MICROSECOND(self),
4518 HASTZINFO(self) ? self->tzinfo : Py_None);
Tim Petersa9bc1682003-01-11 03:39:11 +00004519}
4520
4521static PyObject *
4522datetime_utctimetuple(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004523{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004524 int y = GET_YEAR(self);
4525 int m = GET_MONTH(self);
4526 int d = GET_DAY(self);
4527 int hh = DATE_GET_HOUR(self);
4528 int mm = DATE_GET_MINUTE(self);
4529 int ss = DATE_GET_SECOND(self);
4530 int us = 0; /* microseconds are ignored in a timetuple */
4531 int offset = 0;
Tim Peters2a799bf2002-12-16 20:18:38 +00004532
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004533 if (HASTZINFO(self) && self->tzinfo != Py_None) {
4534 int none;
Tim Peters2a799bf2002-12-16 20:18:38 +00004535
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004536 offset = call_utcoffset(self->tzinfo, (PyObject *)self, &none);
4537 if (offset == -1 && PyErr_Occurred())
4538 return NULL;
4539 }
4540 /* Even if offset is 0, don't call timetuple() -- tm_isdst should be
4541 * 0 in a UTC timetuple regardless of what dst() says.
4542 */
4543 if (offset) {
4544 /* Subtract offset minutes & normalize. */
4545 int stat;
Tim Peters2a799bf2002-12-16 20:18:38 +00004546
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004547 mm -= offset;
4548 stat = normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us);
4549 if (stat < 0) {
4550 /* At the edges, it's possible we overflowed
4551 * beyond MINYEAR or MAXYEAR.
4552 */
4553 if (PyErr_ExceptionMatches(PyExc_OverflowError))
4554 PyErr_Clear();
4555 else
4556 return NULL;
4557 }
4558 }
4559 return build_struct_time(y, m, d, hh, mm, ss, 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00004560}
4561
Tim Peters371935f2003-02-01 01:52:50 +00004562/* Pickle support, a simple use of __reduce__. */
Tim Peters33e0f382003-01-10 02:05:14 +00004563
Tim Petersa9bc1682003-01-11 03:39:11 +00004564/* Let basestate be the non-tzinfo data string.
Tim Peters2a799bf2002-12-16 20:18:38 +00004565 * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
4566 * So it's a tuple in any (non-error) case.
Tim Petersb57f8f02003-02-01 02:54:15 +00004567 * __getstate__ isn't exposed.
Tim Peters2a799bf2002-12-16 20:18:38 +00004568 */
4569static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004570datetime_getstate(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004571{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004572 PyObject *basestate;
4573 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004574
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004575 basestate = PyString_FromStringAndSize((char *)self->data,
4576 _PyDateTime_DATETIME_DATASIZE);
4577 if (basestate != NULL) {
4578 if (! HASTZINFO(self) || self->tzinfo == Py_None)
4579 result = PyTuple_Pack(1, basestate);
4580 else
4581 result = PyTuple_Pack(2, basestate, self->tzinfo);
4582 Py_DECREF(basestate);
4583 }
4584 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00004585}
4586
4587static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00004588datetime_reduce(PyDateTime_DateTime *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00004589{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004590 return Py_BuildValue("(ON)", Py_TYPE(self), datetime_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00004591}
4592
Tim Petersa9bc1682003-01-11 03:39:11 +00004593static PyMethodDef datetime_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00004594
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004595 /* Class methods: */
Tim Peters2a799bf2002-12-16 20:18:38 +00004596
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004597 {"now", (PyCFunction)datetime_now,
4598 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
4599 PyDoc_STR("[tz] -> new datetime with tz's local day and time.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004600
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004601 {"utcnow", (PyCFunction)datetime_utcnow,
4602 METH_NOARGS | METH_CLASS,
4603 PyDoc_STR("Return a new datetime representing UTC day and time.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00004604
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004605 {"fromtimestamp", (PyCFunction)datetime_fromtimestamp,
4606 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
4607 PyDoc_STR("timestamp[, tz] -> tz's local time from POSIX timestamp.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004608
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004609 {"utcfromtimestamp", (PyCFunction)datetime_utcfromtimestamp,
4610 METH_VARARGS | METH_CLASS,
4611 PyDoc_STR("timestamp -> UTC datetime from a POSIX timestamp "
4612 "(like time.time()).")},
Tim Petersa9bc1682003-01-11 03:39:11 +00004613
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004614 {"strptime", (PyCFunction)datetime_strptime,
4615 METH_VARARGS | METH_CLASS,
4616 PyDoc_STR("string, format -> new datetime parsed from a string "
4617 "(like time.strptime()).")},
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004618
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004619 {"combine", (PyCFunction)datetime_combine,
4620 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
4621 PyDoc_STR("date, time -> datetime with same date and time fields")},
Tim Petersa9bc1682003-01-11 03:39:11 +00004622
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004623 /* Instance methods: */
Guido van Rossum177e41a2003-01-30 22:06:23 +00004624
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004625 {"date", (PyCFunction)datetime_getdate, METH_NOARGS,
4626 PyDoc_STR("Return date object with same year, month and day.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00004627
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004628 {"time", (PyCFunction)datetime_gettime, METH_NOARGS,
4629 PyDoc_STR("Return time object with same time but with tzinfo=None.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00004630
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004631 {"timetz", (PyCFunction)datetime_gettimetz, METH_NOARGS,
4632 PyDoc_STR("Return time object with same time and tzinfo.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00004633
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004634 {"ctime", (PyCFunction)datetime_ctime, METH_NOARGS,
4635 PyDoc_STR("Return ctime() style string.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00004636
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004637 {"timetuple", (PyCFunction)datetime_timetuple, METH_NOARGS,
4638 PyDoc_STR("Return time tuple, compatible with time.localtime().")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004639
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004640 {"utctimetuple", (PyCFunction)datetime_utctimetuple, METH_NOARGS,
4641 PyDoc_STR("Return UTC time tuple, compatible with time.localtime().")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004642
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004643 {"isoformat", (PyCFunction)datetime_isoformat, METH_VARARGS | METH_KEYWORDS,
4644 PyDoc_STR("[sep] -> string in ISO 8601 format, "
4645 "YYYY-MM-DDTHH:MM:SS[.mmmmmm][+HH:MM].\n\n"
4646 "sep is used to separate the year from the time, and "
4647 "defaults to 'T'.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004648
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004649 {"utcoffset", (PyCFunction)datetime_utcoffset, METH_NOARGS,
4650 PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004651
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004652 {"tzname", (PyCFunction)datetime_tzname, METH_NOARGS,
4653 PyDoc_STR("Return self.tzinfo.tzname(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004654
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004655 {"dst", (PyCFunction)datetime_dst, METH_NOARGS,
4656 PyDoc_STR("Return self.tzinfo.dst(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004657
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004658 {"replace", (PyCFunction)datetime_replace, METH_VARARGS | METH_KEYWORDS,
4659 PyDoc_STR("Return datetime with new specified fields.")},
Tim Peters12bf3392002-12-24 05:41:27 +00004660
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004661 {"astimezone", (PyCFunction)datetime_astimezone, METH_VARARGS | METH_KEYWORDS,
4662 PyDoc_STR("tz -> convert to local time in new timezone tz\n")},
Tim Peters80475bb2002-12-25 07:40:55 +00004663
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004664 {"__reduce__", (PyCFunction)datetime_reduce, METH_NOARGS,
4665 PyDoc_STR("__reduce__() -> (cls, state)")},
Guido van Rossum177e41a2003-01-30 22:06:23 +00004666
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004667 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00004668};
4669
Tim Petersa9bc1682003-01-11 03:39:11 +00004670static char datetime_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00004671PyDoc_STR("datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]])\n\
4672\n\
4673The year, month and day arguments are required. tzinfo may be None, or an\n\
4674instance of a tzinfo subclass. The remaining arguments may be ints or longs.\n");
Tim Peters2a799bf2002-12-16 20:18:38 +00004675
Tim Petersa9bc1682003-01-11 03:39:11 +00004676static PyNumberMethods datetime_as_number = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004677 datetime_add, /* nb_add */
4678 datetime_subtract, /* nb_subtract */
4679 0, /* nb_multiply */
4680 0, /* nb_divide */
4681 0, /* nb_remainder */
4682 0, /* nb_divmod */
4683 0, /* nb_power */
4684 0, /* nb_negative */
4685 0, /* nb_positive */
4686 0, /* nb_absolute */
4687 0, /* nb_nonzero */
Tim Peters2a799bf2002-12-16 20:18:38 +00004688};
4689
Tim Petersa9bc1682003-01-11 03:39:11 +00004690statichere PyTypeObject PyDateTime_DateTimeType = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004691 PyObject_HEAD_INIT(NULL)
4692 0, /* ob_size */
4693 "datetime.datetime", /* tp_name */
4694 sizeof(PyDateTime_DateTime), /* tp_basicsize */
4695 0, /* tp_itemsize */
4696 (destructor)datetime_dealloc, /* tp_dealloc */
4697 0, /* tp_print */
4698 0, /* tp_getattr */
4699 0, /* tp_setattr */
4700 0, /* tp_compare */
4701 (reprfunc)datetime_repr, /* tp_repr */
4702 &datetime_as_number, /* tp_as_number */
4703 0, /* tp_as_sequence */
4704 0, /* tp_as_mapping */
4705 (hashfunc)datetime_hash, /* tp_hash */
4706 0, /* tp_call */
4707 (reprfunc)datetime_str, /* tp_str */
4708 PyObject_GenericGetAttr, /* tp_getattro */
4709 0, /* tp_setattro */
4710 0, /* tp_as_buffer */
4711 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
4712 Py_TPFLAGS_BASETYPE, /* tp_flags */
4713 datetime_doc, /* tp_doc */
4714 0, /* tp_traverse */
4715 0, /* tp_clear */
4716 (richcmpfunc)datetime_richcompare, /* tp_richcompare */
4717 0, /* tp_weaklistoffset */
4718 0, /* tp_iter */
4719 0, /* tp_iternext */
4720 datetime_methods, /* tp_methods */
4721 0, /* tp_members */
4722 datetime_getset, /* tp_getset */
4723 &PyDateTime_DateType, /* tp_base */
4724 0, /* tp_dict */
4725 0, /* tp_descr_get */
4726 0, /* tp_descr_set */
4727 0, /* tp_dictoffset */
4728 0, /* tp_init */
4729 datetime_alloc, /* tp_alloc */
4730 datetime_new, /* tp_new */
4731 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00004732};
4733
4734/* ---------------------------------------------------------------------------
4735 * Module methods and initialization.
4736 */
4737
4738static PyMethodDef module_methods[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004739 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00004740};
4741
Tim Peters9ddf40b2004-06-20 22:41:32 +00004742/* C API. Clients get at this via PyDateTime_IMPORT, defined in
4743 * datetime.h.
4744 */
4745static PyDateTime_CAPI CAPI = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004746 &PyDateTime_DateType,
4747 &PyDateTime_DateTimeType,
4748 &PyDateTime_TimeType,
4749 &PyDateTime_DeltaType,
4750 &PyDateTime_TZInfoType,
4751 new_date_ex,
4752 new_datetime_ex,
4753 new_time_ex,
4754 new_delta_ex,
4755 datetime_fromtimestamp,
4756 date_fromtimestamp
Tim Peters9ddf40b2004-06-20 22:41:32 +00004757};
4758
4759
Tim Peters2a799bf2002-12-16 20:18:38 +00004760PyMODINIT_FUNC
4761initdatetime(void)
4762{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004763 PyObject *m; /* a module object */
4764 PyObject *d; /* its dict */
4765 PyObject *x;
Tim Peters2a799bf2002-12-16 20:18:38 +00004766
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004767 m = Py_InitModule3("datetime", module_methods,
4768 "Fast implementation of the datetime type.");
4769 if (m == NULL)
4770 return;
Tim Peters2a799bf2002-12-16 20:18:38 +00004771
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004772 if (PyType_Ready(&PyDateTime_DateType) < 0)
4773 return;
4774 if (PyType_Ready(&PyDateTime_DateTimeType) < 0)
4775 return;
4776 if (PyType_Ready(&PyDateTime_DeltaType) < 0)
4777 return;
4778 if (PyType_Ready(&PyDateTime_TimeType) < 0)
4779 return;
4780 if (PyType_Ready(&PyDateTime_TZInfoType) < 0)
4781 return;
Tim Peters2a799bf2002-12-16 20:18:38 +00004782
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004783 /* timedelta values */
4784 d = PyDateTime_DeltaType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00004785
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004786 x = new_delta(0, 0, 1, 0);
4787 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4788 return;
4789 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00004790
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004791 x = new_delta(-MAX_DELTA_DAYS, 0, 0, 0);
4792 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4793 return;
4794 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00004795
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004796 x = new_delta(MAX_DELTA_DAYS, 24*3600-1, 1000000-1, 0);
4797 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4798 return;
4799 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00004800
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004801 /* date values */
4802 d = PyDateTime_DateType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00004803
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004804 x = new_date(1, 1, 1);
4805 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4806 return;
4807 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00004808
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004809 x = new_date(MAXYEAR, 12, 31);
4810 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4811 return;
4812 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00004813
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004814 x = new_delta(1, 0, 0, 0);
4815 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4816 return;
4817 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00004818
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004819 /* time values */
4820 d = PyDateTime_TimeType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00004821
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004822 x = new_time(0, 0, 0, 0, Py_None);
4823 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4824 return;
4825 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00004826
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004827 x = new_time(23, 59, 59, 999999, Py_None);
4828 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4829 return;
4830 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00004831
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004832 x = new_delta(0, 0, 1, 0);
4833 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4834 return;
4835 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00004836
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004837 /* datetime values */
4838 d = PyDateTime_DateTimeType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00004839
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004840 x = new_datetime(1, 1, 1, 0, 0, 0, 0, Py_None);
4841 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4842 return;
4843 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00004844
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004845 x = new_datetime(MAXYEAR, 12, 31, 23, 59, 59, 999999, Py_None);
4846 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4847 return;
4848 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00004849
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004850 x = new_delta(0, 0, 1, 0);
4851 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4852 return;
4853 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00004854
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004855 /* module initialization */
4856 PyModule_AddIntConstant(m, "MINYEAR", MINYEAR);
4857 PyModule_AddIntConstant(m, "MAXYEAR", MAXYEAR);
Tim Peters2a799bf2002-12-16 20:18:38 +00004858
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004859 Py_INCREF(&PyDateTime_DateType);
4860 PyModule_AddObject(m, "date", (PyObject *) &PyDateTime_DateType);
Tim Peters2a799bf2002-12-16 20:18:38 +00004861
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004862 Py_INCREF(&PyDateTime_DateTimeType);
4863 PyModule_AddObject(m, "datetime",
4864 (PyObject *)&PyDateTime_DateTimeType);
Tim Petersa9bc1682003-01-11 03:39:11 +00004865
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004866 Py_INCREF(&PyDateTime_TimeType);
4867 PyModule_AddObject(m, "time", (PyObject *) &PyDateTime_TimeType);
Tim Petersa9bc1682003-01-11 03:39:11 +00004868
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004869 Py_INCREF(&PyDateTime_DeltaType);
4870 PyModule_AddObject(m, "timedelta", (PyObject *) &PyDateTime_DeltaType);
Tim Peters2a799bf2002-12-16 20:18:38 +00004871
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004872 Py_INCREF(&PyDateTime_TZInfoType);
4873 PyModule_AddObject(m, "tzinfo", (PyObject *) &PyDateTime_TZInfoType);
Tim Peters2a799bf2002-12-16 20:18:38 +00004874
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004875 x = PyCapsule_New(&CAPI, PyDateTime_CAPSULE_NAME, NULL);
4876 if (x == NULL)
4877 return;
4878 PyModule_AddObject(m, "datetime_CAPI", x);
Tim Peters9ddf40b2004-06-20 22:41:32 +00004879
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004880 /* A 4-year cycle has an extra leap day over what we'd get from
4881 * pasting together 4 single years.
4882 */
4883 assert(DI4Y == 4 * 365 + 1);
4884 assert(DI4Y == days_before_year(4+1));
Tim Peters2a799bf2002-12-16 20:18:38 +00004885
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004886 /* Similarly, a 400-year cycle has an extra leap day over what we'd
4887 * get from pasting together 4 100-year cycles.
4888 */
4889 assert(DI400Y == 4 * DI100Y + 1);
4890 assert(DI400Y == days_before_year(400+1));
Tim Peters2a799bf2002-12-16 20:18:38 +00004891
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004892 /* OTOH, a 100-year cycle has one fewer leap day than we'd get from
4893 * pasting together 25 4-year cycles.
4894 */
4895 assert(DI100Y == 25 * DI4Y - 1);
4896 assert(DI100Y == days_before_year(100+1));
Tim Peters2a799bf2002-12-16 20:18:38 +00004897
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004898 us_per_us = PyInt_FromLong(1);
4899 us_per_ms = PyInt_FromLong(1000);
4900 us_per_second = PyInt_FromLong(1000000);
4901 us_per_minute = PyInt_FromLong(60000000);
4902 seconds_per_day = PyInt_FromLong(24 * 3600);
4903 if (us_per_us == NULL || us_per_ms == NULL || us_per_second == NULL ||
4904 us_per_minute == NULL || seconds_per_day == NULL)
4905 return;
Tim Peters2a799bf2002-12-16 20:18:38 +00004906
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004907 /* The rest are too big for 32-bit ints, but even
4908 * us_per_week fits in 40 bits, so doubles should be exact.
4909 */
4910 us_per_hour = PyLong_FromDouble(3600000000.0);
4911 us_per_day = PyLong_FromDouble(86400000000.0);
4912 us_per_week = PyLong_FromDouble(604800000000.0);
4913 if (us_per_hour == NULL || us_per_day == NULL || us_per_week == NULL)
4914 return;
Tim Peters2a799bf2002-12-16 20:18:38 +00004915}
Tim Petersf3615152003-01-01 21:51:37 +00004916
4917/* ---------------------------------------------------------------------------
Tim Petersa9bc1682003-01-11 03:39:11 +00004918Some time zone algebra. For a datetime x, let
Tim Petersf3615152003-01-01 21:51:37 +00004919 x.n = x stripped of its timezone -- its naive time.
4920 x.o = x.utcoffset(), and assuming that doesn't raise an exception or
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004921 return None
Tim Petersf3615152003-01-01 21:51:37 +00004922 x.d = x.dst(), and assuming that doesn't raise an exception or
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004923 return None
Tim Petersf3615152003-01-01 21:51:37 +00004924 x.s = x's standard offset, x.o - x.d
4925
4926Now some derived rules, where k is a duration (timedelta).
4927
49281. x.o = x.s + x.d
4929 This follows from the definition of x.s.
4930
Tim Petersc5dc4da2003-01-02 17:55:03 +000049312. If x and y have the same tzinfo member, x.s = y.s.
Tim Petersf3615152003-01-01 21:51:37 +00004932 This is actually a requirement, an assumption we need to make about
4933 sane tzinfo classes.
4934
49353. The naive UTC time corresponding to x is x.n - x.o.
4936 This is again a requirement for a sane tzinfo class.
4937
49384. (x+k).s = x.s
Tim Peters8bb5ad22003-01-24 02:44:45 +00004939 This follows from #2, and that datimetimetz+timedelta preserves tzinfo.
Tim Petersf3615152003-01-01 21:51:37 +00004940
Tim Petersc5dc4da2003-01-02 17:55:03 +000049415. (x+k).n = x.n + k
Tim Petersf3615152003-01-01 21:51:37 +00004942 Again follows from how arithmetic is defined.
4943
Tim Peters8bb5ad22003-01-24 02:44:45 +00004944Now we can explain tz.fromutc(x). Let's assume it's an interesting case
Tim Petersf3615152003-01-01 21:51:37 +00004945(meaning that the various tzinfo methods exist, and don't blow up or return
4946None when called).
4947
Tim Petersa9bc1682003-01-11 03:39:11 +00004948The function wants to return a datetime y with timezone tz, equivalent to x.
Tim Peters8bb5ad22003-01-24 02:44:45 +00004949x is already in UTC.
Tim Petersf3615152003-01-01 21:51:37 +00004950
4951By #3, we want
4952
Tim Peters8bb5ad22003-01-24 02:44:45 +00004953 y.n - y.o = x.n [1]
Tim Petersf3615152003-01-01 21:51:37 +00004954
4955The algorithm starts by attaching tz to x.n, and calling that y. So
4956x.n = y.n at the start. Then it wants to add a duration k to y, so that [1]
4957becomes true; in effect, we want to solve [2] for k:
4958
Tim Peters8bb5ad22003-01-24 02:44:45 +00004959 (y+k).n - (y+k).o = x.n [2]
Tim Petersf3615152003-01-01 21:51:37 +00004960
4961By #1, this is the same as
4962
Tim Peters8bb5ad22003-01-24 02:44:45 +00004963 (y+k).n - ((y+k).s + (y+k).d) = x.n [3]
Tim Petersf3615152003-01-01 21:51:37 +00004964
4965By #5, (y+k).n = y.n + k, which equals x.n + k because x.n=y.n at the start.
4966Substituting that into [3],
4967
Tim Peters8bb5ad22003-01-24 02:44:45 +00004968 x.n + k - (y+k).s - (y+k).d = x.n; the x.n terms cancel, leaving
4969 k - (y+k).s - (y+k).d = 0; rearranging,
4970 k = (y+k).s - (y+k).d; by #4, (y+k).s == y.s, so
4971 k = y.s - (y+k).d
Tim Petersf3615152003-01-01 21:51:37 +00004972
Tim Peters8bb5ad22003-01-24 02:44:45 +00004973On the RHS, (y+k).d can't be computed directly, but y.s can be, and we
4974approximate k by ignoring the (y+k).d term at first. Note that k can't be
4975very large, since all offset-returning methods return a duration of magnitude
4976less than 24 hours. For that reason, if y is firmly in std time, (y+k).d must
4977be 0, so ignoring it has no consequence then.
Tim Petersf3615152003-01-01 21:51:37 +00004978
4979In any case, the new value is
4980
Tim Peters8bb5ad22003-01-24 02:44:45 +00004981 z = y + y.s [4]
Tim Petersf3615152003-01-01 21:51:37 +00004982
Tim Peters8bb5ad22003-01-24 02:44:45 +00004983It's helpful to step back at look at [4] from a higher level: it's simply
4984mapping from UTC to tz's standard time.
Tim Petersc5dc4da2003-01-02 17:55:03 +00004985
4986At this point, if
4987
Tim Peters8bb5ad22003-01-24 02:44:45 +00004988 z.n - z.o = x.n [5]
Tim Petersc5dc4da2003-01-02 17:55:03 +00004989
4990we have an equivalent time, and are almost done. The insecurity here is
Tim Petersf3615152003-01-01 21:51:37 +00004991at the start of daylight time. Picture US Eastern for concreteness. The wall
4992time 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 +00004993sense then. The docs ask that an Eastern tzinfo class consider such a time to
4994be EDT (because it's "after 2"), which is a redundant spelling of 1:MM EST
4995on the day DST starts. We want to return the 1:MM EST spelling because that's
Tim Petersf3615152003-01-01 21:51:37 +00004996the only spelling that makes sense on the local wall clock.
4997
Tim Petersc5dc4da2003-01-02 17:55:03 +00004998In fact, if [5] holds at this point, we do have the standard-time spelling,
4999but that takes a bit of proof. We first prove a stronger result. What's the
5000difference between the LHS and RHS of [5]? Let
Tim Petersf3615152003-01-01 21:51:37 +00005001
Tim Peters8bb5ad22003-01-24 02:44:45 +00005002 diff = x.n - (z.n - z.o) [6]
Tim Petersf3615152003-01-01 21:51:37 +00005003
Tim Petersc5dc4da2003-01-02 17:55:03 +00005004Now
5005 z.n = by [4]
Tim Peters8bb5ad22003-01-24 02:44:45 +00005006 (y + y.s).n = by #5
5007 y.n + y.s = since y.n = x.n
5008 x.n + y.s = since z and y are have the same tzinfo member,
5009 y.s = z.s by #2
5010 x.n + z.s
Tim Petersf3615152003-01-01 21:51:37 +00005011
Tim Petersc5dc4da2003-01-02 17:55:03 +00005012Plugging that back into [6] gives
Tim Petersf3615152003-01-01 21:51:37 +00005013
Tim Petersc5dc4da2003-01-02 17:55:03 +00005014 diff =
Tim Peters8bb5ad22003-01-24 02:44:45 +00005015 x.n - ((x.n + z.s) - z.o) = expanding
5016 x.n - x.n - z.s + z.o = cancelling
5017 - z.s + z.o = by #2
Tim Petersc5dc4da2003-01-02 17:55:03 +00005018 z.d
Tim Petersf3615152003-01-01 21:51:37 +00005019
Tim Petersc5dc4da2003-01-02 17:55:03 +00005020So diff = z.d.
Tim Petersf3615152003-01-01 21:51:37 +00005021
Tim Petersc5dc4da2003-01-02 17:55:03 +00005022If [5] is true now, diff = 0, so z.d = 0 too, and we have the standard-time
Tim Peters8bb5ad22003-01-24 02:44:45 +00005023spelling we wanted in the endcase described above. We're done. Contrarily,
5024if z.d = 0, then we have a UTC equivalent, and are also done.
Tim Petersf3615152003-01-01 21:51:37 +00005025
Tim Petersc5dc4da2003-01-02 17:55:03 +00005026If [5] is not true now, diff = z.d != 0, and z.d is the offset we need to
5027add to z (in effect, z is in tz's standard time, and we need to shift the
Tim Peters8bb5ad22003-01-24 02:44:45 +00005028local clock into tz's daylight time).
Tim Petersf3615152003-01-01 21:51:37 +00005029
Tim Petersc5dc4da2003-01-02 17:55:03 +00005030Let
Tim Petersf3615152003-01-01 21:51:37 +00005031
Tim Peters4fede1a2003-01-04 00:26:59 +00005032 z' = z + z.d = z + diff [7]
Tim Petersc3bb26a2003-01-02 03:14:59 +00005033
Tim Peters4fede1a2003-01-04 00:26:59 +00005034and we can again ask whether
Tim Petersc3bb26a2003-01-02 03:14:59 +00005035
Tim Peters8bb5ad22003-01-24 02:44:45 +00005036 z'.n - z'.o = x.n [8]
Tim Petersc3bb26a2003-01-02 03:14:59 +00005037
Tim Peters8bb5ad22003-01-24 02:44:45 +00005038If so, we're done. If not, the tzinfo class is insane, according to the
5039assumptions we've made. This also requires a bit of proof. As before, let's
5040compute the difference between the LHS and RHS of [8] (and skipping some of
5041the justifications for the kinds of substitutions we've done several times
5042already):
Tim Peters4fede1a2003-01-04 00:26:59 +00005043
Tim Peters8bb5ad22003-01-24 02:44:45 +00005044 diff' = x.n - (z'.n - z'.o) = replacing z'.n via [7]
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005045 x.n - (z.n + diff - z'.o) = replacing diff via [6]
5046 x.n - (z.n + x.n - (z.n - z.o) - z'.o) =
5047 x.n - z.n - x.n + z.n - z.o + z'.o = cancel x.n
5048 - z.n + z.n - z.o + z'.o = cancel z.n
5049 - z.o + z'.o = #1 twice
5050 -z.s - z.d + z'.s + z'.d = z and z' have same tzinfo
5051 z'.d - z.d
Tim Peters4fede1a2003-01-04 00:26:59 +00005052
5053So 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 +00005054we've found the UTC-equivalent so are done. In fact, we stop with [7] and
5055return z', not bothering to compute z'.d.
Tim Peters4fede1a2003-01-04 00:26:59 +00005056
Tim Peters8bb5ad22003-01-24 02:44:45 +00005057How could z.d and z'd differ? z' = z + z.d [7], so merely moving z' by
5058a dst() offset, and starting *from* a time already in DST (we know z.d != 0),
5059would have to change the result dst() returns: we start in DST, and moving
5060a little further into it takes us out of DST.
Tim Peters4fede1a2003-01-04 00:26:59 +00005061
Tim Peters8bb5ad22003-01-24 02:44:45 +00005062There isn't a sane case where this can happen. The closest it gets is at
5063the end of DST, where there's an hour in UTC with no spelling in a hybrid
5064tzinfo class. In US Eastern, that's 5:MM UTC = 0:MM EST = 1:MM EDT. During
5065that hour, on an Eastern clock 1:MM is taken as being in standard time (6:MM
5066UTC) because the docs insist on that, but 0:MM is taken as being in daylight
5067time (4:MM UTC). There is no local time mapping to 5:MM UTC. The local
5068clock jumps from 1:59 back to 1:00 again, and repeats the 1:MM hour in
5069standard time. Since that's what the local clock *does*, we want to map both
5070UTC hours 5:MM and 6:MM to 1:MM Eastern. The result is ambiguous
Tim Peters4fede1a2003-01-04 00:26:59 +00005071in local time, but so it goes -- it's the way the local clock works.
5072
Tim Peters8bb5ad22003-01-24 02:44:45 +00005073When x = 5:MM UTC is the input to this algorithm, x.o=0, y.o=-5 and y.d=0,
5074so z=0:MM. z.d=60 (minutes) then, so [5] doesn't hold and we keep going.
5075z' = 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 +00005076(correctly) concludes that z' is not UTC-equivalent to x.
5077
5078Because we know z.d said z was in daylight time (else [5] would have held and
5079we would have stopped then), and we know z.d != z'.d (else [8] would have held
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +00005080and we would have stopped then), and there are only 2 possible values dst() can
Tim Peters4fede1a2003-01-04 00:26:59 +00005081return in Eastern, it follows that z'.d must be 0 (which it is in the example,
5082but the reasoning doesn't depend on the example -- it depends on there being
5083two possible dst() outcomes, one zero and the other non-zero). Therefore
Tim Peters8bb5ad22003-01-24 02:44:45 +00005084z' must be in standard time, and is the spelling we want in this case.
5085
5086Note again that z' is not UTC-equivalent as far as the hybrid tzinfo class is
5087concerned (because it takes z' as being in standard time rather than the
5088daylight time we intend here), but returning it gives the real-life "local
5089clock repeats an hour" behavior when mapping the "unspellable" UTC hour into
5090tz.
5091
5092When the input is 6:MM, z=1:MM and z.d=0, and we stop at once, again with
5093the 1:MM standard time spelling we want.
5094
5095So how can this break? One of the assumptions must be violated. Two
5096possibilities:
5097
50981) [2] effectively says that y.s is invariant across all y belong to a given
5099 time zone. This isn't true if, for political reasons or continental drift,
5100 a region decides to change its base offset from UTC.
5101
51022) There may be versions of "double daylight" time where the tail end of
5103 the analysis gives up a step too early. I haven't thought about that
5104 enough to say.
5105
5106In any case, it's clear that the default fromutc() is strong enough to handle
5107"almost all" time zones: so long as the standard offset is invariant, it
5108doesn't matter if daylight time transition points change from year to year, or
5109if daylight time is skipped in some years; it doesn't matter how large or
5110small dst() may get within its bounds; and it doesn't even matter if some
5111perverse time zone returns a negative dst()). So a breaking case must be
5112pretty bizarre, and a tzinfo subclass can override fromutc() if it is.
Tim Petersf3615152003-01-01 21:51:37 +00005113--------------------------------------------------------------------------- */