blob: 0f6b68f60f25c84ccd8899d251efeafc60579d93 [file] [log] [blame]
Tim Peters2a799bf2002-12-16 20:18:38 +00001/* C implementation for the date/time type documented at
2 * http://www.zope.org/Members/fdrake/DateTimeWiki/FrontPage
3 */
4
5#include "Python.h"
6#include "modsupport.h"
7#include "structmember.h"
8
9#include <time.h>
10
Tim Peters1b6f7a92004-06-20 02:50:16 +000011#include "timefuncs.h"
Tim Peters9ddf40b2004-06-20 22:41:32 +000012
13/* Differentiate between building the core module and building extension
14 * modules.
15 */
Guido van Rossum360e4b82007-05-14 22:51:27 +000016#ifndef Py_BUILD_CORE
Tim Peters9ddf40b2004-06-20 22:41:32 +000017#define Py_BUILD_CORE
Guido van Rossum360e4b82007-05-14 22:51:27 +000018#endif
Tim Peters2a799bf2002-12-16 20:18:38 +000019#include "datetime.h"
Tim Peters9ddf40b2004-06-20 22:41:32 +000020#undef Py_BUILD_CORE
Tim Peters2a799bf2002-12-16 20:18:38 +000021
22/* We require that C int be at least 32 bits, and use int virtually
23 * everywhere. In just a few cases we use a temp long, where a Python
24 * API returns a C long. In such cases, we have to ensure that the
25 * final result fits in a C int (this can be an issue on 64-bit boxes).
26 */
27#if SIZEOF_INT < 4
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000028# error "datetime.c requires that C int have at least 32 bits"
Tim Peters2a799bf2002-12-16 20:18:38 +000029#endif
30
31#define MINYEAR 1
32#define MAXYEAR 9999
Alexander Belopolskyf03a6162010-05-27 21:42:58 +000033#define MAXORDINAL 3652059 /* date(9999,12,31).toordinal() */
Tim Peters2a799bf2002-12-16 20:18:38 +000034
35/* Nine decimal digits is easy to communicate, and leaves enough room
36 * so that two delta days can be added w/o fear of overflowing a signed
37 * 32-bit int, and with plenty of room left over to absorb any possible
38 * carries from adding seconds.
39 */
40#define MAX_DELTA_DAYS 999999999
41
42/* Rename the long macros in datetime.h to more reasonable short names. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000043#define GET_YEAR PyDateTime_GET_YEAR
44#define GET_MONTH PyDateTime_GET_MONTH
45#define GET_DAY PyDateTime_GET_DAY
46#define DATE_GET_HOUR PyDateTime_DATE_GET_HOUR
47#define DATE_GET_MINUTE PyDateTime_DATE_GET_MINUTE
48#define DATE_GET_SECOND PyDateTime_DATE_GET_SECOND
49#define DATE_GET_MICROSECOND PyDateTime_DATE_GET_MICROSECOND
Tim Peters2a799bf2002-12-16 20:18:38 +000050
51/* Date accessors for date and datetime. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000052#define SET_YEAR(o, v) (((o)->data[0] = ((v) & 0xff00) >> 8), \
53 ((o)->data[1] = ((v) & 0x00ff)))
54#define SET_MONTH(o, v) (PyDateTime_GET_MONTH(o) = (v))
55#define SET_DAY(o, v) (PyDateTime_GET_DAY(o) = (v))
Tim Peters2a799bf2002-12-16 20:18:38 +000056
57/* Date/Time accessors for datetime. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000058#define DATE_SET_HOUR(o, v) (PyDateTime_DATE_GET_HOUR(o) = (v))
59#define DATE_SET_MINUTE(o, v) (PyDateTime_DATE_GET_MINUTE(o) = (v))
60#define DATE_SET_SECOND(o, v) (PyDateTime_DATE_GET_SECOND(o) = (v))
61#define DATE_SET_MICROSECOND(o, v) \
62 (((o)->data[7] = ((v) & 0xff0000) >> 16), \
63 ((o)->data[8] = ((v) & 0x00ff00) >> 8), \
64 ((o)->data[9] = ((v) & 0x0000ff)))
Tim Peters2a799bf2002-12-16 20:18:38 +000065
66/* Time accessors for time. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000067#define TIME_GET_HOUR PyDateTime_TIME_GET_HOUR
68#define TIME_GET_MINUTE PyDateTime_TIME_GET_MINUTE
69#define TIME_GET_SECOND PyDateTime_TIME_GET_SECOND
70#define TIME_GET_MICROSECOND PyDateTime_TIME_GET_MICROSECOND
71#define TIME_SET_HOUR(o, v) (PyDateTime_TIME_GET_HOUR(o) = (v))
72#define TIME_SET_MINUTE(o, v) (PyDateTime_TIME_GET_MINUTE(o) = (v))
73#define TIME_SET_SECOND(o, v) (PyDateTime_TIME_GET_SECOND(o) = (v))
74#define TIME_SET_MICROSECOND(o, v) \
75 (((o)->data[3] = ((v) & 0xff0000) >> 16), \
76 ((o)->data[4] = ((v) & 0x00ff00) >> 8), \
77 ((o)->data[5] = ((v) & 0x0000ff)))
Tim Peters2a799bf2002-12-16 20:18:38 +000078
79/* Delta accessors for timedelta. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000080#define GET_TD_DAYS(o) (((PyDateTime_Delta *)(o))->days)
81#define GET_TD_SECONDS(o) (((PyDateTime_Delta *)(o))->seconds)
82#define GET_TD_MICROSECONDS(o) (((PyDateTime_Delta *)(o))->microseconds)
Tim Peters2a799bf2002-12-16 20:18:38 +000083
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000084#define SET_TD_DAYS(o, v) ((o)->days = (v))
85#define SET_TD_SECONDS(o, v) ((o)->seconds = (v))
Tim Peters2a799bf2002-12-16 20:18:38 +000086#define SET_TD_MICROSECONDS(o, v) ((o)->microseconds = (v))
87
Tim Petersa032d2e2003-01-11 00:15:54 +000088/* p is a pointer to a time or a datetime object; HASTZINFO(p) returns
89 * p->hastzinfo.
90 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000091#define HASTZINFO(p) (((_PyDateTime_BaseTZInfo *)(p))->hastzinfo)
Tim Petersa032d2e2003-01-11 00:15:54 +000092
Tim Peters3f606292004-03-21 23:38:41 +000093/* M is a char or int claiming to be a valid month. The macro is equivalent
94 * to the two-sided Python test
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000095 * 1 <= M <= 12
Tim Peters3f606292004-03-21 23:38:41 +000096 */
97#define MONTH_IS_SANE(M) ((unsigned int)(M) - 1 < 12)
98
Tim Peters2a799bf2002-12-16 20:18:38 +000099/* Forward declarations. */
100static PyTypeObject PyDateTime_DateType;
101static PyTypeObject PyDateTime_DateTimeType;
Tim Peters2a799bf2002-12-16 20:18:38 +0000102static PyTypeObject PyDateTime_DeltaType;
103static PyTypeObject PyDateTime_TimeType;
104static PyTypeObject PyDateTime_TZInfoType;
Tim Peters2a799bf2002-12-16 20:18:38 +0000105
106/* ---------------------------------------------------------------------------
107 * Math utilities.
108 */
109
110/* k = i+j overflows iff k differs in sign from both inputs,
111 * iff k^i has sign bit set and k^j has sign bit set,
112 * iff (k^i)&(k^j) has sign bit set.
113 */
114#define SIGNED_ADD_OVERFLOWED(RESULT, I, J) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000115 ((((RESULT) ^ (I)) & ((RESULT) ^ (J))) < 0)
Tim Peters2a799bf2002-12-16 20:18:38 +0000116
117/* Compute Python divmod(x, y), returning the quotient and storing the
118 * remainder into *r. The quotient is the floor of x/y, and that's
119 * the real point of this. C will probably truncate instead (C99
120 * requires truncation; C89 left it implementation-defined).
121 * Simplification: we *require* that y > 0 here. That's appropriate
122 * for all the uses made of it. This simplifies the code and makes
123 * the overflow case impossible (divmod(LONG_MIN, -1) is the only
124 * overflow case).
125 */
126static int
127divmod(int x, int y, int *r)
128{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000129 int quo;
Tim Peters2a799bf2002-12-16 20:18:38 +0000130
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000131 assert(y > 0);
132 quo = x / y;
133 *r = x - quo * y;
134 if (*r < 0) {
135 --quo;
136 *r += y;
137 }
138 assert(0 <= *r && *r < y);
139 return quo;
Tim Peters2a799bf2002-12-16 20:18:38 +0000140}
141
Tim Peters5d644dd2003-01-02 16:32:54 +0000142/* Round a double to the nearest long. |x| must be small enough to fit
143 * in a C long; this is not checked.
144 */
145static long
146round_to_long(double x)
147{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000148 if (x >= 0.0)
149 x = floor(x + 0.5);
150 else
151 x = ceil(x - 0.5);
152 return (long)x;
Tim Peters5d644dd2003-01-02 16:32:54 +0000153}
154
Tim Peters2a799bf2002-12-16 20:18:38 +0000155/* ---------------------------------------------------------------------------
156 * General calendrical helper functions
157 */
158
159/* For each month ordinal in 1..12, the number of days in that month,
160 * and the number of days before that month in the same year. These
161 * are correct for non-leap years only.
162 */
163static int _days_in_month[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000164 0, /* unused; this vector uses 1-based indexing */
165 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
Tim Peters2a799bf2002-12-16 20:18:38 +0000166};
167
168static int _days_before_month[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000169 0, /* unused; this vector uses 1-based indexing */
170 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
Tim Peters2a799bf2002-12-16 20:18:38 +0000171};
172
173/* year -> 1 if leap year, else 0. */
174static int
175is_leap(int year)
176{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000177 /* Cast year to unsigned. The result is the same either way, but
178 * C can generate faster code for unsigned mod than for signed
179 * mod (especially for % 4 -- a good compiler should just grab
180 * the last 2 bits when the LHS is unsigned).
181 */
182 const unsigned int ayear = (unsigned int)year;
183 return ayear % 4 == 0 && (ayear % 100 != 0 || ayear % 400 == 0);
Tim Peters2a799bf2002-12-16 20:18:38 +0000184}
185
186/* year, month -> number of days in that month in that year */
187static int
188days_in_month(int year, int month)
189{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000190 assert(month >= 1);
191 assert(month <= 12);
192 if (month == 2 && is_leap(year))
193 return 29;
194 else
195 return _days_in_month[month];
Tim Peters2a799bf2002-12-16 20:18:38 +0000196}
197
198/* year, month -> number of days in year preceeding first day of month */
199static int
200days_before_month(int year, int month)
201{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000202 int days;
Tim Peters2a799bf2002-12-16 20:18:38 +0000203
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000204 assert(month >= 1);
205 assert(month <= 12);
206 days = _days_before_month[month];
207 if (month > 2 && is_leap(year))
208 ++days;
209 return days;
Tim Peters2a799bf2002-12-16 20:18:38 +0000210}
211
212/* year -> number of days before January 1st of year. Remember that we
213 * start with year 1, so days_before_year(1) == 0.
214 */
215static int
216days_before_year(int year)
217{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000218 int y = year - 1;
219 /* This is incorrect if year <= 0; we really want the floor
220 * here. But so long as MINYEAR is 1, the smallest year this
221 * can see is 0 (this can happen in some normalization endcases),
222 * so we'll just special-case that.
223 */
224 assert (year >= 0);
225 if (y >= 0)
226 return y*365 + y/4 - y/100 + y/400;
227 else {
228 assert(y == -1);
229 return -366;
230 }
Tim Peters2a799bf2002-12-16 20:18:38 +0000231}
232
233/* Number of days in 4, 100, and 400 year cycles. That these have
234 * the correct values is asserted in the module init function.
235 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000236#define DI4Y 1461 /* days_before_year(5); days in 4 years */
237#define DI100Y 36524 /* days_before_year(101); days in 100 years */
238#define DI400Y 146097 /* days_before_year(401); days in 400 years */
Tim Peters2a799bf2002-12-16 20:18:38 +0000239
240/* ordinal -> year, month, day, considering 01-Jan-0001 as day 1. */
241static void
242ord_to_ymd(int ordinal, int *year, int *month, int *day)
243{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000244 int n, n1, n4, n100, n400, leapyear, preceding;
Tim Peters2a799bf2002-12-16 20:18:38 +0000245
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000246 /* ordinal is a 1-based index, starting at 1-Jan-1. The pattern of
247 * leap years repeats exactly every 400 years. The basic strategy is
248 * to find the closest 400-year boundary at or before ordinal, then
249 * work with the offset from that boundary to ordinal. Life is much
250 * clearer if we subtract 1 from ordinal first -- then the values
251 * of ordinal at 400-year boundaries are exactly those divisible
252 * by DI400Y:
253 *
254 * D M Y n n-1
255 * -- --- ---- ---------- ----------------
256 * 31 Dec -400 -DI400Y -DI400Y -1
257 * 1 Jan -399 -DI400Y +1 -DI400Y 400-year boundary
258 * ...
259 * 30 Dec 000 -1 -2
260 * 31 Dec 000 0 -1
261 * 1 Jan 001 1 0 400-year boundary
262 * 2 Jan 001 2 1
263 * 3 Jan 001 3 2
264 * ...
265 * 31 Dec 400 DI400Y DI400Y -1
266 * 1 Jan 401 DI400Y +1 DI400Y 400-year boundary
267 */
268 assert(ordinal >= 1);
269 --ordinal;
270 n400 = ordinal / DI400Y;
271 n = ordinal % DI400Y;
272 *year = n400 * 400 + 1;
Tim Peters2a799bf2002-12-16 20:18:38 +0000273
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000274 /* Now n is the (non-negative) offset, in days, from January 1 of
275 * year, to the desired date. Now compute how many 100-year cycles
276 * precede n.
277 * Note that it's possible for n100 to equal 4! In that case 4 full
278 * 100-year cycles precede the desired day, which implies the
279 * desired day is December 31 at the end of a 400-year cycle.
280 */
281 n100 = n / DI100Y;
282 n = n % DI100Y;
Tim Peters2a799bf2002-12-16 20:18:38 +0000283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000284 /* Now compute how many 4-year cycles precede it. */
285 n4 = n / DI4Y;
286 n = n % DI4Y;
Tim Peters2a799bf2002-12-16 20:18:38 +0000287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000288 /* And now how many single years. Again n1 can be 4, and again
289 * meaning that the desired day is December 31 at the end of the
290 * 4-year cycle.
291 */
292 n1 = n / 365;
293 n = n % 365;
Tim Peters2a799bf2002-12-16 20:18:38 +0000294
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000295 *year += n100 * 100 + n4 * 4 + n1;
296 if (n1 == 4 || n100 == 4) {
297 assert(n == 0);
298 *year -= 1;
299 *month = 12;
300 *day = 31;
301 return;
302 }
Tim Peters2a799bf2002-12-16 20:18:38 +0000303
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000304 /* Now the year is correct, and n is the offset from January 1. We
305 * find the month via an estimate that's either exact or one too
306 * large.
307 */
308 leapyear = n1 == 3 && (n4 != 24 || n100 == 3);
309 assert(leapyear == is_leap(*year));
310 *month = (n + 50) >> 5;
311 preceding = (_days_before_month[*month] + (*month > 2 && leapyear));
312 if (preceding > n) {
313 /* estimate is too large */
314 *month -= 1;
315 preceding -= days_in_month(*year, *month);
316 }
317 n -= preceding;
318 assert(0 <= n);
319 assert(n < days_in_month(*year, *month));
Tim Peters2a799bf2002-12-16 20:18:38 +0000320
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000321 *day = n + 1;
Tim Peters2a799bf2002-12-16 20:18:38 +0000322}
323
324/* year, month, day -> ordinal, considering 01-Jan-0001 as day 1. */
325static int
326ymd_to_ord(int year, int month, int day)
327{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000328 return days_before_year(year) + days_before_month(year, month) + day;
Tim Peters2a799bf2002-12-16 20:18:38 +0000329}
330
331/* Day of week, where Monday==0, ..., Sunday==6. 1/1/1 was a Monday. */
332static int
333weekday(int year, int month, int day)
334{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000335 return (ymd_to_ord(year, month, day) + 6) % 7;
Tim Peters2a799bf2002-12-16 20:18:38 +0000336}
337
338/* Ordinal of the Monday starting week 1 of the ISO year. Week 1 is the
339 * first calendar week containing a Thursday.
340 */
341static int
342iso_week1_monday(int year)
343{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000344 int first_day = ymd_to_ord(year, 1, 1); /* ord of 1/1 */
345 /* 0 if 1/1 is a Monday, 1 if a Tue, etc. */
346 int first_weekday = (first_day + 6) % 7;
347 /* ordinal of closest Monday at or before 1/1 */
348 int week1_monday = first_day - first_weekday;
Tim Peters2a799bf2002-12-16 20:18:38 +0000349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000350 if (first_weekday > 3) /* if 1/1 was Fri, Sat, Sun */
351 week1_monday += 7;
352 return week1_monday;
Tim Peters2a799bf2002-12-16 20:18:38 +0000353}
354
355/* ---------------------------------------------------------------------------
356 * Range checkers.
357 */
358
359/* Check that -MAX_DELTA_DAYS <= days <= MAX_DELTA_DAYS. If so, return 0.
360 * If not, raise OverflowError and return -1.
361 */
362static int
363check_delta_day_range(int days)
364{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000365 if (-MAX_DELTA_DAYS <= days && days <= MAX_DELTA_DAYS)
366 return 0;
367 PyErr_Format(PyExc_OverflowError,
368 "days=%d; must have magnitude <= %d",
369 days, MAX_DELTA_DAYS);
370 return -1;
Tim Peters2a799bf2002-12-16 20:18:38 +0000371}
372
373/* Check that date arguments are in range. Return 0 if they are. If they
374 * aren't, raise ValueError and return -1.
375 */
376static int
377check_date_args(int year, int month, int day)
378{
379
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000380 if (year < MINYEAR || year > MAXYEAR) {
381 PyErr_SetString(PyExc_ValueError,
382 "year is out of range");
383 return -1;
384 }
385 if (month < 1 || month > 12) {
386 PyErr_SetString(PyExc_ValueError,
387 "month must be in 1..12");
388 return -1;
389 }
390 if (day < 1 || day > days_in_month(year, month)) {
391 PyErr_SetString(PyExc_ValueError,
392 "day is out of range for month");
393 return -1;
394 }
395 return 0;
Tim Peters2a799bf2002-12-16 20:18:38 +0000396}
397
398/* Check that time arguments are in range. Return 0 if they are. If they
399 * aren't, raise ValueError and return -1.
400 */
401static int
402check_time_args(int h, int m, int s, int us)
403{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000404 if (h < 0 || h > 23) {
405 PyErr_SetString(PyExc_ValueError,
406 "hour must be in 0..23");
407 return -1;
408 }
409 if (m < 0 || m > 59) {
410 PyErr_SetString(PyExc_ValueError,
411 "minute must be in 0..59");
412 return -1;
413 }
414 if (s < 0 || s > 59) {
415 PyErr_SetString(PyExc_ValueError,
416 "second must be in 0..59");
417 return -1;
418 }
419 if (us < 0 || us > 999999) {
420 PyErr_SetString(PyExc_ValueError,
421 "microsecond must be in 0..999999");
422 return -1;
423 }
424 return 0;
Tim Peters2a799bf2002-12-16 20:18:38 +0000425}
426
427/* ---------------------------------------------------------------------------
428 * Normalization utilities.
429 */
430
431/* One step of a mixed-radix conversion. A "hi" unit is equivalent to
432 * factor "lo" units. factor must be > 0. If *lo is less than 0, or
433 * at least factor, enough of *lo is converted into "hi" units so that
434 * 0 <= *lo < factor. The input values must be such that int overflow
435 * is impossible.
436 */
437static void
438normalize_pair(int *hi, int *lo, int factor)
439{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000440 assert(factor > 0);
441 assert(lo != hi);
442 if (*lo < 0 || *lo >= factor) {
443 const int num_hi = divmod(*lo, factor, lo);
444 const int new_hi = *hi + num_hi;
445 assert(! SIGNED_ADD_OVERFLOWED(new_hi, *hi, num_hi));
446 *hi = new_hi;
447 }
448 assert(0 <= *lo && *lo < factor);
Tim Peters2a799bf2002-12-16 20:18:38 +0000449}
450
451/* Fiddle days (d), seconds (s), and microseconds (us) so that
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000452 * 0 <= *s < 24*3600
453 * 0 <= *us < 1000000
Tim Peters2a799bf2002-12-16 20:18:38 +0000454 * The input values must be such that the internals don't overflow.
455 * The way this routine is used, we don't get close.
456 */
457static void
458normalize_d_s_us(int *d, int *s, int *us)
459{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000460 if (*us < 0 || *us >= 1000000) {
461 normalize_pair(s, us, 1000000);
462 /* |s| can't be bigger than about
463 * |original s| + |original us|/1000000 now.
464 */
Tim Peters2a799bf2002-12-16 20:18:38 +0000465
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000466 }
467 if (*s < 0 || *s >= 24*3600) {
468 normalize_pair(d, s, 24*3600);
469 /* |d| can't be bigger than about
470 * |original d| +
471 * (|original s| + |original us|/1000000) / (24*3600) now.
472 */
473 }
474 assert(0 <= *s && *s < 24*3600);
475 assert(0 <= *us && *us < 1000000);
Tim Peters2a799bf2002-12-16 20:18:38 +0000476}
477
478/* Fiddle years (y), months (m), and days (d) so that
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000479 * 1 <= *m <= 12
480 * 1 <= *d <= days_in_month(*y, *m)
Tim Peters2a799bf2002-12-16 20:18:38 +0000481 * The input values must be such that the internals don't overflow.
482 * The way this routine is used, we don't get close.
483 */
Alexander Belopolskyf03a6162010-05-27 21:42:58 +0000484static int
Tim Peters2a799bf2002-12-16 20:18:38 +0000485normalize_y_m_d(int *y, int *m, int *d)
486{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000487 int dim; /* # of days in month */
Tim Peters2a799bf2002-12-16 20:18:38 +0000488
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000489 /* This gets muddy: the proper range for day can't be determined
490 * without knowing the correct month and year, but if day is, e.g.,
491 * plus or minus a million, the current month and year values make
492 * no sense (and may also be out of bounds themselves).
493 * Saying 12 months == 1 year should be non-controversial.
494 */
495 if (*m < 1 || *m > 12) {
496 --*m;
497 normalize_pair(y, m, 12);
498 ++*m;
499 /* |y| can't be bigger than about
500 * |original y| + |original m|/12 now.
501 */
502 }
503 assert(1 <= *m && *m <= 12);
Tim Peters2a799bf2002-12-16 20:18:38 +0000504
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000505 /* Now only day can be out of bounds (year may also be out of bounds
506 * for a datetime object, but we don't care about that here).
507 * If day is out of bounds, what to do is arguable, but at least the
508 * method here is principled and explainable.
509 */
510 dim = days_in_month(*y, *m);
511 if (*d < 1 || *d > dim) {
512 /* Move day-1 days from the first of the month. First try to
513 * get off cheap if we're only one day out of range
514 * (adjustments for timezone alone can't be worse than that).
515 */
516 if (*d == 0) {
517 --*m;
518 if (*m > 0)
519 *d = days_in_month(*y, *m);
520 else {
521 --*y;
522 *m = 12;
523 *d = 31;
524 }
525 }
526 else if (*d == dim + 1) {
527 /* move forward a day */
528 ++*m;
529 *d = 1;
530 if (*m > 12) {
531 *m = 1;
532 ++*y;
533 }
534 }
535 else {
536 int ordinal = ymd_to_ord(*y, *m, 1) +
537 *d - 1;
Alexander Belopolskyf03a6162010-05-27 21:42:58 +0000538 if (ordinal < 1 || ordinal > MAXORDINAL) {
539 goto error;
540 } else {
541 ord_to_ymd(ordinal, y, m, d);
542 return 0;
543 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000544 }
545 }
546 assert(*m > 0);
547 assert(*d > 0);
Alexander Belopolskyf03a6162010-05-27 21:42:58 +0000548 if (MINYEAR <= *y && *y <= MAXYEAR)
549 return 0;
550 error:
551 PyErr_SetString(PyExc_OverflowError,
552 "date value out of range");
553 return -1;
554
Tim Peters2a799bf2002-12-16 20:18:38 +0000555}
556
557/* Fiddle out-of-bounds months and days so that the result makes some kind
558 * of sense. The parameters are both inputs and outputs. Returns < 0 on
559 * failure, where failure means the adjusted year is out of bounds.
560 */
561static int
562normalize_date(int *year, int *month, int *day)
563{
Alexander Belopolskyf03a6162010-05-27 21:42:58 +0000564 return normalize_y_m_d(year, month, day);
Tim Peters2a799bf2002-12-16 20:18:38 +0000565}
566
567/* Force all the datetime fields into range. The parameters are both
568 * inputs and outputs. Returns < 0 on error.
569 */
570static int
571normalize_datetime(int *year, int *month, int *day,
572 int *hour, int *minute, int *second,
573 int *microsecond)
574{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000575 normalize_pair(second, microsecond, 1000000);
576 normalize_pair(minute, second, 60);
577 normalize_pair(hour, minute, 60);
578 normalize_pair(day, hour, 24);
579 return normalize_date(year, month, day);
Tim Peters2a799bf2002-12-16 20:18:38 +0000580}
581
582/* ---------------------------------------------------------------------------
Tim Petersb0c854d2003-05-17 15:57:00 +0000583 * Basic object allocation: tp_alloc implementations. These allocate
584 * Python objects of the right size and type, and do the Python object-
585 * initialization bit. If there's not enough memory, they return NULL after
586 * setting MemoryError. All data members remain uninitialized trash.
587 *
588 * We abuse the tp_alloc "nitems" argument to communicate whether a tzinfo
Tim Peters03eaf8b2003-05-18 02:24:46 +0000589 * member is needed. This is ugly, imprecise, and possibly insecure.
590 * tp_basicsize for the time and datetime types is set to the size of the
591 * struct that has room for the tzinfo member, so subclasses in Python will
592 * allocate enough space for a tzinfo member whether or not one is actually
593 * needed. That's the "ugly and imprecise" parts. The "possibly insecure"
594 * part is that PyType_GenericAlloc() (which subclasses in Python end up
595 * using) just happens today to effectively ignore the nitems argument
596 * when tp_itemsize is 0, which it is for these type objects. If that
597 * changes, perhaps the callers of tp_alloc slots in this file should
598 * be changed to force a 0 nitems argument unless the type being allocated
599 * is a base type implemented in this file (so that tp_alloc is time_alloc
600 * or datetime_alloc below, which know about the nitems abuse).
Tim Petersb0c854d2003-05-17 15:57:00 +0000601 */
602
603static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000604time_alloc(PyTypeObject *type, Py_ssize_t aware)
Tim Petersb0c854d2003-05-17 15:57:00 +0000605{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000606 PyObject *self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000607
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000608 self = (PyObject *)
609 PyObject_MALLOC(aware ?
610 sizeof(PyDateTime_Time) :
611 sizeof(_PyDateTime_BaseTime));
612 if (self == NULL)
613 return (PyObject *)PyErr_NoMemory();
614 PyObject_INIT(self, type);
615 return self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000616}
617
618static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000619datetime_alloc(PyTypeObject *type, Py_ssize_t aware)
Tim Petersb0c854d2003-05-17 15:57:00 +0000620{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000621 PyObject *self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000622
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000623 self = (PyObject *)
624 PyObject_MALLOC(aware ?
625 sizeof(PyDateTime_DateTime) :
626 sizeof(_PyDateTime_BaseDateTime));
627 if (self == NULL)
628 return (PyObject *)PyErr_NoMemory();
629 PyObject_INIT(self, type);
630 return self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000631}
632
633/* ---------------------------------------------------------------------------
634 * Helpers for setting object fields. These work on pointers to the
635 * appropriate base class.
636 */
637
638/* For date and datetime. */
639static void
640set_date_fields(PyDateTime_Date *self, int y, int m, int d)
641{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000642 self->hashcode = -1;
643 SET_YEAR(self, y);
644 SET_MONTH(self, m);
645 SET_DAY(self, d);
Tim Petersb0c854d2003-05-17 15:57:00 +0000646}
647
648/* ---------------------------------------------------------------------------
649 * Create various objects, mostly without range checking.
650 */
651
652/* Create a date instance with no range checking. */
653static PyObject *
654new_date_ex(int year, int month, int day, PyTypeObject *type)
655{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000656 PyDateTime_Date *self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000657
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000658 self = (PyDateTime_Date *) (type->tp_alloc(type, 0));
659 if (self != NULL)
660 set_date_fields(self, year, month, day);
661 return (PyObject *) self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000662}
663
664#define new_date(year, month, day) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000665 new_date_ex(year, month, day, &PyDateTime_DateType)
Tim Petersb0c854d2003-05-17 15:57:00 +0000666
667/* Create a datetime instance with no range checking. */
668static PyObject *
669new_datetime_ex(int year, int month, int day, int hour, int minute,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000670 int second, int usecond, PyObject *tzinfo, PyTypeObject *type)
Tim Petersb0c854d2003-05-17 15:57:00 +0000671{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000672 PyDateTime_DateTime *self;
673 char aware = tzinfo != Py_None;
Tim Petersb0c854d2003-05-17 15:57:00 +0000674
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000675 self = (PyDateTime_DateTime *) (type->tp_alloc(type, aware));
676 if (self != NULL) {
677 self->hastzinfo = aware;
678 set_date_fields((PyDateTime_Date *)self, year, month, day);
679 DATE_SET_HOUR(self, hour);
680 DATE_SET_MINUTE(self, minute);
681 DATE_SET_SECOND(self, second);
682 DATE_SET_MICROSECOND(self, usecond);
683 if (aware) {
684 Py_INCREF(tzinfo);
685 self->tzinfo = tzinfo;
686 }
687 }
688 return (PyObject *)self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000689}
690
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000691#define new_datetime(y, m, d, hh, mm, ss, us, tzinfo) \
692 new_datetime_ex(y, m, d, hh, mm, ss, us, tzinfo, \
693 &PyDateTime_DateTimeType)
Tim Petersb0c854d2003-05-17 15:57:00 +0000694
695/* Create a time instance with no range checking. */
696static PyObject *
697new_time_ex(int hour, int minute, int second, int usecond,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000698 PyObject *tzinfo, PyTypeObject *type)
Tim Petersb0c854d2003-05-17 15:57:00 +0000699{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000700 PyDateTime_Time *self;
701 char aware = tzinfo != Py_None;
Tim Petersb0c854d2003-05-17 15:57:00 +0000702
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000703 self = (PyDateTime_Time *) (type->tp_alloc(type, aware));
704 if (self != NULL) {
705 self->hastzinfo = aware;
706 self->hashcode = -1;
707 TIME_SET_HOUR(self, hour);
708 TIME_SET_MINUTE(self, minute);
709 TIME_SET_SECOND(self, second);
710 TIME_SET_MICROSECOND(self, usecond);
711 if (aware) {
712 Py_INCREF(tzinfo);
713 self->tzinfo = tzinfo;
714 }
715 }
716 return (PyObject *)self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000717}
718
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000719#define new_time(hh, mm, ss, us, tzinfo) \
720 new_time_ex(hh, mm, ss, us, tzinfo, &PyDateTime_TimeType)
Tim Petersb0c854d2003-05-17 15:57:00 +0000721
722/* Create a timedelta instance. Normalize the members iff normalize is
723 * true. Passing false is a speed optimization, if you know for sure
724 * that seconds and microseconds are already in their proper ranges. In any
725 * case, raises OverflowError and returns NULL if the normalized days is out
726 * of range).
727 */
728static PyObject *
729new_delta_ex(int days, int seconds, int microseconds, int normalize,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000730 PyTypeObject *type)
Tim Petersb0c854d2003-05-17 15:57:00 +0000731{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000732 PyDateTime_Delta *self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000733
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000734 if (normalize)
735 normalize_d_s_us(&days, &seconds, &microseconds);
736 assert(0 <= seconds && seconds < 24*3600);
737 assert(0 <= microseconds && microseconds < 1000000);
Tim Petersb0c854d2003-05-17 15:57:00 +0000738
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000739 if (check_delta_day_range(days) < 0)
740 return NULL;
Tim Petersb0c854d2003-05-17 15:57:00 +0000741
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000742 self = (PyDateTime_Delta *) (type->tp_alloc(type, 0));
743 if (self != NULL) {
744 self->hashcode = -1;
745 SET_TD_DAYS(self, days);
746 SET_TD_SECONDS(self, seconds);
747 SET_TD_MICROSECONDS(self, microseconds);
748 }
749 return (PyObject *) self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000750}
751
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000752#define new_delta(d, s, us, normalize) \
753 new_delta_ex(d, s, us, normalize, &PyDateTime_DeltaType)
Tim Petersb0c854d2003-05-17 15:57:00 +0000754
755/* ---------------------------------------------------------------------------
Tim Peters2a799bf2002-12-16 20:18:38 +0000756 * tzinfo helpers.
757 */
758
Tim Peters855fe882002-12-22 03:43:39 +0000759/* Ensure that p is None or of a tzinfo subclass. Return 0 if OK; if not
760 * raise TypeError and return -1.
761 */
762static int
763check_tzinfo_subclass(PyObject *p)
764{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000765 if (p == Py_None || PyTZInfo_Check(p))
766 return 0;
767 PyErr_Format(PyExc_TypeError,
768 "tzinfo argument must be None or of a tzinfo subclass, "
769 "not type '%s'",
770 Py_TYPE(p)->tp_name);
771 return -1;
Tim Peters855fe882002-12-22 03:43:39 +0000772}
773
Tim Petersbad8ff02002-12-30 20:52:32 +0000774/* Return tzinfo.methname(tzinfoarg), without any checking of results.
Tim Peters855fe882002-12-22 03:43:39 +0000775 * If tzinfo is None, returns None.
776 */
777static PyObject *
Tim Petersbad8ff02002-12-30 20:52:32 +0000778call_tzinfo_method(PyObject *tzinfo, char *methname, PyObject *tzinfoarg)
Tim Peters855fe882002-12-22 03:43:39 +0000779{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000780 PyObject *result;
Tim Peters855fe882002-12-22 03:43:39 +0000781
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000782 assert(tzinfo && methname && tzinfoarg);
783 assert(check_tzinfo_subclass(tzinfo) >= 0);
784 if (tzinfo == Py_None) {
785 result = Py_None;
786 Py_INCREF(result);
787 }
788 else
789 result = PyObject_CallMethod(tzinfo, methname, "O", tzinfoarg);
790 return result;
Tim Peters855fe882002-12-22 03:43:39 +0000791}
792
Tim Peters2a799bf2002-12-16 20:18:38 +0000793/* If self has a tzinfo member, return a BORROWED reference to it. Else
794 * return NULL, which is NOT AN ERROR. There are no error returns here,
795 * and the caller must not decref the result.
796 */
797static PyObject *
798get_tzinfo_member(PyObject *self)
799{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000800 PyObject *tzinfo = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +0000801
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000802 if (PyDateTime_Check(self) && HASTZINFO(self))
803 tzinfo = ((PyDateTime_DateTime *)self)->tzinfo;
804 else if (PyTime_Check(self) && HASTZINFO(self))
805 tzinfo = ((PyDateTime_Time *)self)->tzinfo;
Tim Peters2a799bf2002-12-16 20:18:38 +0000806
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000807 return tzinfo;
Tim Peters2a799bf2002-12-16 20:18:38 +0000808}
809
Tim Petersbad8ff02002-12-30 20:52:32 +0000810/* Call getattr(tzinfo, name)(tzinfoarg), and extract an int from the
Tim Peters2a799bf2002-12-16 20:18:38 +0000811 * result. tzinfo must be an instance of the tzinfo class. If the method
812 * returns None, this returns 0 and sets *none to 1. If the method doesn't
Tim Peters397301e2003-01-02 21:28:08 +0000813 * return None or timedelta, TypeError is raised and this returns -1. If it
814 * returnsa timedelta and the value is out of range or isn't a whole number
815 * of minutes, ValueError is raised and this returns -1.
Tim Peters2a799bf2002-12-16 20:18:38 +0000816 * Else *none is set to 0 and the integer method result is returned.
817 */
818static int
819call_utc_tzinfo_method(PyObject *tzinfo, char *name, PyObject *tzinfoarg,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000820 int *none)
Tim Peters2a799bf2002-12-16 20:18:38 +0000821{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000822 PyObject *u;
823 int result = -1;
Tim Peters2a799bf2002-12-16 20:18:38 +0000824
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000825 assert(tzinfo != NULL);
826 assert(PyTZInfo_Check(tzinfo));
827 assert(tzinfoarg != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +0000828
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000829 *none = 0;
830 u = call_tzinfo_method(tzinfo, name, tzinfoarg);
831 if (u == NULL)
832 return -1;
Tim Peters2a799bf2002-12-16 20:18:38 +0000833
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000834 else if (u == Py_None) {
835 result = 0;
836 *none = 1;
837 }
838 else if (PyDelta_Check(u)) {
839 const int days = GET_TD_DAYS(u);
840 if (days < -1 || days > 0)
841 result = 24*60; /* trigger ValueError below */
842 else {
843 /* next line can't overflow because we know days
844 * is -1 or 0 now
845 */
846 int ss = days * 24 * 3600 + GET_TD_SECONDS(u);
847 result = divmod(ss, 60, &ss);
848 if (ss || GET_TD_MICROSECONDS(u)) {
849 PyErr_Format(PyExc_ValueError,
850 "tzinfo.%s() must return a "
851 "whole number of minutes",
852 name);
853 result = -1;
854 }
855 }
856 }
857 else {
858 PyErr_Format(PyExc_TypeError,
859 "tzinfo.%s() must return None or "
860 "timedelta, not '%s'",
861 name, Py_TYPE(u)->tp_name);
862 }
Tim Peters2a799bf2002-12-16 20:18:38 +0000863
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000864 Py_DECREF(u);
865 if (result < -1439 || result > 1439) {
866 PyErr_Format(PyExc_ValueError,
867 "tzinfo.%s() returned %d; must be in "
868 "-1439 .. 1439",
869 name, result);
870 result = -1;
871 }
872 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +0000873}
874
875/* Call tzinfo.utcoffset(tzinfoarg), and extract an integer from the
876 * result. tzinfo must be an instance of the tzinfo class. If utcoffset()
877 * returns None, call_utcoffset returns 0 and sets *none to 1. If uctoffset()
Tim Peters397301e2003-01-02 21:28:08 +0000878 * doesn't return None or timedelta, TypeError is raised and this returns -1.
879 * If utcoffset() returns an invalid timedelta (out of range, or not a whole
880 * # of minutes), ValueError is raised and this returns -1. Else *none is
881 * set to 0 and the offset is returned (as int # of minutes east of UTC).
Tim Peters2a799bf2002-12-16 20:18:38 +0000882 */
883static int
884call_utcoffset(PyObject *tzinfo, PyObject *tzinfoarg, int *none)
885{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000886 return call_utc_tzinfo_method(tzinfo, "utcoffset", tzinfoarg, none);
Tim Peters2a799bf2002-12-16 20:18:38 +0000887}
888
Tim Petersbad8ff02002-12-30 20:52:32 +0000889/* Call tzinfo.name(tzinfoarg), and return the offset as a timedelta or None.
890 */
Tim Peters855fe882002-12-22 03:43:39 +0000891static PyObject *
Tim Petersbad8ff02002-12-30 20:52:32 +0000892offset_as_timedelta(PyObject *tzinfo, char *name, PyObject *tzinfoarg) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000893 PyObject *result;
Tim Peters855fe882002-12-22 03:43:39 +0000894
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000895 assert(tzinfo && name && tzinfoarg);
896 if (tzinfo == Py_None) {
897 result = Py_None;
898 Py_INCREF(result);
899 }
900 else {
901 int none;
902 int offset = call_utc_tzinfo_method(tzinfo, name, tzinfoarg,
903 &none);
904 if (offset < 0 && PyErr_Occurred())
905 return NULL;
906 if (none) {
907 result = Py_None;
908 Py_INCREF(result);
909 }
910 else
911 result = new_delta(0, offset * 60, 0, 1);
912 }
913 return result;
Tim Peters855fe882002-12-22 03:43:39 +0000914}
915
Tim Peters2a799bf2002-12-16 20:18:38 +0000916/* Call tzinfo.dst(tzinfoarg), and extract an integer from the
917 * result. tzinfo must be an instance of the tzinfo class. If dst()
918 * returns None, call_dst returns 0 and sets *none to 1. If dst()
Tim Peters397301e2003-01-02 21:28:08 +0000919 & doesn't return None or timedelta, TypeError is raised and this
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000920 * returns -1. If dst() returns an invalid timedelta for a UTC offset,
Tim Peters397301e2003-01-02 21:28:08 +0000921 * ValueError is raised and this returns -1. Else *none is set to 0 and
922 * the offset is returned (as an int # of minutes east of UTC).
Tim Peters2a799bf2002-12-16 20:18:38 +0000923 */
924static int
925call_dst(PyObject *tzinfo, PyObject *tzinfoarg, int *none)
926{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000927 return call_utc_tzinfo_method(tzinfo, "dst", tzinfoarg, none);
Tim Peters2a799bf2002-12-16 20:18:38 +0000928}
929
Tim Petersbad8ff02002-12-30 20:52:32 +0000930/* Call tzinfo.tzname(tzinfoarg), and return the result. tzinfo must be
Tim Peters855fe882002-12-22 03:43:39 +0000931 * an instance of the tzinfo class or None. If tzinfo isn't None, and
Tim Petersbad8ff02002-12-30 20:52:32 +0000932 * tzname() doesn't return None or a string, TypeError is raised and this
Guido van Rossume3d1d412007-05-23 21:24:35 +0000933 * returns NULL. If the result is a string, we ensure it is a Unicode
934 * string.
Tim Peters2a799bf2002-12-16 20:18:38 +0000935 */
936static PyObject *
Tim Petersbad8ff02002-12-30 20:52:32 +0000937call_tzname(PyObject *tzinfo, PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +0000938{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000939 PyObject *result;
Tim Peters2a799bf2002-12-16 20:18:38 +0000940
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000941 assert(tzinfo != NULL);
942 assert(check_tzinfo_subclass(tzinfo) >= 0);
943 assert(tzinfoarg != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +0000944
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000945 if (tzinfo == Py_None) {
946 result = Py_None;
947 Py_INCREF(result);
948 }
949 else
950 result = PyObject_CallMethod(tzinfo, "tzname", "O", tzinfoarg);
Tim Peters855fe882002-12-22 03:43:39 +0000951
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000952 if (result != NULL && result != Py_None) {
953 if (!PyUnicode_Check(result)) {
954 PyErr_Format(PyExc_TypeError, "tzinfo.tzname() must "
955 "return None or a string, not '%s'",
956 Py_TYPE(result)->tp_name);
957 Py_DECREF(result);
958 result = NULL;
959 }
960 else if (!PyUnicode_Check(result)) {
961 PyObject *temp = PyUnicode_FromObject(result);
962 Py_DECREF(result);
963 result = temp;
964 }
965 }
966 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +0000967}
968
969typedef enum {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000970 /* an exception has been set; the caller should pass it on */
971 OFFSET_ERROR,
Tim Peters2a799bf2002-12-16 20:18:38 +0000972
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000973 /* type isn't date, datetime, or time subclass */
974 OFFSET_UNKNOWN,
Tim Peters2a799bf2002-12-16 20:18:38 +0000975
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000976 /* date,
977 * datetime with !hastzinfo
978 * datetime with None tzinfo,
979 * datetime where utcoffset() returns None
980 * time with !hastzinfo
981 * time with None tzinfo,
982 * time where utcoffset() returns None
983 */
984 OFFSET_NAIVE,
Tim Peters2a799bf2002-12-16 20:18:38 +0000985
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000986 /* time or datetime where utcoffset() doesn't return None */
987 OFFSET_AWARE
Tim Peters2a799bf2002-12-16 20:18:38 +0000988} naivety;
989
Tim Peters14b69412002-12-22 18:10:22 +0000990/* Classify an object as to whether it's naive or offset-aware. See
Tim Peters2a799bf2002-12-16 20:18:38 +0000991 * the "naivety" typedef for details. If the type is aware, *offset is set
992 * to minutes east of UTC (as returned by the tzinfo.utcoffset() method).
Tim Peters14b69412002-12-22 18:10:22 +0000993 * If the type is offset-naive (or unknown, or error), *offset is set to 0.
Tim Peterse39a80c2002-12-30 21:28:52 +0000994 * tzinfoarg is the argument to pass to the tzinfo.utcoffset() method.
Tim Peters2a799bf2002-12-16 20:18:38 +0000995 */
996static naivety
Tim Peterse39a80c2002-12-30 21:28:52 +0000997classify_utcoffset(PyObject *op, PyObject *tzinfoarg, int *offset)
Tim Peters2a799bf2002-12-16 20:18:38 +0000998{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000999 int none;
1000 PyObject *tzinfo;
Tim Peters2a799bf2002-12-16 20:18:38 +00001001
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001002 assert(tzinfoarg != NULL);
1003 *offset = 0;
1004 tzinfo = get_tzinfo_member(op); /* NULL means no tzinfo, not error */
1005 if (tzinfo == Py_None)
1006 return OFFSET_NAIVE;
1007 if (tzinfo == NULL) {
1008 /* note that a datetime passes the PyDate_Check test */
1009 return (PyTime_Check(op) || PyDate_Check(op)) ?
1010 OFFSET_NAIVE : OFFSET_UNKNOWN;
1011 }
1012 *offset = call_utcoffset(tzinfo, tzinfoarg, &none);
1013 if (*offset == -1 && PyErr_Occurred())
1014 return OFFSET_ERROR;
1015 return none ? OFFSET_NAIVE : OFFSET_AWARE;
Tim Peters2a799bf2002-12-16 20:18:38 +00001016}
1017
Tim Peters00237032002-12-27 02:21:51 +00001018/* Classify two objects as to whether they're naive or offset-aware.
1019 * This isn't quite the same as calling classify_utcoffset() twice: for
1020 * binary operations (comparison and subtraction), we generally want to
1021 * ignore the tzinfo members if they're identical. This is by design,
1022 * so that results match "naive" expectations when mixing objects from a
1023 * single timezone. So in that case, this sets both offsets to 0 and
1024 * both naiveties to OFFSET_NAIVE.
1025 * The function returns 0 if everything's OK, and -1 on error.
1026 */
1027static int
1028classify_two_utcoffsets(PyObject *o1, int *offset1, naivety *n1,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001029 PyObject *tzinfoarg1,
1030 PyObject *o2, int *offset2, naivety *n2,
1031 PyObject *tzinfoarg2)
Tim Peters00237032002-12-27 02:21:51 +00001032{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001033 if (get_tzinfo_member(o1) == get_tzinfo_member(o2)) {
1034 *offset1 = *offset2 = 0;
1035 *n1 = *n2 = OFFSET_NAIVE;
1036 }
1037 else {
1038 *n1 = classify_utcoffset(o1, tzinfoarg1, offset1);
1039 if (*n1 == OFFSET_ERROR)
1040 return -1;
1041 *n2 = classify_utcoffset(o2, tzinfoarg2, offset2);
1042 if (*n2 == OFFSET_ERROR)
1043 return -1;
1044 }
1045 return 0;
Tim Peters00237032002-12-27 02:21:51 +00001046}
1047
Tim Peters2a799bf2002-12-16 20:18:38 +00001048/* repr is like "someclass(arg1, arg2)". If tzinfo isn't None,
1049 * stuff
1050 * ", tzinfo=" + repr(tzinfo)
1051 * before the closing ")".
1052 */
1053static PyObject *
1054append_keyword_tzinfo(PyObject *repr, PyObject *tzinfo)
1055{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001056 PyObject *temp;
Tim Peters2a799bf2002-12-16 20:18:38 +00001057
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001058 assert(PyUnicode_Check(repr));
1059 assert(tzinfo);
1060 if (tzinfo == Py_None)
1061 return repr;
1062 /* Get rid of the trailing ')'. */
1063 assert(PyUnicode_AS_UNICODE(repr)[PyUnicode_GET_SIZE(repr)-1] == ')');
1064 temp = PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(repr),
1065 PyUnicode_GET_SIZE(repr) - 1);
1066 Py_DECREF(repr);
1067 if (temp == NULL)
1068 return NULL;
1069 repr = PyUnicode_FromFormat("%U, tzinfo=%R)", temp, tzinfo);
1070 Py_DECREF(temp);
1071 return repr;
Tim Peters2a799bf2002-12-16 20:18:38 +00001072}
1073
1074/* ---------------------------------------------------------------------------
1075 * String format helpers.
1076 */
1077
1078static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00001079format_ctime(PyDateTime_Date *date, int hours, int minutes, int seconds)
Tim Peters2a799bf2002-12-16 20:18:38 +00001080{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001081 static const char *DayNames[] = {
1082 "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"
1083 };
1084 static const char *MonthNames[] = {
1085 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
1086 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
1087 };
Tim Peters2a799bf2002-12-16 20:18:38 +00001088
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001089 int wday = weekday(GET_YEAR(date), GET_MONTH(date), GET_DAY(date));
Tim Peters2a799bf2002-12-16 20:18:38 +00001090
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001091 return PyUnicode_FromFormat("%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));
Tim Peters2a799bf2002-12-16 20:18:38 +00001095}
1096
1097/* Add an hours & minutes UTC offset string to buf. buf has no more than
1098 * buflen bytes remaining. The UTC offset is gotten by calling
1099 * tzinfo.uctoffset(tzinfoarg). If that returns None, \0 is stored into
1100 * *buf, and that's all. Else the returned value is checked for sanity (an
1101 * integer in range), and if that's OK it's converted to an hours & minutes
1102 * string of the form
1103 * sign HH sep MM
1104 * Returns 0 if everything is OK. If the return value from utcoffset() is
1105 * bogus, an appropriate exception is set and -1 is returned.
1106 */
1107static int
Tim Peters328fff72002-12-20 01:31:27 +00001108format_utcoffset(char *buf, size_t buflen, const char *sep,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001109 PyObject *tzinfo, PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +00001110{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001111 int offset;
1112 int hours;
1113 int minutes;
1114 char sign;
1115 int none;
Tim Peters2a799bf2002-12-16 20:18:38 +00001116
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001117 assert(buflen >= 1);
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00001118
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001119 offset = call_utcoffset(tzinfo, tzinfoarg, &none);
1120 if (offset == -1 && PyErr_Occurred())
1121 return -1;
1122 if (none) {
1123 *buf = '\0';
1124 return 0;
1125 }
1126 sign = '+';
1127 if (offset < 0) {
1128 sign = '-';
1129 offset = - offset;
1130 }
1131 hours = divmod(offset, 60, &minutes);
1132 PyOS_snprintf(buf, buflen, "%c%02d%s%02d", sign, hours, sep, minutes);
1133 return 0;
Tim Peters2a799bf2002-12-16 20:18:38 +00001134}
1135
Guido van Rossumd8595fe2007-05-23 21:36:49 +00001136static PyObject *
1137make_Zreplacement(PyObject *object, PyObject *tzinfoarg)
1138{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001139 PyObject *temp;
1140 PyObject *tzinfo = get_tzinfo_member(object);
1141 PyObject *Zreplacement = PyUnicode_FromStringAndSize(NULL, 0);
1142 if (Zreplacement == NULL)
1143 return NULL;
1144 if (tzinfo == Py_None || tzinfo == NULL)
1145 return Zreplacement;
Neal Norwitzaea70e02007-08-12 04:32:26 +00001146
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001147 assert(tzinfoarg != NULL);
1148 temp = call_tzname(tzinfo, tzinfoarg);
1149 if (temp == NULL)
1150 goto Error;
1151 if (temp == Py_None) {
1152 Py_DECREF(temp);
1153 return Zreplacement;
1154 }
Neal Norwitzaea70e02007-08-12 04:32:26 +00001155
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001156 assert(PyUnicode_Check(temp));
1157 /* Since the tzname is getting stuffed into the
1158 * format, we have to double any % signs so that
1159 * strftime doesn't treat them as format codes.
1160 */
1161 Py_DECREF(Zreplacement);
1162 Zreplacement = PyObject_CallMethod(temp, "replace", "ss", "%", "%%");
1163 Py_DECREF(temp);
1164 if (Zreplacement == NULL)
1165 return NULL;
1166 if (!PyUnicode_Check(Zreplacement)) {
1167 PyErr_SetString(PyExc_TypeError,
1168 "tzname.replace() did not return a string");
1169 goto Error;
1170 }
1171 return Zreplacement;
Guido van Rossumd8595fe2007-05-23 21:36:49 +00001172
1173 Error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001174 Py_DECREF(Zreplacement);
1175 return NULL;
Guido van Rossumd8595fe2007-05-23 21:36:49 +00001176}
1177
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001178static PyObject *
1179make_freplacement(PyObject *object)
1180{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001181 char freplacement[64];
1182 if (PyTime_Check(object))
1183 sprintf(freplacement, "%06d", TIME_GET_MICROSECOND(object));
1184 else if (PyDateTime_Check(object))
1185 sprintf(freplacement, "%06d", DATE_GET_MICROSECOND(object));
1186 else
1187 sprintf(freplacement, "%06d", 0);
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001188
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001189 return PyBytes_FromStringAndSize(freplacement, strlen(freplacement));
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001190}
1191
Tim Peters2a799bf2002-12-16 20:18:38 +00001192/* I sure don't want to reproduce the strftime code from the time module,
1193 * so this imports the module and calls it. All the hair is due to
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001194 * giving special meanings to the %z, %Z and %f format codes via a
1195 * preprocessing step on the format string.
Tim Petersbad8ff02002-12-30 20:52:32 +00001196 * tzinfoarg is the argument to pass to the object's tzinfo method, if
1197 * needed.
Tim Peters2a799bf2002-12-16 20:18:38 +00001198 */
1199static PyObject *
Tim Petersbad8ff02002-12-30 20:52:32 +00001200wrap_strftime(PyObject *object, PyObject *format, PyObject *timetuple,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001201 PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +00001202{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001203 PyObject *result = NULL; /* guilty until proved innocent */
Tim Peters2a799bf2002-12-16 20:18:38 +00001204
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001205 PyObject *zreplacement = NULL; /* py string, replacement for %z */
1206 PyObject *Zreplacement = NULL; /* py string, replacement for %Z */
1207 PyObject *freplacement = NULL; /* py string, replacement for %f */
Tim Peters2a799bf2002-12-16 20:18:38 +00001208
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001209 const char *pin; /* pointer to next char in input format */
1210 Py_ssize_t flen; /* length of input format */
1211 char ch; /* next char in input format */
Tim Peters2a799bf2002-12-16 20:18:38 +00001212
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001213 PyObject *newfmt = NULL; /* py string, the output format */
1214 char *pnew; /* pointer to available byte in output format */
1215 size_t totalnew; /* number bytes total in output format buffer,
1216 exclusive of trailing \0 */
1217 size_t usednew; /* number bytes used so far in output format buffer */
Tim Peters2a799bf2002-12-16 20:18:38 +00001218
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001219 const char *ptoappend; /* ptr to string to append to output buffer */
1220 Py_ssize_t ntoappend; /* # of bytes to append to output buffer */
Tim Peters2a799bf2002-12-16 20:18:38 +00001221
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001222 assert(object && format && timetuple);
1223 assert(PyUnicode_Check(format));
1224 /* Convert the input format to a C string and size */
1225 pin = _PyUnicode_AsStringAndSize(format, &flen);
1226 if (!pin)
1227 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001228
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001229 /* Give up if the year is before 1900.
1230 * Python strftime() plays games with the year, and different
1231 * games depending on whether envar PYTHON2K is set. This makes
1232 * years before 1900 a nightmare, even if the platform strftime
1233 * supports them (and not all do).
1234 * We could get a lot farther here by avoiding Python's strftime
1235 * wrapper and calling the C strftime() directly, but that isn't
1236 * an option in the Python implementation of this module.
1237 */
1238 {
1239 long year;
1240 PyObject *pyyear = PySequence_GetItem(timetuple, 0);
1241 if (pyyear == NULL) return NULL;
1242 assert(PyLong_Check(pyyear));
1243 year = PyLong_AsLong(pyyear);
1244 Py_DECREF(pyyear);
1245 if (year < 1900) {
1246 PyErr_Format(PyExc_ValueError, "year=%ld is before "
1247 "1900; the datetime strftime() "
1248 "methods require year >= 1900",
1249 year);
1250 return NULL;
1251 }
1252 }
Tim Petersd6844152002-12-22 20:58:42 +00001253
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001254 /* Scan the input format, looking for %z/%Z/%f escapes, building
1255 * a new format. Since computing the replacements for those codes
1256 * is expensive, don't unless they're actually used.
1257 */
1258 if (flen > INT_MAX - 1) {
1259 PyErr_NoMemory();
1260 goto Done;
1261 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00001262
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001263 totalnew = flen + 1; /* realistic if no %z/%Z */
1264 newfmt = PyBytes_FromStringAndSize(NULL, totalnew);
1265 if (newfmt == NULL) goto Done;
1266 pnew = PyBytes_AsString(newfmt);
1267 usednew = 0;
Tim Peters2a799bf2002-12-16 20:18:38 +00001268
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001269 while ((ch = *pin++) != '\0') {
1270 if (ch != '%') {
1271 ptoappend = pin - 1;
1272 ntoappend = 1;
1273 }
1274 else if ((ch = *pin++) == '\0') {
1275 /* There's a lone trailing %; doesn't make sense. */
1276 PyErr_SetString(PyExc_ValueError, "strftime format "
1277 "ends with raw %");
1278 goto Done;
1279 }
1280 /* A % has been seen and ch is the character after it. */
1281 else if (ch == 'z') {
1282 if (zreplacement == NULL) {
1283 /* format utcoffset */
1284 char buf[100];
1285 PyObject *tzinfo = get_tzinfo_member(object);
1286 zreplacement = PyBytes_FromStringAndSize("", 0);
1287 if (zreplacement == NULL) goto Done;
1288 if (tzinfo != Py_None && tzinfo != NULL) {
1289 assert(tzinfoarg != NULL);
1290 if (format_utcoffset(buf,
1291 sizeof(buf),
1292 "",
1293 tzinfo,
1294 tzinfoarg) < 0)
1295 goto Done;
1296 Py_DECREF(zreplacement);
1297 zreplacement =
1298 PyBytes_FromStringAndSize(buf,
1299 strlen(buf));
1300 if (zreplacement == NULL)
1301 goto Done;
1302 }
1303 }
1304 assert(zreplacement != NULL);
1305 ptoappend = PyBytes_AS_STRING(zreplacement);
1306 ntoappend = PyBytes_GET_SIZE(zreplacement);
1307 }
1308 else if (ch == 'Z') {
1309 /* format tzname */
1310 if (Zreplacement == NULL) {
1311 Zreplacement = make_Zreplacement(object,
1312 tzinfoarg);
1313 if (Zreplacement == NULL)
1314 goto Done;
1315 }
1316 assert(Zreplacement != NULL);
1317 assert(PyUnicode_Check(Zreplacement));
1318 ptoappend = _PyUnicode_AsStringAndSize(Zreplacement,
1319 &ntoappend);
1320 ntoappend = Py_SIZE(Zreplacement);
1321 }
1322 else if (ch == 'f') {
1323 /* format microseconds */
1324 if (freplacement == NULL) {
1325 freplacement = make_freplacement(object);
1326 if (freplacement == NULL)
1327 goto Done;
1328 }
1329 assert(freplacement != NULL);
1330 assert(PyBytes_Check(freplacement));
1331 ptoappend = PyBytes_AS_STRING(freplacement);
1332 ntoappend = PyBytes_GET_SIZE(freplacement);
1333 }
1334 else {
1335 /* percent followed by neither z nor Z */
1336 ptoappend = pin - 2;
1337 ntoappend = 2;
1338 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001339
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001340 /* Append the ntoappend chars starting at ptoappend to
1341 * the new format.
1342 */
1343 if (ntoappend == 0)
1344 continue;
1345 assert(ptoappend != NULL);
1346 assert(ntoappend > 0);
1347 while (usednew + ntoappend > totalnew) {
1348 size_t bigger = totalnew << 1;
1349 if ((bigger >> 1) != totalnew) { /* overflow */
1350 PyErr_NoMemory();
1351 goto Done;
1352 }
1353 if (_PyBytes_Resize(&newfmt, bigger) < 0)
1354 goto Done;
1355 totalnew = bigger;
1356 pnew = PyBytes_AsString(newfmt) + usednew;
1357 }
1358 memcpy(pnew, ptoappend, ntoappend);
1359 pnew += ntoappend;
1360 usednew += ntoappend;
1361 assert(usednew <= totalnew);
1362 } /* end while() */
Tim Peters2a799bf2002-12-16 20:18:38 +00001363
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001364 if (_PyBytes_Resize(&newfmt, usednew) < 0)
1365 goto Done;
1366 {
1367 PyObject *format;
1368 PyObject *time = PyImport_ImportModuleNoBlock("time");
1369 if (time == NULL)
1370 goto Done;
1371 format = PyUnicode_FromString(PyBytes_AS_STRING(newfmt));
1372 if (format != NULL) {
1373 result = PyObject_CallMethod(time, "strftime", "OO",
1374 format, timetuple);
1375 Py_DECREF(format);
1376 }
1377 Py_DECREF(time);
1378 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001379 Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001380 Py_XDECREF(freplacement);
1381 Py_XDECREF(zreplacement);
1382 Py_XDECREF(Zreplacement);
1383 Py_XDECREF(newfmt);
1384 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001385}
1386
Tim Peters2a799bf2002-12-16 20:18:38 +00001387/* ---------------------------------------------------------------------------
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 Pitrouf95a1b32010-05-09 15:52:27 +00001396 PyObject *result = NULL;
1397 PyObject *time = PyImport_ImportModuleNoBlock("time");
Tim Peters2a799bf2002-12-16 20:18:38 +00001398
Antoine Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +00001412 PyObject *time;
1413 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001414
Antoine Pitrouf95a1b32010-05-09 15:52:27 +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
Mark Dickinsone94c6792009-02-02 20:36:42 +00001433/* For various reasons, we need to use tp_richcompare instead of tp_reserved.
Tim Peters2a799bf2002-12-16 20:18:38 +00001434 * 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 Pitrouf95a1b32010-05-09 15:52:27 +00001440 PyObject *result;
1441 int istrue;
Tim Peters2a799bf2002-12-16 20:18:38 +00001442
Antoine Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +00001505 x1 = PyLong_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 Pitrouf95a1b32010-05-09 15:52:27 +00001514 /* x2 has days in seconds */
1515 x1 = PyLong_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 x1 = x2 = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001524
Antoine Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +00001532 /* x1 has days+seconds in us */
1533 x2 = PyLong_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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +00001550 int us;
1551 int s;
1552 int d;
1553 long temp;
Tim Peters2a799bf2002-12-16 20:18:38 +00001554
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001555 PyObject *tuple = NULL;
1556 PyObject *num = NULL;
1557 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001558
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001559 tuple = PyNumber_Divmod(pyus, us_per_second);
1560 if (tuple == NULL)
1561 goto Done;
Tim Peters2a799bf2002-12-16 20:18:38 +00001562
Antoine Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +00001621 Py_XDECREF(tuple);
1622 Py_XDECREF(num);
1623 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001624}
1625
Antoine Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +00001632 PyObject *pyus_in;
1633 PyObject *pyus_out;
1634 PyObject *result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001635
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001636 pyus_in = delta_to_microseconds(delta);
1637 if (pyus_in == NULL)
1638 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001639
Antoine Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +00001653 PyObject *pyus_in;
1654 PyObject *pyus_out;
1655 PyObject *result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001656
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001657 pyus_in = delta_to_microseconds(delta);
1658 if (pyus_in == NULL)
1659 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001660
Antoine Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 *
Mark Dickinson7c186e22010-04-20 22:32:49 +00001672divide_timedelta_timedelta(PyDateTime_Delta *left, PyDateTime_Delta *right)
1673{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001674 PyObject *pyus_left;
1675 PyObject *pyus_right;
1676 PyObject *result;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001677
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001678 pyus_left = delta_to_microseconds(left);
1679 if (pyus_left == NULL)
1680 return NULL;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001681
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001682 pyus_right = delta_to_microseconds(right);
1683 if (pyus_right == NULL) {
1684 Py_DECREF(pyus_left);
1685 return NULL;
1686 }
Mark Dickinson7c186e22010-04-20 22:32:49 +00001687
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001688 result = PyNumber_FloorDivide(pyus_left, pyus_right);
1689 Py_DECREF(pyus_left);
1690 Py_DECREF(pyus_right);
1691 return result;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001692}
1693
1694static PyObject *
1695truedivide_timedelta_timedelta(PyDateTime_Delta *left, PyDateTime_Delta *right)
1696{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001697 PyObject *pyus_left;
1698 PyObject *pyus_right;
1699 PyObject *result;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001700
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001701 pyus_left = delta_to_microseconds(left);
1702 if (pyus_left == NULL)
1703 return NULL;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001704
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001705 pyus_right = delta_to_microseconds(right);
1706 if (pyus_right == NULL) {
1707 Py_DECREF(pyus_left);
1708 return NULL;
1709 }
Mark Dickinson7c186e22010-04-20 22:32:49 +00001710
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001711 result = PyNumber_TrueDivide(pyus_left, pyus_right);
1712 Py_DECREF(pyus_left);
1713 Py_DECREF(pyus_right);
1714 return result;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001715}
1716
1717static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00001718delta_add(PyObject *left, PyObject *right)
1719{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001720 PyObject *result = Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00001721
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001722 if (PyDelta_Check(left) && PyDelta_Check(right)) {
1723 /* delta + delta */
1724 /* The C-level additions can't overflow because of the
1725 * invariant bounds.
1726 */
1727 int days = GET_TD_DAYS(left) + GET_TD_DAYS(right);
1728 int seconds = GET_TD_SECONDS(left) + GET_TD_SECONDS(right);
1729 int microseconds = GET_TD_MICROSECONDS(left) +
1730 GET_TD_MICROSECONDS(right);
1731 result = new_delta(days, seconds, microseconds, 1);
1732 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001733
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001734 if (result == Py_NotImplemented)
1735 Py_INCREF(result);
1736 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001737}
1738
1739static PyObject *
1740delta_negative(PyDateTime_Delta *self)
1741{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001742 return new_delta(-GET_TD_DAYS(self),
1743 -GET_TD_SECONDS(self),
1744 -GET_TD_MICROSECONDS(self),
1745 1);
Tim Peters2a799bf2002-12-16 20:18:38 +00001746}
1747
1748static PyObject *
1749delta_positive(PyDateTime_Delta *self)
1750{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001751 /* Could optimize this (by returning self) if this isn't a
1752 * subclass -- but who uses unary + ? Approximately nobody.
1753 */
1754 return new_delta(GET_TD_DAYS(self),
1755 GET_TD_SECONDS(self),
1756 GET_TD_MICROSECONDS(self),
1757 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00001758}
1759
1760static PyObject *
1761delta_abs(PyDateTime_Delta *self)
1762{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001763 PyObject *result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001764
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001765 assert(GET_TD_MICROSECONDS(self) >= 0);
1766 assert(GET_TD_SECONDS(self) >= 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00001767
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001768 if (GET_TD_DAYS(self) < 0)
1769 result = delta_negative(self);
1770 else
1771 result = delta_positive(self);
Tim Peters2a799bf2002-12-16 20:18:38 +00001772
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001773 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001774}
1775
1776static PyObject *
1777delta_subtract(PyObject *left, PyObject *right)
1778{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001779 PyObject *result = Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00001780
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001781 if (PyDelta_Check(left) && PyDelta_Check(right)) {
1782 /* delta - delta */
1783 PyObject *minus_right = PyNumber_Negative(right);
1784 if (minus_right) {
1785 result = delta_add(left, minus_right);
1786 Py_DECREF(minus_right);
1787 }
1788 else
1789 result = NULL;
1790 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001791
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001792 if (result == Py_NotImplemented)
1793 Py_INCREF(result);
1794 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001795}
1796
Tim Peters2a799bf2002-12-16 20:18:38 +00001797static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00001798delta_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters2a799bf2002-12-16 20:18:38 +00001799{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001800 if (PyDelta_Check(other)) {
1801 int diff = GET_TD_DAYS(self) - GET_TD_DAYS(other);
1802 if (diff == 0) {
1803 diff = GET_TD_SECONDS(self) - GET_TD_SECONDS(other);
1804 if (diff == 0)
1805 diff = GET_TD_MICROSECONDS(self) -
1806 GET_TD_MICROSECONDS(other);
1807 }
1808 return diff_to_bool(diff, op);
1809 }
1810 else {
1811 Py_INCREF(Py_NotImplemented);
1812 return Py_NotImplemented;
1813 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001814}
1815
1816static PyObject *delta_getstate(PyDateTime_Delta *self);
1817
1818static long
1819delta_hash(PyDateTime_Delta *self)
1820{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001821 if (self->hashcode == -1) {
1822 PyObject *temp = delta_getstate(self);
1823 if (temp != NULL) {
1824 self->hashcode = PyObject_Hash(temp);
1825 Py_DECREF(temp);
1826 }
1827 }
1828 return self->hashcode;
Tim Peters2a799bf2002-12-16 20:18:38 +00001829}
1830
1831static PyObject *
1832delta_multiply(PyObject *left, PyObject *right)
1833{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001834 PyObject *result = Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00001835
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001836 if (PyDelta_Check(left)) {
1837 /* delta * ??? */
1838 if (PyLong_Check(right))
1839 result = multiply_int_timedelta(right,
1840 (PyDateTime_Delta *) left);
1841 }
1842 else if (PyLong_Check(left))
1843 result = multiply_int_timedelta(left,
1844 (PyDateTime_Delta *) right);
Tim Peters2a799bf2002-12-16 20:18:38 +00001845
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001846 if (result == Py_NotImplemented)
1847 Py_INCREF(result);
1848 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001849}
1850
1851static PyObject *
1852delta_divide(PyObject *left, PyObject *right)
1853{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001854 PyObject *result = Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00001855
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001856 if (PyDelta_Check(left)) {
1857 /* delta * ??? */
1858 if (PyLong_Check(right))
1859 result = divide_timedelta_int(
1860 (PyDateTime_Delta *)left,
1861 right);
1862 else if (PyDelta_Check(right))
1863 result = divide_timedelta_timedelta(
1864 (PyDateTime_Delta *)left,
1865 (PyDateTime_Delta *)right);
1866 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001867
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001868 if (result == Py_NotImplemented)
1869 Py_INCREF(result);
1870 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001871}
1872
Mark Dickinson7c186e22010-04-20 22:32:49 +00001873static PyObject *
1874delta_truedivide(PyObject *left, PyObject *right)
1875{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001876 PyObject *result = Py_NotImplemented;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001877
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001878 if (PyDelta_Check(left)) {
1879 if (PyDelta_Check(right))
1880 result = truedivide_timedelta_timedelta(
1881 (PyDateTime_Delta *)left,
1882 (PyDateTime_Delta *)right);
1883 }
Mark Dickinson7c186e22010-04-20 22:32:49 +00001884
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001885 if (result == Py_NotImplemented)
1886 Py_INCREF(result);
1887 return result;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001888}
1889
1890static PyObject *
1891delta_remainder(PyObject *left, PyObject *right)
1892{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001893 PyObject *pyus_left;
1894 PyObject *pyus_right;
1895 PyObject *pyus_remainder;
1896 PyObject *remainder;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001897
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001898 if (!PyDelta_Check(left) || !PyDelta_Check(right)) {
1899 Py_INCREF(Py_NotImplemented);
1900 return Py_NotImplemented;
1901 }
Mark Dickinson7c186e22010-04-20 22:32:49 +00001902
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001903 pyus_left = delta_to_microseconds((PyDateTime_Delta *)left);
1904 if (pyus_left == NULL)
1905 return NULL;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001906
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001907 pyus_right = delta_to_microseconds((PyDateTime_Delta *)right);
1908 if (pyus_right == NULL) {
1909 Py_DECREF(pyus_left);
1910 return NULL;
1911 }
Mark Dickinson7c186e22010-04-20 22:32:49 +00001912
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001913 pyus_remainder = PyNumber_Remainder(pyus_left, pyus_right);
1914 Py_DECREF(pyus_left);
1915 Py_DECREF(pyus_right);
1916 if (pyus_remainder == NULL)
1917 return NULL;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001918
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001919 remainder = microseconds_to_delta(pyus_remainder);
1920 Py_DECREF(pyus_remainder);
1921 if (remainder == NULL)
1922 return NULL;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001923
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001924 return remainder;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001925}
1926
1927static PyObject *
1928delta_divmod(PyObject *left, PyObject *right)
1929{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001930 PyObject *pyus_left;
1931 PyObject *pyus_right;
1932 PyObject *divmod;
1933 PyObject *delta;
1934 PyObject *result;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001935
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001936 if (!PyDelta_Check(left) || !PyDelta_Check(right)) {
1937 Py_INCREF(Py_NotImplemented);
1938 return Py_NotImplemented;
1939 }
Mark Dickinson7c186e22010-04-20 22:32:49 +00001940
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001941 pyus_left = delta_to_microseconds((PyDateTime_Delta *)left);
1942 if (pyus_left == NULL)
1943 return NULL;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001944
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001945 pyus_right = delta_to_microseconds((PyDateTime_Delta *)right);
1946 if (pyus_right == NULL) {
1947 Py_DECREF(pyus_left);
1948 return NULL;
1949 }
Mark Dickinson7c186e22010-04-20 22:32:49 +00001950
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001951 divmod = PyNumber_Divmod(pyus_left, pyus_right);
1952 Py_DECREF(pyus_left);
1953 Py_DECREF(pyus_right);
1954 if (divmod == NULL)
1955 return NULL;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001956
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001957 assert(PyTuple_Size(divmod) == 2);
1958 delta = microseconds_to_delta(PyTuple_GET_ITEM(divmod, 1));
1959 if (delta == NULL) {
1960 Py_DECREF(divmod);
1961 return NULL;
1962 }
1963 result = PyTuple_Pack(2, PyTuple_GET_ITEM(divmod, 0), delta);
1964 Py_DECREF(delta);
1965 Py_DECREF(divmod);
1966 return result;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001967}
1968
Tim Peters2a799bf2002-12-16 20:18:38 +00001969/* Fold in the value of the tag ("seconds", "weeks", etc) component of a
1970 * timedelta constructor. sofar is the # of microseconds accounted for
1971 * so far, and there are factor microseconds per current unit, the number
1972 * of which is given by num. num * factor is added to sofar in a
1973 * numerically careful way, and that's the result. Any fractional
1974 * microseconds left over (this can happen if num is a float type) are
1975 * added into *leftover.
1976 * Note that there are many ways this can give an error (NULL) return.
1977 */
1978static PyObject *
1979accum(const char* tag, PyObject *sofar, PyObject *num, PyObject *factor,
1980 double *leftover)
1981{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001982 PyObject *prod;
1983 PyObject *sum;
Tim Peters2a799bf2002-12-16 20:18:38 +00001984
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001985 assert(num != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +00001986
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001987 if (PyLong_Check(num)) {
1988 prod = PyNumber_Multiply(num, factor);
1989 if (prod == NULL)
1990 return NULL;
1991 sum = PyNumber_Add(sofar, prod);
1992 Py_DECREF(prod);
1993 return sum;
1994 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001995
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001996 if (PyFloat_Check(num)) {
1997 double dnum;
1998 double fracpart;
1999 double intpart;
2000 PyObject *x;
2001 PyObject *y;
Tim Peters2a799bf2002-12-16 20:18:38 +00002002
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002003 /* The Plan: decompose num into an integer part and a
2004 * fractional part, num = intpart + fracpart.
2005 * Then num * factor ==
2006 * intpart * factor + fracpart * factor
2007 * and the LHS can be computed exactly in long arithmetic.
2008 * The RHS is again broken into an int part and frac part.
2009 * and the frac part is added into *leftover.
2010 */
2011 dnum = PyFloat_AsDouble(num);
2012 if (dnum == -1.0 && PyErr_Occurred())
2013 return NULL;
2014 fracpart = modf(dnum, &intpart);
2015 x = PyLong_FromDouble(intpart);
2016 if (x == NULL)
2017 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002018
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002019 prod = PyNumber_Multiply(x, factor);
2020 Py_DECREF(x);
2021 if (prod == NULL)
2022 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002023
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002024 sum = PyNumber_Add(sofar, prod);
2025 Py_DECREF(prod);
2026 if (sum == NULL)
2027 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002028
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002029 if (fracpart == 0.0)
2030 return sum;
2031 /* So far we've lost no information. Dealing with the
2032 * fractional part requires float arithmetic, and may
2033 * lose a little info.
2034 */
2035 assert(PyLong_Check(factor));
2036 dnum = PyLong_AsDouble(factor);
Tim Peters2a799bf2002-12-16 20:18:38 +00002037
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002038 dnum *= fracpart;
2039 fracpart = modf(dnum, &intpart);
2040 x = PyLong_FromDouble(intpart);
2041 if (x == NULL) {
2042 Py_DECREF(sum);
2043 return NULL;
2044 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002045
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002046 y = PyNumber_Add(sum, x);
2047 Py_DECREF(sum);
2048 Py_DECREF(x);
2049 *leftover += fracpart;
2050 return y;
2051 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002052
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002053 PyErr_Format(PyExc_TypeError,
2054 "unsupported type for timedelta %s component: %s",
2055 tag, Py_TYPE(num)->tp_name);
2056 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002057}
2058
2059static PyObject *
2060delta_new(PyTypeObject *type, PyObject *args, PyObject *kw)
2061{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002062 PyObject *self = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002063
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002064 /* Argument objects. */
2065 PyObject *day = NULL;
2066 PyObject *second = NULL;
2067 PyObject *us = NULL;
2068 PyObject *ms = NULL;
2069 PyObject *minute = NULL;
2070 PyObject *hour = NULL;
2071 PyObject *week = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002072
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002073 PyObject *x = NULL; /* running sum of microseconds */
2074 PyObject *y = NULL; /* temp sum of microseconds */
2075 double leftover_us = 0.0;
Tim Peters2a799bf2002-12-16 20:18:38 +00002076
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002077 static char *keywords[] = {
2078 "days", "seconds", "microseconds", "milliseconds",
2079 "minutes", "hours", "weeks", NULL
2080 };
Tim Peters2a799bf2002-12-16 20:18:38 +00002081
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002082 if (PyArg_ParseTupleAndKeywords(args, kw, "|OOOOOOO:__new__",
2083 keywords,
2084 &day, &second, &us,
2085 &ms, &minute, &hour, &week) == 0)
2086 goto Done;
Tim Peters2a799bf2002-12-16 20:18:38 +00002087
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002088 x = PyLong_FromLong(0);
2089 if (x == NULL)
2090 goto Done;
Tim Peters2a799bf2002-12-16 20:18:38 +00002091
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002092#define CLEANUP \
2093 Py_DECREF(x); \
2094 x = y; \
2095 if (x == NULL) \
2096 goto Done
Tim Peters2a799bf2002-12-16 20:18:38 +00002097
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002098 if (us) {
2099 y = accum("microseconds", x, us, us_per_us, &leftover_us);
2100 CLEANUP;
2101 }
2102 if (ms) {
2103 y = accum("milliseconds", x, ms, us_per_ms, &leftover_us);
2104 CLEANUP;
2105 }
2106 if (second) {
2107 y = accum("seconds", x, second, us_per_second, &leftover_us);
2108 CLEANUP;
2109 }
2110 if (minute) {
2111 y = accum("minutes", x, minute, us_per_minute, &leftover_us);
2112 CLEANUP;
2113 }
2114 if (hour) {
2115 y = accum("hours", x, hour, us_per_hour, &leftover_us);
2116 CLEANUP;
2117 }
2118 if (day) {
2119 y = accum("days", x, day, us_per_day, &leftover_us);
2120 CLEANUP;
2121 }
2122 if (week) {
2123 y = accum("weeks", x, week, us_per_week, &leftover_us);
2124 CLEANUP;
2125 }
2126 if (leftover_us) {
2127 /* Round to nearest whole # of us, and add into x. */
2128 PyObject *temp = PyLong_FromLong(round_to_long(leftover_us));
2129 if (temp == NULL) {
2130 Py_DECREF(x);
2131 goto Done;
2132 }
2133 y = PyNumber_Add(x, temp);
2134 Py_DECREF(temp);
2135 CLEANUP;
2136 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002137
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002138 self = microseconds_to_delta_ex(x, type);
2139 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00002140Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002141 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00002142
2143#undef CLEANUP
2144}
2145
2146static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00002147delta_bool(PyDateTime_Delta *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00002148{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002149 return (GET_TD_DAYS(self) != 0
2150 || GET_TD_SECONDS(self) != 0
2151 || GET_TD_MICROSECONDS(self) != 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00002152}
2153
2154static PyObject *
2155delta_repr(PyDateTime_Delta *self)
2156{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002157 if (GET_TD_MICROSECONDS(self) != 0)
2158 return PyUnicode_FromFormat("%s(%d, %d, %d)",
2159 Py_TYPE(self)->tp_name,
2160 GET_TD_DAYS(self),
2161 GET_TD_SECONDS(self),
2162 GET_TD_MICROSECONDS(self));
2163 if (GET_TD_SECONDS(self) != 0)
2164 return PyUnicode_FromFormat("%s(%d, %d)",
2165 Py_TYPE(self)->tp_name,
2166 GET_TD_DAYS(self),
2167 GET_TD_SECONDS(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002168
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002169 return PyUnicode_FromFormat("%s(%d)",
2170 Py_TYPE(self)->tp_name,
2171 GET_TD_DAYS(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002172}
2173
2174static PyObject *
2175delta_str(PyDateTime_Delta *self)
2176{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002177 int us = GET_TD_MICROSECONDS(self);
2178 int seconds = GET_TD_SECONDS(self);
2179 int minutes = divmod(seconds, 60, &seconds);
2180 int hours = divmod(minutes, 60, &minutes);
2181 int days = GET_TD_DAYS(self);
Tim Peters2a799bf2002-12-16 20:18:38 +00002182
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002183 if (days) {
2184 if (us)
2185 return PyUnicode_FromFormat("%d day%s, %d:%02d:%02d.%06d",
2186 days, (days == 1 || days == -1) ? "" : "s",
2187 hours, minutes, seconds, us);
2188 else
2189 return PyUnicode_FromFormat("%d day%s, %d:%02d:%02d",
2190 days, (days == 1 || days == -1) ? "" : "s",
2191 hours, minutes, seconds);
2192 } else {
2193 if (us)
2194 return PyUnicode_FromFormat("%d:%02d:%02d.%06d",
2195 hours, minutes, seconds, us);
2196 else
2197 return PyUnicode_FromFormat("%d:%02d:%02d",
2198 hours, minutes, seconds);
2199 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002200
Tim Peters2a799bf2002-12-16 20:18:38 +00002201}
2202
Tim Peters371935f2003-02-01 01:52:50 +00002203/* Pickle support, a simple use of __reduce__. */
2204
Tim Petersb57f8f02003-02-01 02:54:15 +00002205/* __getstate__ isn't exposed */
Tim Peters2a799bf2002-12-16 20:18:38 +00002206static PyObject *
2207delta_getstate(PyDateTime_Delta *self)
2208{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002209 return Py_BuildValue("iii", GET_TD_DAYS(self),
2210 GET_TD_SECONDS(self),
2211 GET_TD_MICROSECONDS(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002212}
2213
Tim Peters2a799bf2002-12-16 20:18:38 +00002214static PyObject *
Antoine Pitroube6859d2009-11-25 23:02:32 +00002215delta_total_seconds(PyObject *self)
2216{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002217 PyObject *total_seconds;
2218 PyObject *total_microseconds;
2219 PyObject *one_million;
Mark Dickinson0381e3f2010-05-08 14:35:02 +00002220
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002221 total_microseconds = delta_to_microseconds((PyDateTime_Delta *)self);
2222 if (total_microseconds == NULL)
2223 return NULL;
Mark Dickinson0381e3f2010-05-08 14:35:02 +00002224
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002225 one_million = PyLong_FromLong(1000000L);
2226 if (one_million == NULL) {
2227 Py_DECREF(total_microseconds);
2228 return NULL;
2229 }
Mark Dickinson0381e3f2010-05-08 14:35:02 +00002230
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002231 total_seconds = PyNumber_TrueDivide(total_microseconds, one_million);
Mark Dickinson0381e3f2010-05-08 14:35:02 +00002232
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002233 Py_DECREF(total_microseconds);
2234 Py_DECREF(one_million);
2235 return total_seconds;
Antoine Pitroube6859d2009-11-25 23:02:32 +00002236}
2237
2238static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002239delta_reduce(PyDateTime_Delta* self)
2240{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002241 return Py_BuildValue("ON", Py_TYPE(self), delta_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002242}
2243
2244#define OFFSET(field) offsetof(PyDateTime_Delta, field)
2245
2246static PyMemberDef delta_members[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002247
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002248 {"days", T_INT, OFFSET(days), READONLY,
2249 PyDoc_STR("Number of days.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002250
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002251 {"seconds", T_INT, OFFSET(seconds), READONLY,
2252 PyDoc_STR("Number of seconds (>= 0 and less than 1 day).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002253
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002254 {"microseconds", T_INT, OFFSET(microseconds), READONLY,
2255 PyDoc_STR("Number of microseconds (>= 0 and less than 1 second).")},
2256 {NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00002257};
2258
2259static PyMethodDef delta_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002260 {"total_seconds", (PyCFunction)delta_total_seconds, METH_NOARGS,
2261 PyDoc_STR("Total seconds in the duration.")},
Antoine Pitroube6859d2009-11-25 23:02:32 +00002262
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002263 {"__reduce__", (PyCFunction)delta_reduce, METH_NOARGS,
2264 PyDoc_STR("__reduce__() -> (cls, state)")},
Guido van Rossum177e41a2003-01-30 22:06:23 +00002265
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002266 {NULL, NULL},
Tim Peters2a799bf2002-12-16 20:18:38 +00002267};
2268
2269static char delta_doc[] =
2270PyDoc_STR("Difference between two datetime values.");
2271
2272static PyNumberMethods delta_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002273 delta_add, /* nb_add */
2274 delta_subtract, /* nb_subtract */
2275 delta_multiply, /* nb_multiply */
2276 delta_remainder, /* nb_remainder */
2277 delta_divmod, /* nb_divmod */
2278 0, /* nb_power */
2279 (unaryfunc)delta_negative, /* nb_negative */
2280 (unaryfunc)delta_positive, /* nb_positive */
2281 (unaryfunc)delta_abs, /* nb_absolute */
2282 (inquiry)delta_bool, /* nb_bool */
2283 0, /*nb_invert*/
2284 0, /*nb_lshift*/
2285 0, /*nb_rshift*/
2286 0, /*nb_and*/
2287 0, /*nb_xor*/
2288 0, /*nb_or*/
2289 0, /*nb_int*/
2290 0, /*nb_reserved*/
2291 0, /*nb_float*/
2292 0, /*nb_inplace_add*/
2293 0, /*nb_inplace_subtract*/
2294 0, /*nb_inplace_multiply*/
2295 0, /*nb_inplace_remainder*/
2296 0, /*nb_inplace_power*/
2297 0, /*nb_inplace_lshift*/
2298 0, /*nb_inplace_rshift*/
2299 0, /*nb_inplace_and*/
2300 0, /*nb_inplace_xor*/
2301 0, /*nb_inplace_or*/
2302 delta_divide, /* nb_floor_divide */
2303 delta_truedivide, /* nb_true_divide */
2304 0, /* nb_inplace_floor_divide */
2305 0, /* nb_inplace_true_divide */
Tim Peters2a799bf2002-12-16 20:18:38 +00002306};
2307
2308static PyTypeObject PyDateTime_DeltaType = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002309 PyVarObject_HEAD_INIT(NULL, 0)
2310 "datetime.timedelta", /* tp_name */
2311 sizeof(PyDateTime_Delta), /* tp_basicsize */
2312 0, /* tp_itemsize */
2313 0, /* tp_dealloc */
2314 0, /* tp_print */
2315 0, /* tp_getattr */
2316 0, /* tp_setattr */
2317 0, /* tp_reserved */
2318 (reprfunc)delta_repr, /* tp_repr */
2319 &delta_as_number, /* tp_as_number */
2320 0, /* tp_as_sequence */
2321 0, /* tp_as_mapping */
2322 (hashfunc)delta_hash, /* tp_hash */
2323 0, /* tp_call */
2324 (reprfunc)delta_str, /* tp_str */
2325 PyObject_GenericGetAttr, /* tp_getattro */
2326 0, /* tp_setattro */
2327 0, /* tp_as_buffer */
2328 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
2329 delta_doc, /* tp_doc */
2330 0, /* tp_traverse */
2331 0, /* tp_clear */
2332 delta_richcompare, /* tp_richcompare */
2333 0, /* tp_weaklistoffset */
2334 0, /* tp_iter */
2335 0, /* tp_iternext */
2336 delta_methods, /* tp_methods */
2337 delta_members, /* tp_members */
2338 0, /* tp_getset */
2339 0, /* tp_base */
2340 0, /* tp_dict */
2341 0, /* tp_descr_get */
2342 0, /* tp_descr_set */
2343 0, /* tp_dictoffset */
2344 0, /* tp_init */
2345 0, /* tp_alloc */
2346 delta_new, /* tp_new */
2347 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00002348};
2349
2350/*
2351 * PyDateTime_Date implementation.
2352 */
2353
2354/* Accessor properties. */
2355
2356static PyObject *
2357date_year(PyDateTime_Date *self, void *unused)
2358{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002359 return PyLong_FromLong(GET_YEAR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002360}
2361
2362static PyObject *
2363date_month(PyDateTime_Date *self, void *unused)
2364{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002365 return PyLong_FromLong(GET_MONTH(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002366}
2367
2368static PyObject *
2369date_day(PyDateTime_Date *self, void *unused)
2370{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002371 return PyLong_FromLong(GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002372}
2373
2374static PyGetSetDef date_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002375 {"year", (getter)date_year},
2376 {"month", (getter)date_month},
2377 {"day", (getter)date_day},
2378 {NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00002379};
2380
2381/* Constructors. */
2382
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00002383static char *date_kws[] = {"year", "month", "day", NULL};
Tim Peters12bf3392002-12-24 05:41:27 +00002384
Tim Peters2a799bf2002-12-16 20:18:38 +00002385static PyObject *
2386date_new(PyTypeObject *type, PyObject *args, PyObject *kw)
2387{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002388 PyObject *self = NULL;
2389 PyObject *state;
2390 int year;
2391 int month;
2392 int day;
Tim Peters2a799bf2002-12-16 20:18:38 +00002393
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002394 /* Check for invocation from pickle with __getstate__ state */
2395 if (PyTuple_GET_SIZE(args) == 1 &&
2396 PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) &&
2397 PyBytes_GET_SIZE(state) == _PyDateTime_DATE_DATASIZE &&
2398 MONTH_IS_SANE(PyBytes_AS_STRING(state)[2]))
2399 {
2400 PyDateTime_Date *me;
Tim Peters70533e22003-02-01 04:40:04 +00002401
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002402 me = (PyDateTime_Date *) (type->tp_alloc(type, 0));
2403 if (me != NULL) {
2404 char *pdata = PyBytes_AS_STRING(state);
2405 memcpy(me->data, pdata, _PyDateTime_DATE_DATASIZE);
2406 me->hashcode = -1;
2407 }
2408 return (PyObject *)me;
2409 }
Guido van Rossum177e41a2003-01-30 22:06:23 +00002410
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002411 if (PyArg_ParseTupleAndKeywords(args, kw, "iii", date_kws,
2412 &year, &month, &day)) {
2413 if (check_date_args(year, month, day) < 0)
2414 return NULL;
2415 self = new_date_ex(year, month, day, type);
2416 }
2417 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00002418}
2419
2420/* Return new date from localtime(t). */
2421static PyObject *
Tim Peters1b6f7a92004-06-20 02:50:16 +00002422date_local_from_time_t(PyObject *cls, double ts)
Tim Peters2a799bf2002-12-16 20:18:38 +00002423{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002424 struct tm *tm;
2425 time_t t;
2426 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002427
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002428 t = _PyTime_DoubleToTimet(ts);
2429 if (t == (time_t)-1 && PyErr_Occurred())
2430 return NULL;
2431 tm = localtime(&t);
2432 if (tm)
2433 result = PyObject_CallFunction(cls, "iii",
2434 tm->tm_year + 1900,
2435 tm->tm_mon + 1,
2436 tm->tm_mday);
2437 else
2438 PyErr_SetString(PyExc_ValueError,
2439 "timestamp out of range for "
2440 "platform localtime() function");
2441 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002442}
2443
2444/* Return new date from current time.
2445 * We say this is equivalent to fromtimestamp(time.time()), and the
2446 * only way to be sure of that is to *call* time.time(). That's not
2447 * generally the same as calling C's time.
2448 */
2449static PyObject *
2450date_today(PyObject *cls, PyObject *dummy)
2451{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002452 PyObject *time;
2453 PyObject *result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002454
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002455 time = time_time();
2456 if (time == NULL)
2457 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002458
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002459 /* Note well: today() is a class method, so this may not call
2460 * date.fromtimestamp. For example, it may call
2461 * datetime.fromtimestamp. That's why we need all the accuracy
2462 * time.time() delivers; if someone were gonzo about optimization,
2463 * date.today() could get away with plain C time().
2464 */
2465 result = PyObject_CallMethod(cls, "fromtimestamp", "O", time);
2466 Py_DECREF(time);
2467 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002468}
2469
2470/* Return new date from given timestamp (Python timestamp -- a double). */
2471static PyObject *
2472date_fromtimestamp(PyObject *cls, PyObject *args)
2473{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002474 double timestamp;
2475 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002476
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002477 if (PyArg_ParseTuple(args, "d:fromtimestamp", &timestamp))
2478 result = date_local_from_time_t(cls, timestamp);
2479 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002480}
2481
2482/* Return new date from proleptic Gregorian ordinal. Raises ValueError if
2483 * the ordinal is out of range.
2484 */
2485static PyObject *
2486date_fromordinal(PyObject *cls, PyObject *args)
2487{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002488 PyObject *result = NULL;
2489 int ordinal;
Tim Peters2a799bf2002-12-16 20:18:38 +00002490
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002491 if (PyArg_ParseTuple(args, "i:fromordinal", &ordinal)) {
2492 int year;
2493 int month;
2494 int day;
Tim Peters2a799bf2002-12-16 20:18:38 +00002495
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002496 if (ordinal < 1)
2497 PyErr_SetString(PyExc_ValueError, "ordinal must be "
2498 ">= 1");
2499 else {
2500 ord_to_ymd(ordinal, &year, &month, &day);
2501 result = PyObject_CallFunction(cls, "iii",
2502 year, month, day);
2503 }
2504 }
2505 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002506}
2507
2508/*
2509 * Date arithmetic.
2510 */
2511
2512/* date + timedelta -> date. If arg negate is true, subtract the timedelta
2513 * instead.
2514 */
2515static PyObject *
2516add_date_timedelta(PyDateTime_Date *date, PyDateTime_Delta *delta, int negate)
2517{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002518 PyObject *result = NULL;
2519 int year = GET_YEAR(date);
2520 int month = GET_MONTH(date);
2521 int deltadays = GET_TD_DAYS(delta);
2522 /* C-level overflow is impossible because |deltadays| < 1e9. */
2523 int day = GET_DAY(date) + (negate ? -deltadays : deltadays);
Tim Peters2a799bf2002-12-16 20:18:38 +00002524
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002525 if (normalize_date(&year, &month, &day) >= 0)
2526 result = new_date(year, month, day);
2527 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002528}
2529
2530static PyObject *
2531date_add(PyObject *left, PyObject *right)
2532{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002533 if (PyDateTime_Check(left) || PyDateTime_Check(right)) {
2534 Py_INCREF(Py_NotImplemented);
2535 return Py_NotImplemented;
2536 }
2537 if (PyDate_Check(left)) {
2538 /* date + ??? */
2539 if (PyDelta_Check(right))
2540 /* date + delta */
2541 return add_date_timedelta((PyDateTime_Date *) left,
2542 (PyDateTime_Delta *) right,
2543 0);
2544 }
2545 else {
2546 /* ??? + date
2547 * 'right' must be one of us, or we wouldn't have been called
2548 */
2549 if (PyDelta_Check(left))
2550 /* delta + date */
2551 return add_date_timedelta((PyDateTime_Date *) right,
2552 (PyDateTime_Delta *) left,
2553 0);
2554 }
2555 Py_INCREF(Py_NotImplemented);
2556 return Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00002557}
2558
2559static PyObject *
2560date_subtract(PyObject *left, PyObject *right)
2561{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002562 if (PyDateTime_Check(left) || PyDateTime_Check(right)) {
2563 Py_INCREF(Py_NotImplemented);
2564 return Py_NotImplemented;
2565 }
2566 if (PyDate_Check(left)) {
2567 if (PyDate_Check(right)) {
2568 /* date - date */
2569 int left_ord = ymd_to_ord(GET_YEAR(left),
2570 GET_MONTH(left),
2571 GET_DAY(left));
2572 int right_ord = ymd_to_ord(GET_YEAR(right),
2573 GET_MONTH(right),
2574 GET_DAY(right));
2575 return new_delta(left_ord - right_ord, 0, 0, 0);
2576 }
2577 if (PyDelta_Check(right)) {
2578 /* date - delta */
2579 return add_date_timedelta((PyDateTime_Date *) left,
2580 (PyDateTime_Delta *) right,
2581 1);
2582 }
2583 }
2584 Py_INCREF(Py_NotImplemented);
2585 return Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00002586}
2587
2588
2589/* Various ways to turn a date into a string. */
2590
2591static PyObject *
2592date_repr(PyDateTime_Date *self)
2593{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002594 return PyUnicode_FromFormat("%s(%d, %d, %d)",
2595 Py_TYPE(self)->tp_name,
2596 GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002597}
2598
2599static PyObject *
2600date_isoformat(PyDateTime_Date *self)
2601{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002602 return PyUnicode_FromFormat("%04d-%02d-%02d",
2603 GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002604}
2605
Tim Peterse2df5ff2003-05-02 18:39:55 +00002606/* str() calls the appropriate isoformat() method. */
Tim Peters2a799bf2002-12-16 20:18:38 +00002607static PyObject *
2608date_str(PyDateTime_Date *self)
2609{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002610 return PyObject_CallMethod((PyObject *)self, "isoformat", "()");
Tim Peters2a799bf2002-12-16 20:18:38 +00002611}
2612
2613
2614static PyObject *
2615date_ctime(PyDateTime_Date *self)
2616{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002617 return format_ctime(self, 0, 0, 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00002618}
2619
2620static PyObject *
2621date_strftime(PyDateTime_Date *self, PyObject *args, PyObject *kw)
2622{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002623 /* This method can be inherited, and needs to call the
2624 * timetuple() method appropriate to self's class.
2625 */
2626 PyObject *result;
2627 PyObject *tuple;
2628 PyObject *format;
2629 static char *keywords[] = {"format", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00002630
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002631 if (! PyArg_ParseTupleAndKeywords(args, kw, "U:strftime", keywords,
2632 &format))
2633 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002634
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002635 tuple = PyObject_CallMethod((PyObject *)self, "timetuple", "()");
2636 if (tuple == NULL)
2637 return NULL;
2638 result = wrap_strftime((PyObject *)self, format, tuple,
2639 (PyObject *)self);
2640 Py_DECREF(tuple);
2641 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002642}
2643
Eric Smith1ba31142007-09-11 18:06:02 +00002644static PyObject *
2645date_format(PyDateTime_Date *self, PyObject *args)
2646{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002647 PyObject *format;
Eric Smith1ba31142007-09-11 18:06:02 +00002648
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002649 if (!PyArg_ParseTuple(args, "U:__format__", &format))
2650 return NULL;
Eric Smith1ba31142007-09-11 18:06:02 +00002651
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002652 /* if the format is zero length, return str(self) */
2653 if (PyUnicode_GetSize(format) == 0)
2654 return PyObject_Str((PyObject *)self);
Eric Smith1ba31142007-09-11 18:06:02 +00002655
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002656 return PyObject_CallMethod((PyObject *)self, "strftime", "O", format);
Eric Smith1ba31142007-09-11 18:06:02 +00002657}
2658
Tim Peters2a799bf2002-12-16 20:18:38 +00002659/* ISO methods. */
2660
2661static PyObject *
2662date_isoweekday(PyDateTime_Date *self)
2663{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002664 int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002665
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002666 return PyLong_FromLong(dow + 1);
Tim Peters2a799bf2002-12-16 20:18:38 +00002667}
2668
2669static PyObject *
2670date_isocalendar(PyDateTime_Date *self)
2671{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002672 int year = GET_YEAR(self);
2673 int week1_monday = iso_week1_monday(year);
2674 int today = ymd_to_ord(year, GET_MONTH(self), GET_DAY(self));
2675 int week;
2676 int day;
Tim Peters2a799bf2002-12-16 20:18:38 +00002677
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002678 week = divmod(today - week1_monday, 7, &day);
2679 if (week < 0) {
2680 --year;
2681 week1_monday = iso_week1_monday(year);
2682 week = divmod(today - week1_monday, 7, &day);
2683 }
2684 else if (week >= 52 && today >= iso_week1_monday(year + 1)) {
2685 ++year;
2686 week = 0;
2687 }
2688 return Py_BuildValue("iii", year, week + 1, day + 1);
Tim Peters2a799bf2002-12-16 20:18:38 +00002689}
2690
2691/* Miscellaneous methods. */
2692
Tim Peters2a799bf2002-12-16 20:18:38 +00002693static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00002694date_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters2a799bf2002-12-16 20:18:38 +00002695{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002696 if (PyDate_Check(other)) {
2697 int diff = memcmp(((PyDateTime_Date *)self)->data,
2698 ((PyDateTime_Date *)other)->data,
2699 _PyDateTime_DATE_DATASIZE);
2700 return diff_to_bool(diff, op);
2701 }
2702 else {
2703 Py_INCREF(Py_NotImplemented);
2704 return Py_NotImplemented;
2705 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002706}
2707
2708static PyObject *
2709date_timetuple(PyDateTime_Date *self)
2710{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002711 return build_struct_time(GET_YEAR(self),
2712 GET_MONTH(self),
2713 GET_DAY(self),
2714 0, 0, 0, -1);
Tim Peters2a799bf2002-12-16 20:18:38 +00002715}
2716
Tim Peters12bf3392002-12-24 05:41:27 +00002717static PyObject *
2718date_replace(PyDateTime_Date *self, PyObject *args, PyObject *kw)
2719{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002720 PyObject *clone;
2721 PyObject *tuple;
2722 int year = GET_YEAR(self);
2723 int month = GET_MONTH(self);
2724 int day = GET_DAY(self);
Tim Peters12bf3392002-12-24 05:41:27 +00002725
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002726 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iii:replace", date_kws,
2727 &year, &month, &day))
2728 return NULL;
2729 tuple = Py_BuildValue("iii", year, month, day);
2730 if (tuple == NULL)
2731 return NULL;
2732 clone = date_new(Py_TYPE(self), tuple, NULL);
2733 Py_DECREF(tuple);
2734 return clone;
Tim Peters12bf3392002-12-24 05:41:27 +00002735}
2736
Guido van Rossumfd53fd62007-08-24 04:05:13 +00002737/*
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002738 Borrowed from stringobject.c, originally it was string_hash()
Guido van Rossumfd53fd62007-08-24 04:05:13 +00002739*/
2740static long
2741generic_hash(unsigned char *data, int len)
2742{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002743 register unsigned char *p;
2744 register long x;
Guido van Rossumfd53fd62007-08-24 04:05:13 +00002745
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002746 p = (unsigned char *) data;
2747 x = *p << 7;
2748 while (--len >= 0)
2749 x = (1000003*x) ^ *p++;
2750 x ^= len;
2751 if (x == -1)
2752 x = -2;
Guido van Rossumfd53fd62007-08-24 04:05:13 +00002753
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002754 return x;
Guido van Rossumfd53fd62007-08-24 04:05:13 +00002755}
2756
2757
2758static PyObject *date_getstate(PyDateTime_Date *self);
Tim Peters2a799bf2002-12-16 20:18:38 +00002759
2760static long
2761date_hash(PyDateTime_Date *self)
2762{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002763 if (self->hashcode == -1)
2764 self->hashcode = generic_hash(
2765 (unsigned char *)self->data, _PyDateTime_DATE_DATASIZE);
Guido van Rossum254348e2007-11-21 19:29:53 +00002766
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002767 return self->hashcode;
Tim Peters2a799bf2002-12-16 20:18:38 +00002768}
2769
2770static PyObject *
2771date_toordinal(PyDateTime_Date *self)
2772{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002773 return PyLong_FromLong(ymd_to_ord(GET_YEAR(self), GET_MONTH(self),
2774 GET_DAY(self)));
Tim Peters2a799bf2002-12-16 20:18:38 +00002775}
2776
2777static PyObject *
2778date_weekday(PyDateTime_Date *self)
2779{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002780 int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002781
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002782 return PyLong_FromLong(dow);
Tim Peters2a799bf2002-12-16 20:18:38 +00002783}
2784
Tim Peters371935f2003-02-01 01:52:50 +00002785/* Pickle support, a simple use of __reduce__. */
Tim Peters2a799bf2002-12-16 20:18:38 +00002786
Tim Petersb57f8f02003-02-01 02:54:15 +00002787/* __getstate__ isn't exposed */
Tim Peters2a799bf2002-12-16 20:18:38 +00002788static PyObject *
Guido van Rossumfd53fd62007-08-24 04:05:13 +00002789date_getstate(PyDateTime_Date *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00002790{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002791 PyObject* field;
2792 field = PyBytes_FromStringAndSize((char*)self->data,
2793 _PyDateTime_DATE_DATASIZE);
2794 return Py_BuildValue("(N)", field);
Tim Peters2a799bf2002-12-16 20:18:38 +00002795}
2796
2797static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00002798date_reduce(PyDateTime_Date *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00002799{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002800 return Py_BuildValue("(ON)", Py_TYPE(self), date_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002801}
2802
2803static PyMethodDef date_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002804
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002805 /* Class methods: */
Guido van Rossum177e41a2003-01-30 22:06:23 +00002806
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002807 {"fromtimestamp", (PyCFunction)date_fromtimestamp, METH_VARARGS |
2808 METH_CLASS,
2809 PyDoc_STR("timestamp -> local date from a POSIX timestamp (like "
2810 "time.time()).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002811
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002812 {"fromordinal", (PyCFunction)date_fromordinal, METH_VARARGS |
2813 METH_CLASS,
2814 PyDoc_STR("int -> date corresponding to a proleptic Gregorian "
2815 "ordinal.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002816
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002817 {"today", (PyCFunction)date_today, METH_NOARGS | METH_CLASS,
2818 PyDoc_STR("Current date or datetime: same as "
2819 "self.__class__.fromtimestamp(time.time()).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002820
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002821 /* Instance methods: */
Tim Peters2a799bf2002-12-16 20:18:38 +00002822
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002823 {"ctime", (PyCFunction)date_ctime, METH_NOARGS,
2824 PyDoc_STR("Return ctime() style string.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002825
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002826 {"strftime", (PyCFunction)date_strftime, METH_VARARGS | METH_KEYWORDS,
2827 PyDoc_STR("format -> strftime() style string.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002828
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002829 {"__format__", (PyCFunction)date_format, METH_VARARGS,
2830 PyDoc_STR("Formats self with strftime.")},
Eric Smith1ba31142007-09-11 18:06:02 +00002831
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002832 {"timetuple", (PyCFunction)date_timetuple, METH_NOARGS,
2833 PyDoc_STR("Return time tuple, compatible with time.localtime().")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002834
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002835 {"isocalendar", (PyCFunction)date_isocalendar, METH_NOARGS,
2836 PyDoc_STR("Return a 3-tuple containing ISO year, week number, and "
2837 "weekday.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002838
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002839 {"isoformat", (PyCFunction)date_isoformat, METH_NOARGS,
2840 PyDoc_STR("Return string in ISO 8601 format, YYYY-MM-DD.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002841
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002842 {"isoweekday", (PyCFunction)date_isoweekday, METH_NOARGS,
2843 PyDoc_STR("Return the day of the week represented by the date.\n"
2844 "Monday == 1 ... Sunday == 7")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002845
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002846 {"toordinal", (PyCFunction)date_toordinal, METH_NOARGS,
2847 PyDoc_STR("Return proleptic Gregorian ordinal. January 1 of year "
2848 "1 is day 1.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002849
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002850 {"weekday", (PyCFunction)date_weekday, METH_NOARGS,
2851 PyDoc_STR("Return the day of the week represented by the date.\n"
2852 "Monday == 0 ... Sunday == 6")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002853
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002854 {"replace", (PyCFunction)date_replace, METH_VARARGS | METH_KEYWORDS,
2855 PyDoc_STR("Return date with new specified fields.")},
Tim Peters12bf3392002-12-24 05:41:27 +00002856
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002857 {"__reduce__", (PyCFunction)date_reduce, METH_NOARGS,
2858 PyDoc_STR("__reduce__() -> (cls, state)")},
Guido van Rossum177e41a2003-01-30 22:06:23 +00002859
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002860 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00002861};
2862
2863static char date_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00002864PyDoc_STR("date(year, month, day) --> date object");
Tim Peters2a799bf2002-12-16 20:18:38 +00002865
2866static PyNumberMethods date_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002867 date_add, /* nb_add */
2868 date_subtract, /* nb_subtract */
2869 0, /* nb_multiply */
2870 0, /* nb_remainder */
2871 0, /* nb_divmod */
2872 0, /* nb_power */
2873 0, /* nb_negative */
2874 0, /* nb_positive */
2875 0, /* nb_absolute */
2876 0, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00002877};
2878
2879static PyTypeObject PyDateTime_DateType = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002880 PyVarObject_HEAD_INIT(NULL, 0)
2881 "datetime.date", /* tp_name */
2882 sizeof(PyDateTime_Date), /* tp_basicsize */
2883 0, /* tp_itemsize */
2884 0, /* tp_dealloc */
2885 0, /* tp_print */
2886 0, /* tp_getattr */
2887 0, /* tp_setattr */
2888 0, /* tp_reserved */
2889 (reprfunc)date_repr, /* tp_repr */
2890 &date_as_number, /* tp_as_number */
2891 0, /* tp_as_sequence */
2892 0, /* tp_as_mapping */
2893 (hashfunc)date_hash, /* tp_hash */
2894 0, /* tp_call */
2895 (reprfunc)date_str, /* tp_str */
2896 PyObject_GenericGetAttr, /* tp_getattro */
2897 0, /* tp_setattro */
2898 0, /* tp_as_buffer */
2899 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
2900 date_doc, /* tp_doc */
2901 0, /* tp_traverse */
2902 0, /* tp_clear */
2903 date_richcompare, /* tp_richcompare */
2904 0, /* tp_weaklistoffset */
2905 0, /* tp_iter */
2906 0, /* tp_iternext */
2907 date_methods, /* tp_methods */
2908 0, /* tp_members */
2909 date_getset, /* tp_getset */
2910 0, /* tp_base */
2911 0, /* tp_dict */
2912 0, /* tp_descr_get */
2913 0, /* tp_descr_set */
2914 0, /* tp_dictoffset */
2915 0, /* tp_init */
2916 0, /* tp_alloc */
2917 date_new, /* tp_new */
2918 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00002919};
2920
2921/*
Tim Peters2a799bf2002-12-16 20:18:38 +00002922 * PyDateTime_TZInfo implementation.
2923 */
2924
2925/* This is a pure abstract base class, so doesn't do anything beyond
2926 * raising NotImplemented exceptions. Real tzinfo classes need
2927 * to derive from this. This is mostly for clarity, and for efficiency in
Tim Petersa9bc1682003-01-11 03:39:11 +00002928 * datetime and time constructors (their tzinfo arguments need to
Tim Peters2a799bf2002-12-16 20:18:38 +00002929 * be subclasses of this tzinfo class, which is easy and quick to check).
2930 *
2931 * Note: For reasons having to do with pickling of subclasses, we have
2932 * to allow tzinfo objects to be instantiated. This wasn't an issue
2933 * in the Python implementation (__init__() could raise NotImplementedError
2934 * there without ill effect), but doing so in the C implementation hit a
2935 * brick wall.
2936 */
2937
2938static PyObject *
2939tzinfo_nogo(const char* methodname)
2940{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002941 PyErr_Format(PyExc_NotImplementedError,
2942 "a tzinfo subclass must implement %s()",
2943 methodname);
2944 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002945}
2946
2947/* Methods. A subclass must implement these. */
2948
Tim Peters52dcce22003-01-23 16:36:11 +00002949static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002950tzinfo_tzname(PyDateTime_TZInfo *self, PyObject *dt)
2951{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002952 return tzinfo_nogo("tzname");
Tim Peters2a799bf2002-12-16 20:18:38 +00002953}
2954
Tim Peters52dcce22003-01-23 16:36:11 +00002955static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002956tzinfo_utcoffset(PyDateTime_TZInfo *self, PyObject *dt)
2957{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002958 return tzinfo_nogo("utcoffset");
Tim Peters2a799bf2002-12-16 20:18:38 +00002959}
2960
Tim Peters52dcce22003-01-23 16:36:11 +00002961static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002962tzinfo_dst(PyDateTime_TZInfo *self, PyObject *dt)
2963{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002964 return tzinfo_nogo("dst");
Tim Peters2a799bf2002-12-16 20:18:38 +00002965}
2966
Tim Peters52dcce22003-01-23 16:36:11 +00002967static PyObject *
2968tzinfo_fromutc(PyDateTime_TZInfo *self, PyDateTime_DateTime *dt)
2969{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002970 int y, m, d, hh, mm, ss, us;
Tim Peters52dcce22003-01-23 16:36:11 +00002971
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002972 PyObject *result;
2973 int off, dst;
2974 int none;
2975 int delta;
Tim Peters52dcce22003-01-23 16:36:11 +00002976
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002977 if (! PyDateTime_Check(dt)) {
2978 PyErr_SetString(PyExc_TypeError,
2979 "fromutc: argument must be a datetime");
2980 return NULL;
2981 }
2982 if (! HASTZINFO(dt) || dt->tzinfo != (PyObject *)self) {
2983 PyErr_SetString(PyExc_ValueError, "fromutc: dt.tzinfo "
2984 "is not self");
2985 return NULL;
2986 }
Tim Peters52dcce22003-01-23 16:36:11 +00002987
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002988 off = call_utcoffset(dt->tzinfo, (PyObject *)dt, &none);
2989 if (off == -1 && PyErr_Occurred())
2990 return NULL;
2991 if (none) {
2992 PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
2993 "utcoffset() result required");
2994 return NULL;
2995 }
Tim Peters52dcce22003-01-23 16:36:11 +00002996
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002997 dst = call_dst(dt->tzinfo, (PyObject *)dt, &none);
2998 if (dst == -1 && PyErr_Occurred())
2999 return NULL;
3000 if (none) {
3001 PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
3002 "dst() result required");
3003 return NULL;
3004 }
Tim Peters52dcce22003-01-23 16:36:11 +00003005
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003006 y = GET_YEAR(dt);
3007 m = GET_MONTH(dt);
3008 d = GET_DAY(dt);
3009 hh = DATE_GET_HOUR(dt);
3010 mm = DATE_GET_MINUTE(dt);
3011 ss = DATE_GET_SECOND(dt);
3012 us = DATE_GET_MICROSECOND(dt);
Tim Peters52dcce22003-01-23 16:36:11 +00003013
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003014 delta = off - dst;
3015 mm += delta;
3016 if ((mm < 0 || mm >= 60) &&
3017 normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
3018 return NULL;
3019 result = new_datetime(y, m, d, hh, mm, ss, us, dt->tzinfo);
3020 if (result == NULL)
3021 return result;
Tim Peters52dcce22003-01-23 16:36:11 +00003022
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003023 dst = call_dst(dt->tzinfo, result, &none);
3024 if (dst == -1 && PyErr_Occurred())
3025 goto Fail;
3026 if (none)
3027 goto Inconsistent;
3028 if (dst == 0)
3029 return result;
Tim Peters52dcce22003-01-23 16:36:11 +00003030
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003031 mm += dst;
3032 if ((mm < 0 || mm >= 60) &&
3033 normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
3034 goto Fail;
3035 Py_DECREF(result);
3036 result = new_datetime(y, m, d, hh, mm, ss, us, dt->tzinfo);
3037 return result;
Tim Peters52dcce22003-01-23 16:36:11 +00003038
3039Inconsistent:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003040 PyErr_SetString(PyExc_ValueError, "fromutc: tz.dst() gave"
3041 "inconsistent results; cannot convert");
Tim Peters52dcce22003-01-23 16:36:11 +00003042
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003043 /* fall thru to failure */
Tim Peters52dcce22003-01-23 16:36:11 +00003044Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003045 Py_DECREF(result);
3046 return NULL;
Tim Peters52dcce22003-01-23 16:36:11 +00003047}
3048
Tim Peters2a799bf2002-12-16 20:18:38 +00003049/*
3050 * Pickle support. This is solely so that tzinfo subclasses can use
Guido van Rossum177e41a2003-01-30 22:06:23 +00003051 * pickling -- tzinfo itself is supposed to be uninstantiable.
Tim Peters2a799bf2002-12-16 20:18:38 +00003052 */
3053
Guido van Rossum177e41a2003-01-30 22:06:23 +00003054static PyObject *
3055tzinfo_reduce(PyObject *self)
3056{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003057 PyObject *args, *state, *tmp;
3058 PyObject *getinitargs, *getstate;
Tim Peters2a799bf2002-12-16 20:18:38 +00003059
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003060 tmp = PyTuple_New(0);
3061 if (tmp == NULL)
3062 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00003063
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003064 getinitargs = PyObject_GetAttrString(self, "__getinitargs__");
3065 if (getinitargs != NULL) {
3066 args = PyObject_CallObject(getinitargs, tmp);
3067 Py_DECREF(getinitargs);
3068 if (args == NULL) {
3069 Py_DECREF(tmp);
3070 return NULL;
3071 }
3072 }
3073 else {
3074 PyErr_Clear();
3075 args = tmp;
3076 Py_INCREF(args);
3077 }
Guido van Rossum177e41a2003-01-30 22:06:23 +00003078
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003079 getstate = PyObject_GetAttrString(self, "__getstate__");
3080 if (getstate != NULL) {
3081 state = PyObject_CallObject(getstate, tmp);
3082 Py_DECREF(getstate);
3083 if (state == NULL) {
3084 Py_DECREF(args);
3085 Py_DECREF(tmp);
3086 return NULL;
3087 }
3088 }
3089 else {
3090 PyObject **dictptr;
3091 PyErr_Clear();
3092 state = Py_None;
3093 dictptr = _PyObject_GetDictPtr(self);
3094 if (dictptr && *dictptr && PyDict_Size(*dictptr))
3095 state = *dictptr;
3096 Py_INCREF(state);
3097 }
Guido van Rossum177e41a2003-01-30 22:06:23 +00003098
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003099 Py_DECREF(tmp);
Guido van Rossum177e41a2003-01-30 22:06:23 +00003100
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003101 if (state == Py_None) {
3102 Py_DECREF(state);
3103 return Py_BuildValue("(ON)", Py_TYPE(self), args);
3104 }
3105 else
3106 return Py_BuildValue("(ONN)", Py_TYPE(self), args, state);
Guido van Rossum177e41a2003-01-30 22:06:23 +00003107}
Tim Peters2a799bf2002-12-16 20:18:38 +00003108
3109static PyMethodDef tzinfo_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00003110
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003111 {"tzname", (PyCFunction)tzinfo_tzname, METH_O,
3112 PyDoc_STR("datetime -> string name of time zone.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003113
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003114 {"utcoffset", (PyCFunction)tzinfo_utcoffset, METH_O,
3115 PyDoc_STR("datetime -> minutes east of UTC (negative for "
3116 "west of UTC).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003117
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003118 {"dst", (PyCFunction)tzinfo_dst, METH_O,
3119 PyDoc_STR("datetime -> DST offset in minutes east of UTC.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003120
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003121 {"fromutc", (PyCFunction)tzinfo_fromutc, METH_O,
3122 PyDoc_STR("datetime in UTC -> datetime in local time.")},
Tim Peters52dcce22003-01-23 16:36:11 +00003123
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003124 {"__reduce__", (PyCFunction)tzinfo_reduce, METH_NOARGS,
3125 PyDoc_STR("-> (cls, state)")},
Guido van Rossum177e41a2003-01-30 22:06:23 +00003126
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003127 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00003128};
3129
3130static char tzinfo_doc[] =
3131PyDoc_STR("Abstract base class for time zone info objects.");
3132
Neal Norwitz227b5332006-03-22 09:28:35 +00003133static PyTypeObject PyDateTime_TZInfoType = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003134 PyVarObject_HEAD_INIT(NULL, 0)
3135 "datetime.tzinfo", /* tp_name */
3136 sizeof(PyDateTime_TZInfo), /* tp_basicsize */
3137 0, /* tp_itemsize */
3138 0, /* tp_dealloc */
3139 0, /* tp_print */
3140 0, /* tp_getattr */
3141 0, /* tp_setattr */
3142 0, /* tp_reserved */
3143 0, /* tp_repr */
3144 0, /* tp_as_number */
3145 0, /* tp_as_sequence */
3146 0, /* tp_as_mapping */
3147 0, /* tp_hash */
3148 0, /* tp_call */
3149 0, /* tp_str */
3150 PyObject_GenericGetAttr, /* tp_getattro */
3151 0, /* tp_setattro */
3152 0, /* tp_as_buffer */
3153 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
3154 tzinfo_doc, /* tp_doc */
3155 0, /* tp_traverse */
3156 0, /* tp_clear */
3157 0, /* tp_richcompare */
3158 0, /* tp_weaklistoffset */
3159 0, /* tp_iter */
3160 0, /* tp_iternext */
3161 tzinfo_methods, /* tp_methods */
3162 0, /* tp_members */
3163 0, /* tp_getset */
3164 0, /* tp_base */
3165 0, /* tp_dict */
3166 0, /* tp_descr_get */
3167 0, /* tp_descr_set */
3168 0, /* tp_dictoffset */
3169 0, /* tp_init */
3170 0, /* tp_alloc */
3171 PyType_GenericNew, /* tp_new */
3172 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00003173};
3174
3175/*
Tim Peters37f39822003-01-10 03:49:02 +00003176 * PyDateTime_Time implementation.
Tim Peters2a799bf2002-12-16 20:18:38 +00003177 */
3178
Tim Peters37f39822003-01-10 03:49:02 +00003179/* Accessor properties.
Tim Peters2a799bf2002-12-16 20:18:38 +00003180 */
3181
3182static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003183time_hour(PyDateTime_Time *self, void *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00003184{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003185 return PyLong_FromLong(TIME_GET_HOUR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00003186}
3187
Tim Peters37f39822003-01-10 03:49:02 +00003188static PyObject *
3189time_minute(PyDateTime_Time *self, void *unused)
3190{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003191 return PyLong_FromLong(TIME_GET_MINUTE(self));
Tim Peters37f39822003-01-10 03:49:02 +00003192}
3193
3194/* The name time_second conflicted with some platform header file. */
3195static PyObject *
3196py_time_second(PyDateTime_Time *self, void *unused)
3197{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003198 return PyLong_FromLong(TIME_GET_SECOND(self));
Tim Peters37f39822003-01-10 03:49:02 +00003199}
3200
3201static PyObject *
3202time_microsecond(PyDateTime_Time *self, void *unused)
3203{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003204 return PyLong_FromLong(TIME_GET_MICROSECOND(self));
Tim Peters37f39822003-01-10 03:49:02 +00003205}
3206
3207static PyObject *
3208time_tzinfo(PyDateTime_Time *self, void *unused)
3209{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003210 PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
3211 Py_INCREF(result);
3212 return result;
Tim Peters37f39822003-01-10 03:49:02 +00003213}
3214
3215static PyGetSetDef time_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003216 {"hour", (getter)time_hour},
3217 {"minute", (getter)time_minute},
3218 {"second", (getter)py_time_second},
3219 {"microsecond", (getter)time_microsecond},
3220 {"tzinfo", (getter)time_tzinfo},
3221 {NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00003222};
3223
3224/*
3225 * Constructors.
3226 */
3227
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003228static char *time_kws[] = {"hour", "minute", "second", "microsecond",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003229 "tzinfo", NULL};
Tim Peters12bf3392002-12-24 05:41:27 +00003230
Tim Peters2a799bf2002-12-16 20:18:38 +00003231static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003232time_new(PyTypeObject *type, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003233{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003234 PyObject *self = NULL;
3235 PyObject *state;
3236 int hour = 0;
3237 int minute = 0;
3238 int second = 0;
3239 int usecond = 0;
3240 PyObject *tzinfo = Py_None;
Tim Peters2a799bf2002-12-16 20:18:38 +00003241
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003242 /* Check for invocation from pickle with __getstate__ state */
3243 if (PyTuple_GET_SIZE(args) >= 1 &&
3244 PyTuple_GET_SIZE(args) <= 2 &&
3245 PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) &&
3246 PyBytes_GET_SIZE(state) == _PyDateTime_TIME_DATASIZE &&
3247 ((unsigned char) (PyBytes_AS_STRING(state)[0])) < 24)
3248 {
3249 PyDateTime_Time *me;
3250 char aware;
Tim Peters70533e22003-02-01 04:40:04 +00003251
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003252 if (PyTuple_GET_SIZE(args) == 2) {
3253 tzinfo = PyTuple_GET_ITEM(args, 1);
3254 if (check_tzinfo_subclass(tzinfo) < 0) {
3255 PyErr_SetString(PyExc_TypeError, "bad "
3256 "tzinfo state arg");
3257 return NULL;
3258 }
3259 }
3260 aware = (char)(tzinfo != Py_None);
3261 me = (PyDateTime_Time *) (type->tp_alloc(type, aware));
3262 if (me != NULL) {
3263 char *pdata = PyBytes_AS_STRING(state);
Tim Peters70533e22003-02-01 04:40:04 +00003264
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003265 memcpy(me->data, pdata, _PyDateTime_TIME_DATASIZE);
3266 me->hashcode = -1;
3267 me->hastzinfo = aware;
3268 if (aware) {
3269 Py_INCREF(tzinfo);
3270 me->tzinfo = tzinfo;
3271 }
3272 }
3273 return (PyObject *)me;
3274 }
Guido van Rossum177e41a2003-01-30 22:06:23 +00003275
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003276 if (PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO", time_kws,
3277 &hour, &minute, &second, &usecond,
3278 &tzinfo)) {
3279 if (check_time_args(hour, minute, second, usecond) < 0)
3280 return NULL;
3281 if (check_tzinfo_subclass(tzinfo) < 0)
3282 return NULL;
3283 self = new_time_ex(hour, minute, second, usecond, tzinfo,
3284 type);
3285 }
3286 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00003287}
3288
3289/*
3290 * Destructor.
3291 */
3292
3293static void
Tim Peters37f39822003-01-10 03:49:02 +00003294time_dealloc(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003295{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003296 if (HASTZINFO(self)) {
3297 Py_XDECREF(self->tzinfo);
3298 }
3299 Py_TYPE(self)->tp_free((PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00003300}
3301
3302/*
Tim Peters855fe882002-12-22 03:43:39 +00003303 * Indirect access to tzinfo methods.
Tim Peters2a799bf2002-12-16 20:18:38 +00003304 */
3305
Tim Peters2a799bf2002-12-16 20:18:38 +00003306/* These are all METH_NOARGS, so don't need to check the arglist. */
3307static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003308time_utcoffset(PyDateTime_Time *self, PyObject *unused) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003309 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
3310 "utcoffset", Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00003311}
3312
3313static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003314time_dst(PyDateTime_Time *self, PyObject *unused) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003315 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
3316 "dst", Py_None);
Tim Peters855fe882002-12-22 03:43:39 +00003317}
3318
3319static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003320time_tzname(PyDateTime_Time *self, PyObject *unused) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003321 return call_tzname(HASTZINFO(self) ? self->tzinfo : Py_None,
3322 Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00003323}
3324
3325/*
Tim Peters37f39822003-01-10 03:49:02 +00003326 * Various ways to turn a time into a string.
Tim Peters2a799bf2002-12-16 20:18:38 +00003327 */
3328
3329static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003330time_repr(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003331{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003332 const char *type_name = Py_TYPE(self)->tp_name;
3333 int h = TIME_GET_HOUR(self);
3334 int m = TIME_GET_MINUTE(self);
3335 int s = TIME_GET_SECOND(self);
3336 int us = TIME_GET_MICROSECOND(self);
3337 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00003338
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003339 if (us)
3340 result = PyUnicode_FromFormat("%s(%d, %d, %d, %d)",
3341 type_name, h, m, s, us);
3342 else if (s)
3343 result = PyUnicode_FromFormat("%s(%d, %d, %d)",
3344 type_name, h, m, s);
3345 else
3346 result = PyUnicode_FromFormat("%s(%d, %d)", type_name, h, m);
3347 if (result != NULL && HASTZINFO(self))
3348 result = append_keyword_tzinfo(result, self->tzinfo);
3349 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00003350}
3351
Tim Peters37f39822003-01-10 03:49:02 +00003352static PyObject *
3353time_str(PyDateTime_Time *self)
3354{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003355 return PyObject_CallMethod((PyObject *)self, "isoformat", "()");
Tim Peters37f39822003-01-10 03:49:02 +00003356}
Tim Peters2a799bf2002-12-16 20:18:38 +00003357
3358static PyObject *
Thomas Wouterscf297e42007-02-23 15:07:44 +00003359time_isoformat(PyDateTime_Time *self, PyObject *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00003360{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003361 char buf[100];
3362 PyObject *result;
3363 int us = TIME_GET_MICROSECOND(self);;
Tim Peters2a799bf2002-12-16 20:18:38 +00003364
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003365 if (us)
3366 result = PyUnicode_FromFormat("%02d:%02d:%02d.%06d",
3367 TIME_GET_HOUR(self),
3368 TIME_GET_MINUTE(self),
3369 TIME_GET_SECOND(self),
3370 us);
3371 else
3372 result = PyUnicode_FromFormat("%02d:%02d:%02d",
3373 TIME_GET_HOUR(self),
3374 TIME_GET_MINUTE(self),
3375 TIME_GET_SECOND(self));
Tim Peters37f39822003-01-10 03:49:02 +00003376
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003377 if (result == NULL || ! HASTZINFO(self) || self->tzinfo == Py_None)
3378 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00003379
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003380 /* We need to append the UTC offset. */
3381 if (format_utcoffset(buf, sizeof(buf), ":", self->tzinfo,
3382 Py_None) < 0) {
3383 Py_DECREF(result);
3384 return NULL;
3385 }
3386 PyUnicode_AppendAndDel(&result, PyUnicode_FromString(buf));
3387 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00003388}
3389
Tim Peters37f39822003-01-10 03:49:02 +00003390static PyObject *
3391time_strftime(PyDateTime_Time *self, PyObject *args, PyObject *kw)
3392{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003393 PyObject *result;
3394 PyObject *tuple;
3395 PyObject *format;
3396 static char *keywords[] = {"format", NULL};
Tim Peters37f39822003-01-10 03:49:02 +00003397
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003398 if (! PyArg_ParseTupleAndKeywords(args, kw, "U:strftime", keywords,
3399 &format))
3400 return NULL;
Tim Peters37f39822003-01-10 03:49:02 +00003401
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003402 /* Python's strftime does insane things with the year part of the
3403 * timetuple. The year is forced to (the otherwise nonsensical)
3404 * 1900 to worm around that.
3405 */
3406 tuple = Py_BuildValue("iiiiiiiii",
3407 1900, 1, 1, /* year, month, day */
3408 TIME_GET_HOUR(self),
3409 TIME_GET_MINUTE(self),
3410 TIME_GET_SECOND(self),
3411 0, 1, -1); /* weekday, daynum, dst */
3412 if (tuple == NULL)
3413 return NULL;
3414 assert(PyTuple_Size(tuple) == 9);
3415 result = wrap_strftime((PyObject *)self, format, tuple,
3416 Py_None);
3417 Py_DECREF(tuple);
3418 return result;
Tim Peters37f39822003-01-10 03:49:02 +00003419}
Tim Peters2a799bf2002-12-16 20:18:38 +00003420
3421/*
3422 * Miscellaneous methods.
3423 */
3424
Tim Peters37f39822003-01-10 03:49:02 +00003425static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00003426time_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters37f39822003-01-10 03:49:02 +00003427{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003428 int diff;
3429 naivety n1, n2;
3430 int offset1, offset2;
Tim Peters37f39822003-01-10 03:49:02 +00003431
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003432 if (! PyTime_Check(other)) {
3433 Py_INCREF(Py_NotImplemented);
3434 return Py_NotImplemented;
3435 }
3436 if (classify_two_utcoffsets(self, &offset1, &n1, Py_None,
3437 other, &offset2, &n2, Py_None) < 0)
3438 return NULL;
3439 assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
3440 /* If they're both naive, or both aware and have the same offsets,
3441 * we get off cheap. Note that if they're both naive, offset1 ==
3442 * offset2 == 0 at this point.
3443 */
3444 if (n1 == n2 && offset1 == offset2) {
3445 diff = memcmp(((PyDateTime_Time *)self)->data,
3446 ((PyDateTime_Time *)other)->data,
3447 _PyDateTime_TIME_DATASIZE);
3448 return diff_to_bool(diff, op);
3449 }
Tim Peters37f39822003-01-10 03:49:02 +00003450
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003451 if (n1 == OFFSET_AWARE && n2 == OFFSET_AWARE) {
3452 assert(offset1 != offset2); /* else last "if" handled it */
3453 /* Convert everything except microseconds to seconds. These
3454 * can't overflow (no more than the # of seconds in 2 days).
3455 */
3456 offset1 = TIME_GET_HOUR(self) * 3600 +
3457 (TIME_GET_MINUTE(self) - offset1) * 60 +
3458 TIME_GET_SECOND(self);
3459 offset2 = TIME_GET_HOUR(other) * 3600 +
3460 (TIME_GET_MINUTE(other) - offset2) * 60 +
3461 TIME_GET_SECOND(other);
3462 diff = offset1 - offset2;
3463 if (diff == 0)
3464 diff = TIME_GET_MICROSECOND(self) -
3465 TIME_GET_MICROSECOND(other);
3466 return diff_to_bool(diff, op);
3467 }
Tim Peters37f39822003-01-10 03:49:02 +00003468
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003469 assert(n1 != n2);
3470 PyErr_SetString(PyExc_TypeError,
3471 "can't compare offset-naive and "
3472 "offset-aware times");
3473 return NULL;
Tim Peters37f39822003-01-10 03:49:02 +00003474}
3475
3476static long
3477time_hash(PyDateTime_Time *self)
3478{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003479 if (self->hashcode == -1) {
3480 naivety n;
3481 int offset;
3482 PyObject *temp;
Tim Peters37f39822003-01-10 03:49:02 +00003483
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003484 n = classify_utcoffset((PyObject *)self, Py_None, &offset);
3485 assert(n != OFFSET_UNKNOWN);
3486 if (n == OFFSET_ERROR)
3487 return -1;
Tim Peters37f39822003-01-10 03:49:02 +00003488
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003489 /* Reduce this to a hash of another object. */
3490 if (offset == 0) {
3491 self->hashcode = generic_hash(
3492 (unsigned char *)self->data, _PyDateTime_TIME_DATASIZE);
3493 return self->hashcode;
3494 }
3495 else {
3496 int hour;
3497 int minute;
Tim Peters37f39822003-01-10 03:49:02 +00003498
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003499 assert(n == OFFSET_AWARE);
3500 assert(HASTZINFO(self));
3501 hour = divmod(TIME_GET_HOUR(self) * 60 +
3502 TIME_GET_MINUTE(self) - offset,
3503 60,
3504 &minute);
3505 if (0 <= hour && hour < 24)
3506 temp = new_time(hour, minute,
3507 TIME_GET_SECOND(self),
3508 TIME_GET_MICROSECOND(self),
3509 Py_None);
3510 else
3511 temp = Py_BuildValue("iiii",
3512 hour, minute,
3513 TIME_GET_SECOND(self),
3514 TIME_GET_MICROSECOND(self));
3515 }
3516 if (temp != NULL) {
3517 self->hashcode = PyObject_Hash(temp);
3518 Py_DECREF(temp);
3519 }
3520 }
3521 return self->hashcode;
Tim Peters37f39822003-01-10 03:49:02 +00003522}
Tim Peters2a799bf2002-12-16 20:18:38 +00003523
Tim Peters12bf3392002-12-24 05:41:27 +00003524static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003525time_replace(PyDateTime_Time *self, PyObject *args, PyObject *kw)
Tim Peters12bf3392002-12-24 05:41:27 +00003526{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003527 PyObject *clone;
3528 PyObject *tuple;
3529 int hh = TIME_GET_HOUR(self);
3530 int mm = TIME_GET_MINUTE(self);
3531 int ss = TIME_GET_SECOND(self);
3532 int us = TIME_GET_MICROSECOND(self);
3533 PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
Tim Peters12bf3392002-12-24 05:41:27 +00003534
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003535 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO:replace",
3536 time_kws,
3537 &hh, &mm, &ss, &us, &tzinfo))
3538 return NULL;
3539 tuple = Py_BuildValue("iiiiO", hh, mm, ss, us, tzinfo);
3540 if (tuple == NULL)
3541 return NULL;
3542 clone = time_new(Py_TYPE(self), tuple, NULL);
3543 Py_DECREF(tuple);
3544 return clone;
Tim Peters12bf3392002-12-24 05:41:27 +00003545}
3546
Tim Peters2a799bf2002-12-16 20:18:38 +00003547static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00003548time_bool(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003549{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003550 int offset;
3551 int none;
Tim Peters2a799bf2002-12-16 20:18:38 +00003552
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003553 if (TIME_GET_SECOND(self) || TIME_GET_MICROSECOND(self)) {
3554 /* Since utcoffset is in whole minutes, nothing can
3555 * alter the conclusion that this is nonzero.
3556 */
3557 return 1;
3558 }
3559 offset = 0;
3560 if (HASTZINFO(self) && self->tzinfo != Py_None) {
3561 offset = call_utcoffset(self->tzinfo, Py_None, &none);
3562 if (offset == -1 && PyErr_Occurred())
3563 return -1;
3564 }
3565 return (TIME_GET_MINUTE(self) - offset + TIME_GET_HOUR(self)*60) != 0;
Tim Peters2a799bf2002-12-16 20:18:38 +00003566}
3567
Tim Peters371935f2003-02-01 01:52:50 +00003568/* Pickle support, a simple use of __reduce__. */
Tim Peters2a799bf2002-12-16 20:18:38 +00003569
Tim Peters33e0f382003-01-10 02:05:14 +00003570/* Let basestate be the non-tzinfo data string.
Tim Peters2a799bf2002-12-16 20:18:38 +00003571 * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
3572 * So it's a tuple in any (non-error) case.
Tim Petersb57f8f02003-02-01 02:54:15 +00003573 * __getstate__ isn't exposed.
Tim Peters2a799bf2002-12-16 20:18:38 +00003574 */
3575static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003576time_getstate(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003577{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003578 PyObject *basestate;
3579 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00003580
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003581 basestate = PyBytes_FromStringAndSize((char *)self->data,
3582 _PyDateTime_TIME_DATASIZE);
3583 if (basestate != NULL) {
3584 if (! HASTZINFO(self) || self->tzinfo == Py_None)
3585 result = PyTuple_Pack(1, basestate);
3586 else
3587 result = PyTuple_Pack(2, basestate, self->tzinfo);
3588 Py_DECREF(basestate);
3589 }
3590 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00003591}
3592
3593static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00003594time_reduce(PyDateTime_Time *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00003595{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003596 return Py_BuildValue("(ON)", Py_TYPE(self), time_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00003597}
3598
Tim Peters37f39822003-01-10 03:49:02 +00003599static PyMethodDef time_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00003600
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003601 {"isoformat", (PyCFunction)time_isoformat, METH_NOARGS,
3602 PyDoc_STR("Return string in ISO 8601 format, HH:MM:SS[.mmmmmm]"
3603 "[+HH:MM].")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003604
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003605 {"strftime", (PyCFunction)time_strftime, METH_VARARGS | METH_KEYWORDS,
3606 PyDoc_STR("format -> strftime() style string.")},
Tim Peters37f39822003-01-10 03:49:02 +00003607
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003608 {"__format__", (PyCFunction)date_format, METH_VARARGS,
3609 PyDoc_STR("Formats self with strftime.")},
Eric Smith1ba31142007-09-11 18:06:02 +00003610
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003611 {"utcoffset", (PyCFunction)time_utcoffset, METH_NOARGS,
3612 PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003613
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003614 {"tzname", (PyCFunction)time_tzname, METH_NOARGS,
3615 PyDoc_STR("Return self.tzinfo.tzname(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003616
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003617 {"dst", (PyCFunction)time_dst, METH_NOARGS,
3618 PyDoc_STR("Return self.tzinfo.dst(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003619
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003620 {"replace", (PyCFunction)time_replace, METH_VARARGS | METH_KEYWORDS,
3621 PyDoc_STR("Return time with new specified fields.")},
Tim Peters12bf3392002-12-24 05:41:27 +00003622
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003623 {"__reduce__", (PyCFunction)time_reduce, METH_NOARGS,
3624 PyDoc_STR("__reduce__() -> (cls, state)")},
Guido van Rossum177e41a2003-01-30 22:06:23 +00003625
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003626 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00003627};
3628
Tim Peters37f39822003-01-10 03:49:02 +00003629static char time_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00003630PyDoc_STR("time([hour[, minute[, second[, microsecond[, tzinfo]]]]]) --> a time object\n\
3631\n\
3632All arguments are optional. tzinfo may be None, or an instance of\n\
3633a tzinfo subclass. The remaining arguments may be ints or longs.\n");
Tim Peters2a799bf2002-12-16 20:18:38 +00003634
Tim Peters37f39822003-01-10 03:49:02 +00003635static PyNumberMethods time_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003636 0, /* nb_add */
3637 0, /* nb_subtract */
3638 0, /* nb_multiply */
3639 0, /* nb_remainder */
3640 0, /* nb_divmod */
3641 0, /* nb_power */
3642 0, /* nb_negative */
3643 0, /* nb_positive */
3644 0, /* nb_absolute */
3645 (inquiry)time_bool, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00003646};
3647
Neal Norwitz227b5332006-03-22 09:28:35 +00003648static PyTypeObject PyDateTime_TimeType = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003649 PyVarObject_HEAD_INIT(NULL, 0)
3650 "datetime.time", /* tp_name */
3651 sizeof(PyDateTime_Time), /* tp_basicsize */
3652 0, /* tp_itemsize */
3653 (destructor)time_dealloc, /* tp_dealloc */
3654 0, /* tp_print */
3655 0, /* tp_getattr */
3656 0, /* tp_setattr */
3657 0, /* tp_reserved */
3658 (reprfunc)time_repr, /* tp_repr */
3659 &time_as_number, /* tp_as_number */
3660 0, /* tp_as_sequence */
3661 0, /* tp_as_mapping */
3662 (hashfunc)time_hash, /* tp_hash */
3663 0, /* tp_call */
3664 (reprfunc)time_str, /* tp_str */
3665 PyObject_GenericGetAttr, /* tp_getattro */
3666 0, /* tp_setattro */
3667 0, /* tp_as_buffer */
3668 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
3669 time_doc, /* tp_doc */
3670 0, /* tp_traverse */
3671 0, /* tp_clear */
3672 time_richcompare, /* tp_richcompare */
3673 0, /* tp_weaklistoffset */
3674 0, /* tp_iter */
3675 0, /* tp_iternext */
3676 time_methods, /* tp_methods */
3677 0, /* tp_members */
3678 time_getset, /* tp_getset */
3679 0, /* tp_base */
3680 0, /* tp_dict */
3681 0, /* tp_descr_get */
3682 0, /* tp_descr_set */
3683 0, /* tp_dictoffset */
3684 0, /* tp_init */
3685 time_alloc, /* tp_alloc */
3686 time_new, /* tp_new */
3687 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00003688};
3689
3690/*
Tim Petersa9bc1682003-01-11 03:39:11 +00003691 * PyDateTime_DateTime implementation.
Tim Peters2a799bf2002-12-16 20:18:38 +00003692 */
3693
Tim Petersa9bc1682003-01-11 03:39:11 +00003694/* Accessor properties. Properties for day, month, and year are inherited
3695 * from date.
Tim Peters2a799bf2002-12-16 20:18:38 +00003696 */
3697
3698static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003699datetime_hour(PyDateTime_DateTime *self, void *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00003700{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003701 return PyLong_FromLong(DATE_GET_HOUR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00003702}
3703
Tim Petersa9bc1682003-01-11 03:39:11 +00003704static PyObject *
3705datetime_minute(PyDateTime_DateTime *self, void *unused)
3706{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003707 return PyLong_FromLong(DATE_GET_MINUTE(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00003708}
3709
3710static PyObject *
3711datetime_second(PyDateTime_DateTime *self, void *unused)
3712{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003713 return PyLong_FromLong(DATE_GET_SECOND(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00003714}
3715
3716static PyObject *
3717datetime_microsecond(PyDateTime_DateTime *self, void *unused)
3718{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003719 return PyLong_FromLong(DATE_GET_MICROSECOND(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00003720}
3721
3722static PyObject *
3723datetime_tzinfo(PyDateTime_DateTime *self, void *unused)
3724{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003725 PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
3726 Py_INCREF(result);
3727 return result;
Tim Petersa9bc1682003-01-11 03:39:11 +00003728}
3729
3730static PyGetSetDef datetime_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003731 {"hour", (getter)datetime_hour},
3732 {"minute", (getter)datetime_minute},
3733 {"second", (getter)datetime_second},
3734 {"microsecond", (getter)datetime_microsecond},
3735 {"tzinfo", (getter)datetime_tzinfo},
3736 {NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00003737};
3738
3739/*
3740 * Constructors.
Tim Peters2a799bf2002-12-16 20:18:38 +00003741 */
3742
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003743static char *datetime_kws[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003744 "year", "month", "day", "hour", "minute", "second",
3745 "microsecond", "tzinfo", NULL
Tim Peters12bf3392002-12-24 05:41:27 +00003746};
3747
Tim Peters2a799bf2002-12-16 20:18:38 +00003748static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003749datetime_new(PyTypeObject *type, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003750{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003751 PyObject *self = NULL;
3752 PyObject *state;
3753 int year;
3754 int month;
3755 int day;
3756 int hour = 0;
3757 int minute = 0;
3758 int second = 0;
3759 int usecond = 0;
3760 PyObject *tzinfo = Py_None;
Tim Peters2a799bf2002-12-16 20:18:38 +00003761
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003762 /* Check for invocation from pickle with __getstate__ state */
3763 if (PyTuple_GET_SIZE(args) >= 1 &&
3764 PyTuple_GET_SIZE(args) <= 2 &&
3765 PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) &&
3766 PyBytes_GET_SIZE(state) == _PyDateTime_DATETIME_DATASIZE &&
3767 MONTH_IS_SANE(PyBytes_AS_STRING(state)[2]))
3768 {
3769 PyDateTime_DateTime *me;
3770 char aware;
Tim Peters70533e22003-02-01 04:40:04 +00003771
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003772 if (PyTuple_GET_SIZE(args) == 2) {
3773 tzinfo = PyTuple_GET_ITEM(args, 1);
3774 if (check_tzinfo_subclass(tzinfo) < 0) {
3775 PyErr_SetString(PyExc_TypeError, "bad "
3776 "tzinfo state arg");
3777 return NULL;
3778 }
3779 }
3780 aware = (char)(tzinfo != Py_None);
3781 me = (PyDateTime_DateTime *) (type->tp_alloc(type , aware));
3782 if (me != NULL) {
3783 char *pdata = PyBytes_AS_STRING(state);
Tim Peters70533e22003-02-01 04:40:04 +00003784
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003785 memcpy(me->data, pdata, _PyDateTime_DATETIME_DATASIZE);
3786 me->hashcode = -1;
3787 me->hastzinfo = aware;
3788 if (aware) {
3789 Py_INCREF(tzinfo);
3790 me->tzinfo = tzinfo;
3791 }
3792 }
3793 return (PyObject *)me;
3794 }
Guido van Rossum177e41a2003-01-30 22:06:23 +00003795
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003796 if (PyArg_ParseTupleAndKeywords(args, kw, "iii|iiiiO", datetime_kws,
3797 &year, &month, &day, &hour, &minute,
3798 &second, &usecond, &tzinfo)) {
3799 if (check_date_args(year, month, day) < 0)
3800 return NULL;
3801 if (check_time_args(hour, minute, second, usecond) < 0)
3802 return NULL;
3803 if (check_tzinfo_subclass(tzinfo) < 0)
3804 return NULL;
3805 self = new_datetime_ex(year, month, day,
3806 hour, minute, second, usecond,
3807 tzinfo, type);
3808 }
3809 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00003810}
3811
Tim Petersa9bc1682003-01-11 03:39:11 +00003812/* TM_FUNC is the shared type of localtime() and gmtime(). */
3813typedef struct tm *(*TM_FUNC)(const time_t *timer);
3814
3815/* Internal helper.
3816 * Build datetime from a time_t and a distinct count of microseconds.
3817 * Pass localtime or gmtime for f, to control the interpretation of timet.
3818 */
3819static PyObject *
3820datetime_from_timet_and_us(PyObject *cls, TM_FUNC f, time_t timet, int us,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003821 PyObject *tzinfo)
Tim Petersa9bc1682003-01-11 03:39:11 +00003822{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003823 struct tm *tm;
3824 PyObject *result = NULL;
Tim Petersa9bc1682003-01-11 03:39:11 +00003825
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003826 tm = f(&timet);
3827 if (tm) {
3828 /* The platform localtime/gmtime may insert leap seconds,
3829 * indicated by tm->tm_sec > 59. We don't care about them,
3830 * except to the extent that passing them on to the datetime
3831 * constructor would raise ValueError for a reason that
3832 * made no sense to the user.
3833 */
3834 if (tm->tm_sec > 59)
3835 tm->tm_sec = 59;
3836 result = PyObject_CallFunction(cls, "iiiiiiiO",
3837 tm->tm_year + 1900,
3838 tm->tm_mon + 1,
3839 tm->tm_mday,
3840 tm->tm_hour,
3841 tm->tm_min,
3842 tm->tm_sec,
3843 us,
3844 tzinfo);
3845 }
3846 else
3847 PyErr_SetString(PyExc_ValueError,
3848 "timestamp out of range for "
3849 "platform localtime()/gmtime() function");
3850 return result;
Tim Petersa9bc1682003-01-11 03:39:11 +00003851}
3852
3853/* Internal helper.
3854 * Build datetime from a Python timestamp. Pass localtime or gmtime for f,
3855 * to control the interpretation of the timestamp. Since a double doesn't
3856 * have enough bits to cover a datetime's full range of precision, it's
3857 * better to call datetime_from_timet_and_us provided you have a way
3858 * to get that much precision (e.g., C time() isn't good enough).
3859 */
3860static PyObject *
3861datetime_from_timestamp(PyObject *cls, TM_FUNC f, double timestamp,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003862 PyObject *tzinfo)
Tim Petersa9bc1682003-01-11 03:39:11 +00003863{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003864 time_t timet;
3865 double fraction;
3866 int us;
Tim Petersa9bc1682003-01-11 03:39:11 +00003867
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003868 timet = _PyTime_DoubleToTimet(timestamp);
3869 if (timet == (time_t)-1 && PyErr_Occurred())
3870 return NULL;
3871 fraction = timestamp - (double)timet;
3872 us = (int)round_to_long(fraction * 1e6);
3873 if (us < 0) {
3874 /* Truncation towards zero is not what we wanted
3875 for negative numbers (Python's mod semantics) */
3876 timet -= 1;
3877 us += 1000000;
3878 }
3879 /* If timestamp is less than one microsecond smaller than a
3880 * full second, round up. Otherwise, ValueErrors are raised
3881 * for some floats. */
3882 if (us == 1000000) {
3883 timet += 1;
3884 us = 0;
3885 }
3886 return datetime_from_timet_and_us(cls, f, timet, us, tzinfo);
Tim Petersa9bc1682003-01-11 03:39:11 +00003887}
3888
3889/* Internal helper.
3890 * Build most accurate possible datetime for current time. Pass localtime or
3891 * gmtime for f as appropriate.
3892 */
3893static PyObject *
3894datetime_best_possible(PyObject *cls, TM_FUNC f, PyObject *tzinfo)
3895{
3896#ifdef HAVE_GETTIMEOFDAY
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003897 struct timeval t;
Tim Petersa9bc1682003-01-11 03:39:11 +00003898
3899#ifdef GETTIMEOFDAY_NO_TZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003900 gettimeofday(&t);
Tim Petersa9bc1682003-01-11 03:39:11 +00003901#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003902 gettimeofday(&t, (struct timezone *)NULL);
Tim Petersa9bc1682003-01-11 03:39:11 +00003903#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003904 return datetime_from_timet_and_us(cls, f, t.tv_sec, (int)t.tv_usec,
3905 tzinfo);
Tim Petersa9bc1682003-01-11 03:39:11 +00003906
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003907#else /* ! HAVE_GETTIMEOFDAY */
3908 /* No flavor of gettimeofday exists on this platform. Python's
3909 * time.time() does a lot of other platform tricks to get the
3910 * best time it can on the platform, and we're not going to do
3911 * better than that (if we could, the better code would belong
3912 * in time.time()!) We're limited by the precision of a double,
3913 * though.
3914 */
3915 PyObject *time;
3916 double dtime;
Tim Petersa9bc1682003-01-11 03:39:11 +00003917
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003918 time = time_time();
3919 if (time == NULL)
3920 return NULL;
3921 dtime = PyFloat_AsDouble(time);
3922 Py_DECREF(time);
3923 if (dtime == -1.0 && PyErr_Occurred())
3924 return NULL;
3925 return datetime_from_timestamp(cls, f, dtime, tzinfo);
3926#endif /* ! HAVE_GETTIMEOFDAY */
Tim Petersa9bc1682003-01-11 03:39:11 +00003927}
3928
Tim Peters2a799bf2002-12-16 20:18:38 +00003929/* Return best possible local time -- this isn't constrained by the
3930 * precision of a timestamp.
3931 */
3932static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003933datetime_now(PyObject *cls, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003934{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003935 PyObject *self;
3936 PyObject *tzinfo = Py_None;
3937 static char *keywords[] = {"tz", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00003938
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003939 if (! PyArg_ParseTupleAndKeywords(args, kw, "|O:now", keywords,
3940 &tzinfo))
3941 return NULL;
3942 if (check_tzinfo_subclass(tzinfo) < 0)
3943 return NULL;
Tim Peters10cadce2003-01-23 19:58:02 +00003944
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003945 self = datetime_best_possible(cls,
3946 tzinfo == Py_None ? localtime : gmtime,
3947 tzinfo);
3948 if (self != NULL && tzinfo != Py_None) {
3949 /* Convert UTC to tzinfo's zone. */
3950 PyObject *temp = self;
3951 self = PyObject_CallMethod(tzinfo, "fromutc", "O", self);
3952 Py_DECREF(temp);
3953 }
3954 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00003955}
3956
Tim Petersa9bc1682003-01-11 03:39:11 +00003957/* Return best possible UTC time -- this isn't constrained by the
3958 * precision of a timestamp.
3959 */
3960static PyObject *
3961datetime_utcnow(PyObject *cls, PyObject *dummy)
3962{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003963 return datetime_best_possible(cls, gmtime, Py_None);
Tim Petersa9bc1682003-01-11 03:39:11 +00003964}
3965
Tim Peters2a799bf2002-12-16 20:18:38 +00003966/* Return new local datetime from timestamp (Python timestamp -- a double). */
3967static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003968datetime_fromtimestamp(PyObject *cls, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003969{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003970 PyObject *self;
3971 double timestamp;
3972 PyObject *tzinfo = Py_None;
3973 static char *keywords[] = {"timestamp", "tz", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00003974
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003975 if (! PyArg_ParseTupleAndKeywords(args, kw, "d|O:fromtimestamp",
3976 keywords, &timestamp, &tzinfo))
3977 return NULL;
3978 if (check_tzinfo_subclass(tzinfo) < 0)
3979 return NULL;
Tim Peters2a44a8d2003-01-23 20:53:10 +00003980
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003981 self = datetime_from_timestamp(cls,
3982 tzinfo == Py_None ? localtime : gmtime,
3983 timestamp,
3984 tzinfo);
3985 if (self != NULL && tzinfo != Py_None) {
3986 /* Convert UTC to tzinfo's zone. */
3987 PyObject *temp = self;
3988 self = PyObject_CallMethod(tzinfo, "fromutc", "O", self);
3989 Py_DECREF(temp);
3990 }
3991 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00003992}
3993
Tim Petersa9bc1682003-01-11 03:39:11 +00003994/* Return new UTC datetime from timestamp (Python timestamp -- a double). */
3995static PyObject *
3996datetime_utcfromtimestamp(PyObject *cls, PyObject *args)
3997{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003998 double timestamp;
3999 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004000
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004001 if (PyArg_ParseTuple(args, "d:utcfromtimestamp", &timestamp))
4002 result = datetime_from_timestamp(cls, gmtime, timestamp,
4003 Py_None);
4004 return result;
Tim Petersa9bc1682003-01-11 03:39:11 +00004005}
4006
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004007/* Return new datetime from time.strptime(). */
4008static PyObject *
4009datetime_strptime(PyObject *cls, PyObject *args)
4010{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004011 static PyObject *module = NULL;
4012 PyObject *result = NULL, *obj, *st = NULL, *frac = NULL;
4013 const Py_UNICODE *string, *format;
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004014
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004015 if (!PyArg_ParseTuple(args, "uu:strptime", &string, &format))
4016 return NULL;
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004017
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004018 if (module == NULL &&
4019 (module = PyImport_ImportModuleNoBlock("_strptime")) == NULL)
4020 return NULL;
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004021
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004022 /* _strptime._strptime returns a two-element tuple. The first
4023 element is a time.struct_time object. The second is the
4024 microseconds (which are not defined for time.struct_time). */
4025 obj = PyObject_CallMethod(module, "_strptime", "uu", string, format);
4026 if (obj != NULL) {
4027 int i, good_timetuple = 1;
4028 long int ia[7];
4029 if (PySequence_Check(obj) && PySequence_Size(obj) == 2) {
4030 st = PySequence_GetItem(obj, 0);
4031 frac = PySequence_GetItem(obj, 1);
4032 if (st == NULL || frac == NULL)
4033 good_timetuple = 0;
4034 /* copy y/m/d/h/m/s values out of the
4035 time.struct_time */
4036 if (good_timetuple &&
4037 PySequence_Check(st) &&
4038 PySequence_Size(st) >= 6) {
4039 for (i=0; i < 6; i++) {
4040 PyObject *p = PySequence_GetItem(st, i);
4041 if (p == NULL) {
4042 good_timetuple = 0;
4043 break;
4044 }
4045 if (PyLong_Check(p))
4046 ia[i] = PyLong_AsLong(p);
4047 else
4048 good_timetuple = 0;
4049 Py_DECREF(p);
4050 }
4051/* if (PyLong_CheckExact(p)) {
4052 ia[i] = PyLong_AsLongAndOverflow(p, &overflow);
4053 if (overflow)
4054 good_timetuple = 0;
4055 }
4056 else
4057 good_timetuple = 0;
4058 Py_DECREF(p);
4059*/ }
4060 else
4061 good_timetuple = 0;
4062 /* follow that up with a little dose of microseconds */
4063 if (PyLong_Check(frac))
4064 ia[6] = PyLong_AsLong(frac);
4065 else
4066 good_timetuple = 0;
4067 }
4068 else
4069 good_timetuple = 0;
4070 if (good_timetuple)
4071 result = PyObject_CallFunction(cls, "iiiiiii",
4072 ia[0], ia[1], ia[2],
4073 ia[3], ia[4], ia[5],
4074 ia[6]);
4075 else
4076 PyErr_SetString(PyExc_ValueError,
4077 "unexpected value from _strptime._strptime");
4078 }
4079 Py_XDECREF(obj);
4080 Py_XDECREF(st);
4081 Py_XDECREF(frac);
4082 return result;
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004083}
4084
Tim Petersa9bc1682003-01-11 03:39:11 +00004085/* Return new datetime from date/datetime and time arguments. */
4086static PyObject *
4087datetime_combine(PyObject *cls, PyObject *args, PyObject *kw)
4088{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004089 static char *keywords[] = {"date", "time", NULL};
4090 PyObject *date;
4091 PyObject *time;
4092 PyObject *result = NULL;
Tim Petersa9bc1682003-01-11 03:39:11 +00004093
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004094 if (PyArg_ParseTupleAndKeywords(args, kw, "O!O!:combine", keywords,
4095 &PyDateTime_DateType, &date,
4096 &PyDateTime_TimeType, &time)) {
4097 PyObject *tzinfo = Py_None;
Tim Petersa9bc1682003-01-11 03:39:11 +00004098
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004099 if (HASTZINFO(time))
4100 tzinfo = ((PyDateTime_Time *)time)->tzinfo;
4101 result = PyObject_CallFunction(cls, "iiiiiiiO",
4102 GET_YEAR(date),
4103 GET_MONTH(date),
4104 GET_DAY(date),
4105 TIME_GET_HOUR(time),
4106 TIME_GET_MINUTE(time),
4107 TIME_GET_SECOND(time),
4108 TIME_GET_MICROSECOND(time),
4109 tzinfo);
4110 }
4111 return result;
Tim Petersa9bc1682003-01-11 03:39:11 +00004112}
Tim Peters2a799bf2002-12-16 20:18:38 +00004113
4114/*
4115 * Destructor.
4116 */
4117
4118static void
Tim Petersa9bc1682003-01-11 03:39:11 +00004119datetime_dealloc(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004120{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004121 if (HASTZINFO(self)) {
4122 Py_XDECREF(self->tzinfo);
4123 }
4124 Py_TYPE(self)->tp_free((PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00004125}
4126
4127/*
4128 * Indirect access to tzinfo methods.
4129 */
4130
Tim Peters2a799bf2002-12-16 20:18:38 +00004131/* These are all METH_NOARGS, so don't need to check the arglist. */
4132static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004133datetime_utcoffset(PyDateTime_DateTime *self, PyObject *unused) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004134 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
4135 "utcoffset", (PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00004136}
4137
4138static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004139datetime_dst(PyDateTime_DateTime *self, PyObject *unused) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004140 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
4141 "dst", (PyObject *)self);
Tim Peters855fe882002-12-22 03:43:39 +00004142}
4143
4144static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004145datetime_tzname(PyDateTime_DateTime *self, PyObject *unused) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004146 return call_tzname(HASTZINFO(self) ? self->tzinfo : Py_None,
4147 (PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00004148}
4149
4150/*
Tim Petersa9bc1682003-01-11 03:39:11 +00004151 * datetime arithmetic.
Tim Peters2a799bf2002-12-16 20:18:38 +00004152 */
4153
Tim Petersa9bc1682003-01-11 03:39:11 +00004154/* factor must be 1 (to add) or -1 (to subtract). The result inherits
4155 * the tzinfo state of date.
Tim Peters2a799bf2002-12-16 20:18:38 +00004156 */
4157static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004158add_datetime_timedelta(PyDateTime_DateTime *date, PyDateTime_Delta *delta,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004159 int factor)
Tim Peters2a799bf2002-12-16 20:18:38 +00004160{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004161 /* Note that the C-level additions can't overflow, because of
4162 * invariant bounds on the member values.
4163 */
4164 int year = GET_YEAR(date);
4165 int month = GET_MONTH(date);
4166 int day = GET_DAY(date) + GET_TD_DAYS(delta) * factor;
4167 int hour = DATE_GET_HOUR(date);
4168 int minute = DATE_GET_MINUTE(date);
4169 int second = DATE_GET_SECOND(date) + GET_TD_SECONDS(delta) * factor;
4170 int microsecond = DATE_GET_MICROSECOND(date) +
4171 GET_TD_MICROSECONDS(delta) * factor;
Tim Peters2a799bf2002-12-16 20:18:38 +00004172
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004173 assert(factor == 1 || factor == -1);
4174 if (normalize_datetime(&year, &month, &day,
4175 &hour, &minute, &second, &microsecond) < 0)
4176 return NULL;
4177 else
4178 return new_datetime(year, month, day,
4179 hour, minute, second, microsecond,
4180 HASTZINFO(date) ? date->tzinfo : Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004181}
4182
4183static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004184datetime_add(PyObject *left, PyObject *right)
Tim Peters2a799bf2002-12-16 20:18:38 +00004185{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004186 if (PyDateTime_Check(left)) {
4187 /* datetime + ??? */
4188 if (PyDelta_Check(right))
4189 /* datetime + delta */
4190 return add_datetime_timedelta(
4191 (PyDateTime_DateTime *)left,
4192 (PyDateTime_Delta *)right,
4193 1);
4194 }
4195 else if (PyDelta_Check(left)) {
4196 /* delta + datetime */
4197 return add_datetime_timedelta((PyDateTime_DateTime *) right,
4198 (PyDateTime_Delta *) left,
4199 1);
4200 }
4201 Py_INCREF(Py_NotImplemented);
4202 return Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00004203}
4204
4205static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004206datetime_subtract(PyObject *left, PyObject *right)
Tim Peters2a799bf2002-12-16 20:18:38 +00004207{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004208 PyObject *result = Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00004209
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004210 if (PyDateTime_Check(left)) {
4211 /* datetime - ??? */
4212 if (PyDateTime_Check(right)) {
4213 /* datetime - datetime */
4214 naivety n1, n2;
4215 int offset1, offset2;
4216 int delta_d, delta_s, delta_us;
Tim Peters2a799bf2002-12-16 20:18:38 +00004217
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004218 if (classify_two_utcoffsets(left, &offset1, &n1, left,
4219 right, &offset2, &n2,
4220 right) < 0)
4221 return NULL;
4222 assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
4223 if (n1 != n2) {
4224 PyErr_SetString(PyExc_TypeError,
4225 "can't subtract offset-naive and "
4226 "offset-aware datetimes");
4227 return NULL;
4228 }
4229 delta_d = ymd_to_ord(GET_YEAR(left),
4230 GET_MONTH(left),
4231 GET_DAY(left)) -
4232 ymd_to_ord(GET_YEAR(right),
4233 GET_MONTH(right),
4234 GET_DAY(right));
4235 /* These can't overflow, since the values are
4236 * normalized. At most this gives the number of
4237 * seconds in one day.
4238 */
4239 delta_s = (DATE_GET_HOUR(left) -
4240 DATE_GET_HOUR(right)) * 3600 +
4241 (DATE_GET_MINUTE(left) -
4242 DATE_GET_MINUTE(right)) * 60 +
4243 (DATE_GET_SECOND(left) -
4244 DATE_GET_SECOND(right));
4245 delta_us = DATE_GET_MICROSECOND(left) -
4246 DATE_GET_MICROSECOND(right);
4247 /* (left - offset1) - (right - offset2) =
4248 * (left - right) + (offset2 - offset1)
4249 */
4250 delta_s += (offset2 - offset1) * 60;
4251 result = new_delta(delta_d, delta_s, delta_us, 1);
4252 }
4253 else if (PyDelta_Check(right)) {
4254 /* datetime - delta */
4255 result = add_datetime_timedelta(
4256 (PyDateTime_DateTime *)left,
4257 (PyDateTime_Delta *)right,
4258 -1);
4259 }
4260 }
Tim Peters2a799bf2002-12-16 20:18:38 +00004261
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004262 if (result == Py_NotImplemented)
4263 Py_INCREF(result);
4264 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00004265}
4266
4267/* Various ways to turn a datetime into a string. */
4268
4269static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004270datetime_repr(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004271{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004272 const char *type_name = Py_TYPE(self)->tp_name;
4273 PyObject *baserepr;
Tim Peters2a799bf2002-12-16 20:18:38 +00004274
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004275 if (DATE_GET_MICROSECOND(self)) {
4276 baserepr = PyUnicode_FromFormat(
4277 "%s(%d, %d, %d, %d, %d, %d, %d)",
4278 type_name,
4279 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4280 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4281 DATE_GET_SECOND(self),
4282 DATE_GET_MICROSECOND(self));
4283 }
4284 else if (DATE_GET_SECOND(self)) {
4285 baserepr = PyUnicode_FromFormat(
4286 "%s(%d, %d, %d, %d, %d, %d)",
4287 type_name,
4288 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4289 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4290 DATE_GET_SECOND(self));
4291 }
4292 else {
4293 baserepr = PyUnicode_FromFormat(
4294 "%s(%d, %d, %d, %d, %d)",
4295 type_name,
4296 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4297 DATE_GET_HOUR(self), DATE_GET_MINUTE(self));
4298 }
4299 if (baserepr == NULL || ! HASTZINFO(self))
4300 return baserepr;
4301 return append_keyword_tzinfo(baserepr, self->tzinfo);
Tim Peters2a799bf2002-12-16 20:18:38 +00004302}
4303
Tim Petersa9bc1682003-01-11 03:39:11 +00004304static PyObject *
4305datetime_str(PyDateTime_DateTime *self)
4306{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004307 return PyObject_CallMethod((PyObject *)self, "isoformat", "(s)", " ");
Tim Petersa9bc1682003-01-11 03:39:11 +00004308}
Tim Peters2a799bf2002-12-16 20:18:38 +00004309
4310static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004311datetime_isoformat(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00004312{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004313 int sep = 'T';
4314 static char *keywords[] = {"sep", NULL};
4315 char buffer[100];
4316 PyObject *result;
4317 int us = DATE_GET_MICROSECOND(self);
Tim Peters2a799bf2002-12-16 20:18:38 +00004318
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004319 if (!PyArg_ParseTupleAndKeywords(args, kw, "|C:isoformat", keywords, &sep))
4320 return NULL;
4321 if (us)
4322 result = PyUnicode_FromFormat("%04d-%02d-%02d%c%02d:%02d:%02d.%06d",
4323 GET_YEAR(self), GET_MONTH(self),
4324 GET_DAY(self), (int)sep,
4325 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4326 DATE_GET_SECOND(self), us);
4327 else
4328 result = PyUnicode_FromFormat("%04d-%02d-%02d%c%02d:%02d:%02d",
4329 GET_YEAR(self), GET_MONTH(self),
4330 GET_DAY(self), (int)sep,
4331 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4332 DATE_GET_SECOND(self));
Walter Dörwaldbafa1372007-05-31 17:50:48 +00004333
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004334 if (!result || !HASTZINFO(self))
4335 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00004336
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004337 /* We need to append the UTC offset. */
4338 if (format_utcoffset(buffer, sizeof(buffer), ":", self->tzinfo,
4339 (PyObject *)self) < 0) {
4340 Py_DECREF(result);
4341 return NULL;
4342 }
4343 PyUnicode_AppendAndDel(&result, PyUnicode_FromString(buffer));
4344 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00004345}
4346
Tim Petersa9bc1682003-01-11 03:39:11 +00004347static PyObject *
4348datetime_ctime(PyDateTime_DateTime *self)
4349{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004350 return format_ctime((PyDateTime_Date *)self,
4351 DATE_GET_HOUR(self),
4352 DATE_GET_MINUTE(self),
4353 DATE_GET_SECOND(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00004354}
4355
Tim Peters2a799bf2002-12-16 20:18:38 +00004356/* Miscellaneous methods. */
4357
Tim Petersa9bc1682003-01-11 03:39:11 +00004358static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00004359datetime_richcompare(PyObject *self, PyObject *other, int op)
Tim Petersa9bc1682003-01-11 03:39:11 +00004360{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004361 int diff;
4362 naivety n1, n2;
4363 int offset1, offset2;
Tim Petersa9bc1682003-01-11 03:39:11 +00004364
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004365 if (! PyDateTime_Check(other)) {
4366 if (PyDate_Check(other)) {
4367 /* Prevent invocation of date_richcompare. We want to
4368 return NotImplemented here to give the other object
4369 a chance. But since DateTime is a subclass of
4370 Date, if the other object is a Date, it would
4371 compute an ordering based on the date part alone,
4372 and we don't want that. So force unequal or
4373 uncomparable here in that case. */
4374 if (op == Py_EQ)
4375 Py_RETURN_FALSE;
4376 if (op == Py_NE)
4377 Py_RETURN_TRUE;
4378 return cmperror(self, other);
4379 }
4380 Py_INCREF(Py_NotImplemented);
4381 return Py_NotImplemented;
4382 }
Tim Petersa9bc1682003-01-11 03:39:11 +00004383
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004384 if (classify_two_utcoffsets(self, &offset1, &n1, self,
4385 other, &offset2, &n2, other) < 0)
4386 return NULL;
4387 assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
4388 /* If they're both naive, or both aware and have the same offsets,
4389 * we get off cheap. Note that if they're both naive, offset1 ==
4390 * offset2 == 0 at this point.
4391 */
4392 if (n1 == n2 && offset1 == offset2) {
4393 diff = memcmp(((PyDateTime_DateTime *)self)->data,
4394 ((PyDateTime_DateTime *)other)->data,
4395 _PyDateTime_DATETIME_DATASIZE);
4396 return diff_to_bool(diff, op);
4397 }
Tim Petersa9bc1682003-01-11 03:39:11 +00004398
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004399 if (n1 == OFFSET_AWARE && n2 == OFFSET_AWARE) {
4400 PyDateTime_Delta *delta;
Tim Petersa9bc1682003-01-11 03:39:11 +00004401
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004402 assert(offset1 != offset2); /* else last "if" handled it */
4403 delta = (PyDateTime_Delta *)datetime_subtract((PyObject *)self,
4404 other);
4405 if (delta == NULL)
4406 return NULL;
4407 diff = GET_TD_DAYS(delta);
4408 if (diff == 0)
4409 diff = GET_TD_SECONDS(delta) |
4410 GET_TD_MICROSECONDS(delta);
4411 Py_DECREF(delta);
4412 return diff_to_bool(diff, op);
4413 }
Tim Petersa9bc1682003-01-11 03:39:11 +00004414
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004415 assert(n1 != n2);
4416 PyErr_SetString(PyExc_TypeError,
4417 "can't compare offset-naive and "
4418 "offset-aware datetimes");
4419 return NULL;
Tim Petersa9bc1682003-01-11 03:39:11 +00004420}
4421
4422static long
4423datetime_hash(PyDateTime_DateTime *self)
4424{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004425 if (self->hashcode == -1) {
4426 naivety n;
4427 int offset;
4428 PyObject *temp;
Tim Petersa9bc1682003-01-11 03:39:11 +00004429
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004430 n = classify_utcoffset((PyObject *)self, (PyObject *)self,
4431 &offset);
4432 assert(n != OFFSET_UNKNOWN);
4433 if (n == OFFSET_ERROR)
4434 return -1;
Tim Petersa9bc1682003-01-11 03:39:11 +00004435
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004436 /* Reduce this to a hash of another object. */
4437 if (n == OFFSET_NAIVE) {
4438 self->hashcode = generic_hash(
4439 (unsigned char *)self->data, _PyDateTime_DATETIME_DATASIZE);
4440 return self->hashcode;
4441 }
4442 else {
4443 int days;
4444 int seconds;
Tim Petersa9bc1682003-01-11 03:39:11 +00004445
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004446 assert(n == OFFSET_AWARE);
4447 assert(HASTZINFO(self));
4448 days = ymd_to_ord(GET_YEAR(self),
4449 GET_MONTH(self),
4450 GET_DAY(self));
4451 seconds = DATE_GET_HOUR(self) * 3600 +
4452 (DATE_GET_MINUTE(self) - offset) * 60 +
4453 DATE_GET_SECOND(self);
4454 temp = new_delta(days,
4455 seconds,
4456 DATE_GET_MICROSECOND(self),
4457 1);
4458 }
4459 if (temp != NULL) {
4460 self->hashcode = PyObject_Hash(temp);
4461 Py_DECREF(temp);
4462 }
4463 }
4464 return self->hashcode;
Tim Petersa9bc1682003-01-11 03:39:11 +00004465}
Tim Peters2a799bf2002-12-16 20:18:38 +00004466
4467static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004468datetime_replace(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters12bf3392002-12-24 05:41:27 +00004469{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004470 PyObject *clone;
4471 PyObject *tuple;
4472 int y = GET_YEAR(self);
4473 int m = GET_MONTH(self);
4474 int d = GET_DAY(self);
4475 int hh = DATE_GET_HOUR(self);
4476 int mm = DATE_GET_MINUTE(self);
4477 int ss = DATE_GET_SECOND(self);
4478 int us = DATE_GET_MICROSECOND(self);
4479 PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
Tim Peters12bf3392002-12-24 05:41:27 +00004480
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004481 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiiiiO:replace",
4482 datetime_kws,
4483 &y, &m, &d, &hh, &mm, &ss, &us,
4484 &tzinfo))
4485 return NULL;
4486 tuple = Py_BuildValue("iiiiiiiO", y, m, d, hh, mm, ss, us, tzinfo);
4487 if (tuple == NULL)
4488 return NULL;
4489 clone = datetime_new(Py_TYPE(self), tuple, NULL);
4490 Py_DECREF(tuple);
4491 return clone;
Tim Peters12bf3392002-12-24 05:41:27 +00004492}
4493
4494static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004495datetime_astimezone(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters80475bb2002-12-25 07:40:55 +00004496{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004497 int y, m, d, hh, mm, ss, us;
4498 PyObject *result;
4499 int offset, none;
Tim Peters521fc152002-12-31 17:36:56 +00004500
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004501 PyObject *tzinfo;
4502 static char *keywords[] = {"tz", NULL};
Tim Peters80475bb2002-12-25 07:40:55 +00004503
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004504 if (! PyArg_ParseTupleAndKeywords(args, kw, "O!:astimezone", keywords,
4505 &PyDateTime_TZInfoType, &tzinfo))
4506 return NULL;
Tim Peters80475bb2002-12-25 07:40:55 +00004507
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004508 if (!HASTZINFO(self) || self->tzinfo == Py_None)
4509 goto NeedAware;
Tim Peters521fc152002-12-31 17:36:56 +00004510
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004511 /* Conversion to self's own time zone is a NOP. */
4512 if (self->tzinfo == tzinfo) {
4513 Py_INCREF(self);
4514 return (PyObject *)self;
4515 }
Tim Peters521fc152002-12-31 17:36:56 +00004516
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004517 /* Convert self to UTC. */
4518 offset = call_utcoffset(self->tzinfo, (PyObject *)self, &none);
4519 if (offset == -1 && PyErr_Occurred())
4520 return NULL;
4521 if (none)
4522 goto NeedAware;
Tim Petersf3615152003-01-01 21:51:37 +00004523
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004524 y = GET_YEAR(self);
4525 m = GET_MONTH(self);
4526 d = GET_DAY(self);
4527 hh = DATE_GET_HOUR(self);
4528 mm = DATE_GET_MINUTE(self);
4529 ss = DATE_GET_SECOND(self);
4530 us = DATE_GET_MICROSECOND(self);
Tim Peters52dcce22003-01-23 16:36:11 +00004531
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004532 mm -= offset;
4533 if ((mm < 0 || mm >= 60) &&
4534 normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
4535 return NULL;
Tim Peters52dcce22003-01-23 16:36:11 +00004536
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004537 /* Attach new tzinfo and let fromutc() do the rest. */
4538 result = new_datetime(y, m, d, hh, mm, ss, us, tzinfo);
4539 if (result != NULL) {
4540 PyObject *temp = result;
Tim Peters52dcce22003-01-23 16:36:11 +00004541
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004542 result = PyObject_CallMethod(tzinfo, "fromutc", "O", temp);
4543 Py_DECREF(temp);
4544 }
4545 return result;
Tim Peters521fc152002-12-31 17:36:56 +00004546
Tim Peters52dcce22003-01-23 16:36:11 +00004547NeedAware:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004548 PyErr_SetString(PyExc_ValueError, "astimezone() cannot be applied to "
4549 "a naive datetime");
4550 return NULL;
Tim Peters80475bb2002-12-25 07:40:55 +00004551}
4552
4553static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004554datetime_timetuple(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004555{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004556 int dstflag = -1;
Tim Peters2a799bf2002-12-16 20:18:38 +00004557
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004558 if (HASTZINFO(self) && self->tzinfo != Py_None) {
4559 int none;
Tim Peters2a799bf2002-12-16 20:18:38 +00004560
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004561 dstflag = call_dst(self->tzinfo, (PyObject *)self, &none);
4562 if (dstflag == -1 && PyErr_Occurred())
4563 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004564
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004565 if (none)
4566 dstflag = -1;
4567 else if (dstflag != 0)
4568 dstflag = 1;
Tim Peters2a799bf2002-12-16 20:18:38 +00004569
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004570 }
4571 return build_struct_time(GET_YEAR(self),
4572 GET_MONTH(self),
4573 GET_DAY(self),
4574 DATE_GET_HOUR(self),
4575 DATE_GET_MINUTE(self),
4576 DATE_GET_SECOND(self),
4577 dstflag);
Tim Peters2a799bf2002-12-16 20:18:38 +00004578}
4579
4580static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004581datetime_getdate(PyDateTime_DateTime *self)
4582{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004583 return new_date(GET_YEAR(self),
4584 GET_MONTH(self),
4585 GET_DAY(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00004586}
4587
4588static PyObject *
4589datetime_gettime(PyDateTime_DateTime *self)
4590{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004591 return new_time(DATE_GET_HOUR(self),
4592 DATE_GET_MINUTE(self),
4593 DATE_GET_SECOND(self),
4594 DATE_GET_MICROSECOND(self),
4595 Py_None);
Tim Petersa9bc1682003-01-11 03:39:11 +00004596}
4597
4598static PyObject *
4599datetime_gettimetz(PyDateTime_DateTime *self)
4600{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004601 return new_time(DATE_GET_HOUR(self),
4602 DATE_GET_MINUTE(self),
4603 DATE_GET_SECOND(self),
4604 DATE_GET_MICROSECOND(self),
4605 HASTZINFO(self) ? self->tzinfo : Py_None);
Tim Petersa9bc1682003-01-11 03:39:11 +00004606}
4607
4608static PyObject *
4609datetime_utctimetuple(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004610{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004611 int y = GET_YEAR(self);
4612 int m = GET_MONTH(self);
4613 int d = GET_DAY(self);
4614 int hh = DATE_GET_HOUR(self);
4615 int mm = DATE_GET_MINUTE(self);
4616 int ss = DATE_GET_SECOND(self);
4617 int us = 0; /* microseconds are ignored in a timetuple */
4618 int offset = 0;
Tim Peters2a799bf2002-12-16 20:18:38 +00004619
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004620 if (HASTZINFO(self) && self->tzinfo != Py_None) {
4621 int none;
Tim Peters2a799bf2002-12-16 20:18:38 +00004622
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004623 offset = call_utcoffset(self->tzinfo, (PyObject *)self, &none);
4624 if (offset == -1 && PyErr_Occurred())
4625 return NULL;
4626 }
4627 /* Even if offset is 0, don't call timetuple() -- tm_isdst should be
4628 * 0 in a UTC timetuple regardless of what dst() says.
4629 */
4630 if (offset) {
4631 /* Subtract offset minutes & normalize. */
4632 int stat;
Tim Peters2a799bf2002-12-16 20:18:38 +00004633
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004634 mm -= offset;
4635 stat = normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us);
4636 if (stat < 0) {
4637 /* At the edges, it's possible we overflowed
4638 * beyond MINYEAR or MAXYEAR.
4639 */
4640 if (PyErr_ExceptionMatches(PyExc_OverflowError))
4641 PyErr_Clear();
4642 else
4643 return NULL;
4644 }
4645 }
4646 return build_struct_time(y, m, d, hh, mm, ss, 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00004647}
4648
Tim Peters371935f2003-02-01 01:52:50 +00004649/* Pickle support, a simple use of __reduce__. */
Tim Peters33e0f382003-01-10 02:05:14 +00004650
Tim Petersa9bc1682003-01-11 03:39:11 +00004651/* Let basestate be the non-tzinfo data string.
Tim Peters2a799bf2002-12-16 20:18:38 +00004652 * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
4653 * So it's a tuple in any (non-error) case.
Tim Petersb57f8f02003-02-01 02:54:15 +00004654 * __getstate__ isn't exposed.
Tim Peters2a799bf2002-12-16 20:18:38 +00004655 */
4656static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004657datetime_getstate(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004658{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004659 PyObject *basestate;
4660 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004661
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004662 basestate = PyBytes_FromStringAndSize((char *)self->data,
4663 _PyDateTime_DATETIME_DATASIZE);
4664 if (basestate != NULL) {
4665 if (! HASTZINFO(self) || self->tzinfo == Py_None)
4666 result = PyTuple_Pack(1, basestate);
4667 else
4668 result = PyTuple_Pack(2, basestate, self->tzinfo);
4669 Py_DECREF(basestate);
4670 }
4671 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00004672}
4673
4674static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00004675datetime_reduce(PyDateTime_DateTime *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00004676{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004677 return Py_BuildValue("(ON)", Py_TYPE(self), datetime_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00004678}
4679
Tim Petersa9bc1682003-01-11 03:39:11 +00004680static PyMethodDef datetime_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00004681
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004682 /* Class methods: */
Tim Peters2a799bf2002-12-16 20:18:38 +00004683
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004684 {"now", (PyCFunction)datetime_now,
4685 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
4686 PyDoc_STR("[tz] -> new datetime with tz's local day and time.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004687
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004688 {"utcnow", (PyCFunction)datetime_utcnow,
4689 METH_NOARGS | METH_CLASS,
4690 PyDoc_STR("Return a new datetime representing UTC day and time.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00004691
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004692 {"fromtimestamp", (PyCFunction)datetime_fromtimestamp,
4693 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
4694 PyDoc_STR("timestamp[, tz] -> tz's local time from POSIX timestamp.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004695
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004696 {"utcfromtimestamp", (PyCFunction)datetime_utcfromtimestamp,
4697 METH_VARARGS | METH_CLASS,
4698 PyDoc_STR("timestamp -> UTC datetime from a POSIX timestamp "
4699 "(like time.time()).")},
Tim Petersa9bc1682003-01-11 03:39:11 +00004700
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004701 {"strptime", (PyCFunction)datetime_strptime,
4702 METH_VARARGS | METH_CLASS,
4703 PyDoc_STR("string, format -> new datetime parsed from a string "
4704 "(like time.strptime()).")},
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004705
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004706 {"combine", (PyCFunction)datetime_combine,
4707 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
4708 PyDoc_STR("date, time -> datetime with same date and time fields")},
Tim Petersa9bc1682003-01-11 03:39:11 +00004709
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004710 /* Instance methods: */
Guido van Rossum177e41a2003-01-30 22:06:23 +00004711
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004712 {"date", (PyCFunction)datetime_getdate, METH_NOARGS,
4713 PyDoc_STR("Return date object with same year, month and day.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00004714
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004715 {"time", (PyCFunction)datetime_gettime, METH_NOARGS,
4716 PyDoc_STR("Return time object with same time but with tzinfo=None.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00004717
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004718 {"timetz", (PyCFunction)datetime_gettimetz, METH_NOARGS,
4719 PyDoc_STR("Return time object with same time and tzinfo.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00004720
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004721 {"ctime", (PyCFunction)datetime_ctime, METH_NOARGS,
4722 PyDoc_STR("Return ctime() style string.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00004723
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004724 {"timetuple", (PyCFunction)datetime_timetuple, METH_NOARGS,
4725 PyDoc_STR("Return time tuple, compatible with time.localtime().")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004726
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004727 {"utctimetuple", (PyCFunction)datetime_utctimetuple, METH_NOARGS,
4728 PyDoc_STR("Return UTC time tuple, compatible with time.localtime().")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004729
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004730 {"isoformat", (PyCFunction)datetime_isoformat, METH_VARARGS | METH_KEYWORDS,
4731 PyDoc_STR("[sep] -> string in ISO 8601 format, "
4732 "YYYY-MM-DDTHH:MM:SS[.mmmmmm][+HH:MM].\n\n"
4733 "sep is used to separate the year from the time, and "
4734 "defaults to 'T'.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004735
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004736 {"utcoffset", (PyCFunction)datetime_utcoffset, METH_NOARGS,
4737 PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004738
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004739 {"tzname", (PyCFunction)datetime_tzname, METH_NOARGS,
4740 PyDoc_STR("Return self.tzinfo.tzname(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004741
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004742 {"dst", (PyCFunction)datetime_dst, METH_NOARGS,
4743 PyDoc_STR("Return self.tzinfo.dst(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004744
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004745 {"replace", (PyCFunction)datetime_replace, METH_VARARGS | METH_KEYWORDS,
4746 PyDoc_STR("Return datetime with new specified fields.")},
Tim Peters12bf3392002-12-24 05:41:27 +00004747
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004748 {"astimezone", (PyCFunction)datetime_astimezone, METH_VARARGS | METH_KEYWORDS,
4749 PyDoc_STR("tz -> convert to local time in new timezone tz\n")},
Tim Peters80475bb2002-12-25 07:40:55 +00004750
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004751 {"__reduce__", (PyCFunction)datetime_reduce, METH_NOARGS,
4752 PyDoc_STR("__reduce__() -> (cls, state)")},
Guido van Rossum177e41a2003-01-30 22:06:23 +00004753
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004754 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00004755};
4756
Tim Petersa9bc1682003-01-11 03:39:11 +00004757static char datetime_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00004758PyDoc_STR("datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]])\n\
4759\n\
4760The year, month and day arguments are required. tzinfo may be None, or an\n\
4761instance of a tzinfo subclass. The remaining arguments may be ints or longs.\n");
Tim Peters2a799bf2002-12-16 20:18:38 +00004762
Tim Petersa9bc1682003-01-11 03:39:11 +00004763static PyNumberMethods datetime_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004764 datetime_add, /* nb_add */
4765 datetime_subtract, /* nb_subtract */
4766 0, /* nb_multiply */
4767 0, /* nb_remainder */
4768 0, /* nb_divmod */
4769 0, /* nb_power */
4770 0, /* nb_negative */
4771 0, /* nb_positive */
4772 0, /* nb_absolute */
4773 0, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00004774};
4775
Neal Norwitz227b5332006-03-22 09:28:35 +00004776static PyTypeObject PyDateTime_DateTimeType = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004777 PyVarObject_HEAD_INIT(NULL, 0)
4778 "datetime.datetime", /* tp_name */
4779 sizeof(PyDateTime_DateTime), /* tp_basicsize */
4780 0, /* tp_itemsize */
4781 (destructor)datetime_dealloc, /* tp_dealloc */
4782 0, /* tp_print */
4783 0, /* tp_getattr */
4784 0, /* tp_setattr */
4785 0, /* tp_reserved */
4786 (reprfunc)datetime_repr, /* tp_repr */
4787 &datetime_as_number, /* tp_as_number */
4788 0, /* tp_as_sequence */
4789 0, /* tp_as_mapping */
4790 (hashfunc)datetime_hash, /* tp_hash */
4791 0, /* tp_call */
4792 (reprfunc)datetime_str, /* tp_str */
4793 PyObject_GenericGetAttr, /* tp_getattro */
4794 0, /* tp_setattro */
4795 0, /* tp_as_buffer */
4796 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
4797 datetime_doc, /* tp_doc */
4798 0, /* tp_traverse */
4799 0, /* tp_clear */
4800 datetime_richcompare, /* tp_richcompare */
4801 0, /* tp_weaklistoffset */
4802 0, /* tp_iter */
4803 0, /* tp_iternext */
4804 datetime_methods, /* tp_methods */
4805 0, /* tp_members */
4806 datetime_getset, /* tp_getset */
4807 &PyDateTime_DateType, /* tp_base */
4808 0, /* tp_dict */
4809 0, /* tp_descr_get */
4810 0, /* tp_descr_set */
4811 0, /* tp_dictoffset */
4812 0, /* tp_init */
4813 datetime_alloc, /* tp_alloc */
4814 datetime_new, /* tp_new */
4815 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00004816};
4817
4818/* ---------------------------------------------------------------------------
4819 * Module methods and initialization.
4820 */
4821
4822static PyMethodDef module_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004823 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00004824};
4825
Tim Peters9ddf40b2004-06-20 22:41:32 +00004826/* C API. Clients get at this via PyDateTime_IMPORT, defined in
4827 * datetime.h.
4828 */
4829static PyDateTime_CAPI CAPI = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004830 &PyDateTime_DateType,
4831 &PyDateTime_DateTimeType,
4832 &PyDateTime_TimeType,
4833 &PyDateTime_DeltaType,
4834 &PyDateTime_TZInfoType,
4835 new_date_ex,
4836 new_datetime_ex,
4837 new_time_ex,
4838 new_delta_ex,
4839 datetime_fromtimestamp,
4840 date_fromtimestamp
Tim Peters9ddf40b2004-06-20 22:41:32 +00004841};
4842
4843
Martin v. Löwis1a214512008-06-11 05:26:20 +00004844
4845static struct PyModuleDef datetimemodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004846 PyModuleDef_HEAD_INIT,
4847 "datetime",
4848 "Fast implementation of the datetime type.",
4849 -1,
4850 module_methods,
4851 NULL,
4852 NULL,
4853 NULL,
4854 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00004855};
4856
Tim Peters2a799bf2002-12-16 20:18:38 +00004857PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00004858PyInit_datetime(void)
Tim Peters2a799bf2002-12-16 20:18:38 +00004859{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004860 PyObject *m; /* a module object */
4861 PyObject *d; /* its dict */
4862 PyObject *x;
Tim Peters2a799bf2002-12-16 20:18:38 +00004863
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004864 m = PyModule_Create(&datetimemodule);
4865 if (m == NULL)
4866 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004867
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004868 if (PyType_Ready(&PyDateTime_DateType) < 0)
4869 return NULL;
4870 if (PyType_Ready(&PyDateTime_DateTimeType) < 0)
4871 return NULL;
4872 if (PyType_Ready(&PyDateTime_DeltaType) < 0)
4873 return NULL;
4874 if (PyType_Ready(&PyDateTime_TimeType) < 0)
4875 return NULL;
4876 if (PyType_Ready(&PyDateTime_TZInfoType) < 0)
4877 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004878
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004879 /* timedelta values */
4880 d = PyDateTime_DeltaType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00004881
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004882 x = new_delta(0, 0, 1, 0);
4883 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4884 return NULL;
4885 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00004886
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004887 x = new_delta(-MAX_DELTA_DAYS, 0, 0, 0);
4888 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4889 return NULL;
4890 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00004891
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004892 x = new_delta(MAX_DELTA_DAYS, 24*3600-1, 1000000-1, 0);
4893 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4894 return NULL;
4895 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00004896
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004897 /* date values */
4898 d = PyDateTime_DateType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00004899
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004900 x = new_date(1, 1, 1);
4901 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4902 return NULL;
4903 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00004904
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004905 x = new_date(MAXYEAR, 12, 31);
4906 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4907 return NULL;
4908 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00004909
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004910 x = new_delta(1, 0, 0, 0);
4911 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4912 return NULL;
4913 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00004914
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004915 /* time values */
4916 d = PyDateTime_TimeType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00004917
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004918 x = new_time(0, 0, 0, 0, Py_None);
4919 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4920 return NULL;
4921 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00004922
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004923 x = new_time(23, 59, 59, 999999, Py_None);
4924 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4925 return NULL;
4926 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00004927
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004928 x = new_delta(0, 0, 1, 0);
4929 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4930 return NULL;
4931 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00004932
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004933 /* datetime values */
4934 d = PyDateTime_DateTimeType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00004935
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004936 x = new_datetime(1, 1, 1, 0, 0, 0, 0, Py_None);
4937 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4938 return NULL;
4939 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00004940
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004941 x = new_datetime(MAXYEAR, 12, 31, 23, 59, 59, 999999, Py_None);
4942 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4943 return NULL;
4944 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00004945
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004946 x = new_delta(0, 0, 1, 0);
4947 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4948 return NULL;
4949 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00004950
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004951 /* module initialization */
4952 PyModule_AddIntConstant(m, "MINYEAR", MINYEAR);
4953 PyModule_AddIntConstant(m, "MAXYEAR", MAXYEAR);
Tim Peters2a799bf2002-12-16 20:18:38 +00004954
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004955 Py_INCREF(&PyDateTime_DateType);
4956 PyModule_AddObject(m, "date", (PyObject *) &PyDateTime_DateType);
Tim Peters2a799bf2002-12-16 20:18:38 +00004957
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004958 Py_INCREF(&PyDateTime_DateTimeType);
4959 PyModule_AddObject(m, "datetime",
4960 (PyObject *)&PyDateTime_DateTimeType);
Tim Petersa9bc1682003-01-11 03:39:11 +00004961
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004962 Py_INCREF(&PyDateTime_TimeType);
4963 PyModule_AddObject(m, "time", (PyObject *) &PyDateTime_TimeType);
Tim Petersa9bc1682003-01-11 03:39:11 +00004964
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004965 Py_INCREF(&PyDateTime_DeltaType);
4966 PyModule_AddObject(m, "timedelta", (PyObject *) &PyDateTime_DeltaType);
Tim Peters2a799bf2002-12-16 20:18:38 +00004967
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004968 Py_INCREF(&PyDateTime_TZInfoType);
4969 PyModule_AddObject(m, "tzinfo", (PyObject *) &PyDateTime_TZInfoType);
Tim Peters2a799bf2002-12-16 20:18:38 +00004970
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004971 x = PyCapsule_New(&CAPI, PyDateTime_CAPSULE_NAME, NULL);
4972 if (x == NULL)
4973 return NULL;
4974 PyModule_AddObject(m, "datetime_CAPI", x);
Tim Peters9ddf40b2004-06-20 22:41:32 +00004975
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004976 /* A 4-year cycle has an extra leap day over what we'd get from
4977 * pasting together 4 single years.
4978 */
4979 assert(DI4Y == 4 * 365 + 1);
4980 assert(DI4Y == days_before_year(4+1));
Tim Peters2a799bf2002-12-16 20:18:38 +00004981
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004982 /* Similarly, a 400-year cycle has an extra leap day over what we'd
4983 * get from pasting together 4 100-year cycles.
4984 */
4985 assert(DI400Y == 4 * DI100Y + 1);
4986 assert(DI400Y == days_before_year(400+1));
Tim Peters2a799bf2002-12-16 20:18:38 +00004987
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004988 /* OTOH, a 100-year cycle has one fewer leap day than we'd get from
4989 * pasting together 25 4-year cycles.
4990 */
4991 assert(DI100Y == 25 * DI4Y - 1);
4992 assert(DI100Y == days_before_year(100+1));
Tim Peters2a799bf2002-12-16 20:18:38 +00004993
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004994 us_per_us = PyLong_FromLong(1);
4995 us_per_ms = PyLong_FromLong(1000);
4996 us_per_second = PyLong_FromLong(1000000);
4997 us_per_minute = PyLong_FromLong(60000000);
4998 seconds_per_day = PyLong_FromLong(24 * 3600);
4999 if (us_per_us == NULL || us_per_ms == NULL || us_per_second == NULL ||
5000 us_per_minute == NULL || seconds_per_day == NULL)
5001 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00005002
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005003 /* The rest are too big for 32-bit ints, but even
5004 * us_per_week fits in 40 bits, so doubles should be exact.
5005 */
5006 us_per_hour = PyLong_FromDouble(3600000000.0);
5007 us_per_day = PyLong_FromDouble(86400000000.0);
5008 us_per_week = PyLong_FromDouble(604800000000.0);
5009 if (us_per_hour == NULL || us_per_day == NULL || us_per_week == NULL)
5010 return NULL;
5011 return m;
Tim Peters2a799bf2002-12-16 20:18:38 +00005012}
Tim Petersf3615152003-01-01 21:51:37 +00005013
5014/* ---------------------------------------------------------------------------
Tim Petersa9bc1682003-01-11 03:39:11 +00005015Some time zone algebra. For a datetime x, let
Tim Petersf3615152003-01-01 21:51:37 +00005016 x.n = x stripped of its timezone -- its naive time.
5017 x.o = x.utcoffset(), and assuming that doesn't raise an exception or
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005018 return None
Tim Petersf3615152003-01-01 21:51:37 +00005019 x.d = x.dst(), and assuming that doesn't raise an exception or
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005020 return None
Tim Petersf3615152003-01-01 21:51:37 +00005021 x.s = x's standard offset, x.o - x.d
5022
5023Now some derived rules, where k is a duration (timedelta).
5024
50251. x.o = x.s + x.d
5026 This follows from the definition of x.s.
5027
Tim Petersc5dc4da2003-01-02 17:55:03 +000050282. If x and y have the same tzinfo member, x.s = y.s.
Tim Petersf3615152003-01-01 21:51:37 +00005029 This is actually a requirement, an assumption we need to make about
5030 sane tzinfo classes.
5031
50323. The naive UTC time corresponding to x is x.n - x.o.
5033 This is again a requirement for a sane tzinfo class.
5034
50354. (x+k).s = x.s
Tim Peters8bb5ad22003-01-24 02:44:45 +00005036 This follows from #2, and that datimetimetz+timedelta preserves tzinfo.
Tim Petersf3615152003-01-01 21:51:37 +00005037
Tim Petersc5dc4da2003-01-02 17:55:03 +000050385. (x+k).n = x.n + k
Tim Petersf3615152003-01-01 21:51:37 +00005039 Again follows from how arithmetic is defined.
5040
Tim Peters8bb5ad22003-01-24 02:44:45 +00005041Now we can explain tz.fromutc(x). Let's assume it's an interesting case
Tim Petersf3615152003-01-01 21:51:37 +00005042(meaning that the various tzinfo methods exist, and don't blow up or return
5043None when called).
5044
Tim Petersa9bc1682003-01-11 03:39:11 +00005045The function wants to return a datetime y with timezone tz, equivalent to x.
Tim Peters8bb5ad22003-01-24 02:44:45 +00005046x is already in UTC.
Tim Petersf3615152003-01-01 21:51:37 +00005047
5048By #3, we want
5049
Tim Peters8bb5ad22003-01-24 02:44:45 +00005050 y.n - y.o = x.n [1]
Tim Petersf3615152003-01-01 21:51:37 +00005051
5052The algorithm starts by attaching tz to x.n, and calling that y. So
5053x.n = y.n at the start. Then it wants to add a duration k to y, so that [1]
5054becomes true; in effect, we want to solve [2] for k:
5055
Tim Peters8bb5ad22003-01-24 02:44:45 +00005056 (y+k).n - (y+k).o = x.n [2]
Tim Petersf3615152003-01-01 21:51:37 +00005057
5058By #1, this is the same as
5059
Tim Peters8bb5ad22003-01-24 02:44:45 +00005060 (y+k).n - ((y+k).s + (y+k).d) = x.n [3]
Tim Petersf3615152003-01-01 21:51:37 +00005061
5062By #5, (y+k).n = y.n + k, which equals x.n + k because x.n=y.n at the start.
5063Substituting that into [3],
5064
Tim Peters8bb5ad22003-01-24 02:44:45 +00005065 x.n + k - (y+k).s - (y+k).d = x.n; the x.n terms cancel, leaving
5066 k - (y+k).s - (y+k).d = 0; rearranging,
5067 k = (y+k).s - (y+k).d; by #4, (y+k).s == y.s, so
5068 k = y.s - (y+k).d
Tim Petersf3615152003-01-01 21:51:37 +00005069
Tim Peters8bb5ad22003-01-24 02:44:45 +00005070On the RHS, (y+k).d can't be computed directly, but y.s can be, and we
5071approximate k by ignoring the (y+k).d term at first. Note that k can't be
5072very large, since all offset-returning methods return a duration of magnitude
5073less than 24 hours. For that reason, if y is firmly in std time, (y+k).d must
5074be 0, so ignoring it has no consequence then.
Tim Petersf3615152003-01-01 21:51:37 +00005075
5076In any case, the new value is
5077
Tim Peters8bb5ad22003-01-24 02:44:45 +00005078 z = y + y.s [4]
Tim Petersf3615152003-01-01 21:51:37 +00005079
Tim Peters8bb5ad22003-01-24 02:44:45 +00005080It's helpful to step back at look at [4] from a higher level: it's simply
5081mapping from UTC to tz's standard time.
Tim Petersc5dc4da2003-01-02 17:55:03 +00005082
5083At this point, if
5084
Tim Peters8bb5ad22003-01-24 02:44:45 +00005085 z.n - z.o = x.n [5]
Tim Petersc5dc4da2003-01-02 17:55:03 +00005086
5087we have an equivalent time, and are almost done. The insecurity here is
Tim Petersf3615152003-01-01 21:51:37 +00005088at the start of daylight time. Picture US Eastern for concreteness. The wall
5089time 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 +00005090sense then. The docs ask that an Eastern tzinfo class consider such a time to
5091be EDT (because it's "after 2"), which is a redundant spelling of 1:MM EST
5092on the day DST starts. We want to return the 1:MM EST spelling because that's
Tim Petersf3615152003-01-01 21:51:37 +00005093the only spelling that makes sense on the local wall clock.
5094
Tim Petersc5dc4da2003-01-02 17:55:03 +00005095In fact, if [5] holds at this point, we do have the standard-time spelling,
5096but that takes a bit of proof. We first prove a stronger result. What's the
5097difference between the LHS and RHS of [5]? Let
Tim Petersf3615152003-01-01 21:51:37 +00005098
Tim Peters8bb5ad22003-01-24 02:44:45 +00005099 diff = x.n - (z.n - z.o) [6]
Tim Petersf3615152003-01-01 21:51:37 +00005100
Tim Petersc5dc4da2003-01-02 17:55:03 +00005101Now
5102 z.n = by [4]
Tim Peters8bb5ad22003-01-24 02:44:45 +00005103 (y + y.s).n = by #5
5104 y.n + y.s = since y.n = x.n
5105 x.n + y.s = since z and y are have the same tzinfo member,
5106 y.s = z.s by #2
5107 x.n + z.s
Tim Petersf3615152003-01-01 21:51:37 +00005108
Tim Petersc5dc4da2003-01-02 17:55:03 +00005109Plugging that back into [6] gives
Tim Petersf3615152003-01-01 21:51:37 +00005110
Tim Petersc5dc4da2003-01-02 17:55:03 +00005111 diff =
Tim Peters8bb5ad22003-01-24 02:44:45 +00005112 x.n - ((x.n + z.s) - z.o) = expanding
5113 x.n - x.n - z.s + z.o = cancelling
5114 - z.s + z.o = by #2
Tim Petersc5dc4da2003-01-02 17:55:03 +00005115 z.d
Tim Petersf3615152003-01-01 21:51:37 +00005116
Tim Petersc5dc4da2003-01-02 17:55:03 +00005117So diff = z.d.
Tim Petersf3615152003-01-01 21:51:37 +00005118
Tim Petersc5dc4da2003-01-02 17:55:03 +00005119If [5] is true now, diff = 0, so z.d = 0 too, and we have the standard-time
Tim Peters8bb5ad22003-01-24 02:44:45 +00005120spelling we wanted in the endcase described above. We're done. Contrarily,
5121if z.d = 0, then we have a UTC equivalent, and are also done.
Tim Petersf3615152003-01-01 21:51:37 +00005122
Tim Petersc5dc4da2003-01-02 17:55:03 +00005123If [5] is not true now, diff = z.d != 0, and z.d is the offset we need to
5124add to z (in effect, z is in tz's standard time, and we need to shift the
Tim Peters8bb5ad22003-01-24 02:44:45 +00005125local clock into tz's daylight time).
Tim Petersf3615152003-01-01 21:51:37 +00005126
Tim Petersc5dc4da2003-01-02 17:55:03 +00005127Let
Tim Petersf3615152003-01-01 21:51:37 +00005128
Tim Peters4fede1a2003-01-04 00:26:59 +00005129 z' = z + z.d = z + diff [7]
Tim Petersc3bb26a2003-01-02 03:14:59 +00005130
Tim Peters4fede1a2003-01-04 00:26:59 +00005131and we can again ask whether
Tim Petersc3bb26a2003-01-02 03:14:59 +00005132
Tim Peters8bb5ad22003-01-24 02:44:45 +00005133 z'.n - z'.o = x.n [8]
Tim Petersc3bb26a2003-01-02 03:14:59 +00005134
Tim Peters8bb5ad22003-01-24 02:44:45 +00005135If so, we're done. If not, the tzinfo class is insane, according to the
5136assumptions we've made. This also requires a bit of proof. As before, let's
5137compute the difference between the LHS and RHS of [8] (and skipping some of
5138the justifications for the kinds of substitutions we've done several times
5139already):
Tim Peters4fede1a2003-01-04 00:26:59 +00005140
Tim Peters8bb5ad22003-01-24 02:44:45 +00005141 diff' = x.n - (z'.n - z'.o) = replacing z'.n via [7]
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005142 x.n - (z.n + diff - z'.o) = replacing diff via [6]
5143 x.n - (z.n + x.n - (z.n - z.o) - z'.o) =
5144 x.n - z.n - x.n + z.n - z.o + z'.o = cancel x.n
5145 - z.n + z.n - z.o + z'.o = cancel z.n
5146 - z.o + z'.o = #1 twice
5147 -z.s - z.d + z'.s + z'.d = z and z' have same tzinfo
5148 z'.d - z.d
Tim Peters4fede1a2003-01-04 00:26:59 +00005149
5150So 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 +00005151we've found the UTC-equivalent so are done. In fact, we stop with [7] and
5152return z', not bothering to compute z'.d.
Tim Peters4fede1a2003-01-04 00:26:59 +00005153
Tim Peters8bb5ad22003-01-24 02:44:45 +00005154How could z.d and z'd differ? z' = z + z.d [7], so merely moving z' by
5155a dst() offset, and starting *from* a time already in DST (we know z.d != 0),
5156would have to change the result dst() returns: we start in DST, and moving
5157a little further into it takes us out of DST.
Tim Peters4fede1a2003-01-04 00:26:59 +00005158
Tim Peters8bb5ad22003-01-24 02:44:45 +00005159There isn't a sane case where this can happen. The closest it gets is at
5160the end of DST, where there's an hour in UTC with no spelling in a hybrid
5161tzinfo class. In US Eastern, that's 5:MM UTC = 0:MM EST = 1:MM EDT. During
5162that hour, on an Eastern clock 1:MM is taken as being in standard time (6:MM
5163UTC) because the docs insist on that, but 0:MM is taken as being in daylight
5164time (4:MM UTC). There is no local time mapping to 5:MM UTC. The local
5165clock jumps from 1:59 back to 1:00 again, and repeats the 1:MM hour in
5166standard time. Since that's what the local clock *does*, we want to map both
5167UTC hours 5:MM and 6:MM to 1:MM Eastern. The result is ambiguous
Tim Peters4fede1a2003-01-04 00:26:59 +00005168in local time, but so it goes -- it's the way the local clock works.
5169
Tim Peters8bb5ad22003-01-24 02:44:45 +00005170When x = 5:MM UTC is the input to this algorithm, x.o=0, y.o=-5 and y.d=0,
5171so z=0:MM. z.d=60 (minutes) then, so [5] doesn't hold and we keep going.
5172z' = 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 +00005173(correctly) concludes that z' is not UTC-equivalent to x.
5174
5175Because we know z.d said z was in daylight time (else [5] would have held and
5176we would have stopped then), and we know z.d != z'.d (else [8] would have held
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +00005177and we would have stopped then), and there are only 2 possible values dst() can
Tim Peters4fede1a2003-01-04 00:26:59 +00005178return in Eastern, it follows that z'.d must be 0 (which it is in the example,
5179but the reasoning doesn't depend on the example -- it depends on there being
5180two possible dst() outcomes, one zero and the other non-zero). Therefore
Tim Peters8bb5ad22003-01-24 02:44:45 +00005181z' must be in standard time, and is the spelling we want in this case.
5182
5183Note again that z' is not UTC-equivalent as far as the hybrid tzinfo class is
5184concerned (because it takes z' as being in standard time rather than the
5185daylight time we intend here), but returning it gives the real-life "local
5186clock repeats an hour" behavior when mapping the "unspellable" UTC hour into
5187tz.
5188
5189When the input is 6:MM, z=1:MM and z.d=0, and we stop at once, again with
5190the 1:MM standard time spelling we want.
5191
5192So how can this break? One of the assumptions must be violated. Two
5193possibilities:
5194
51951) [2] effectively says that y.s is invariant across all y belong to a given
5196 time zone. This isn't true if, for political reasons or continental drift,
5197 a region decides to change its base offset from UTC.
5198
51992) There may be versions of "double daylight" time where the tail end of
5200 the analysis gives up a step too early. I haven't thought about that
5201 enough to say.
5202
5203In any case, it's clear that the default fromutc() is strong enough to handle
5204"almost all" time zones: so long as the standard offset is invariant, it
5205doesn't matter if daylight time transition points change from year to year, or
5206if daylight time is skipped in some years; it doesn't matter how large or
5207small dst() may get within its bounds; and it doesn't even matter if some
5208perverse time zone returns a negative dst()). So a breaking case must be
5209pretty bizarre, and a tzinfo subclass can override fromutc() if it is.
Tim Petersf3615152003-01-01 21:51:37 +00005210--------------------------------------------------------------------------- */