blob: 3b0b36277c71fc8de2931081aec91ffc03030a7f [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"
Tim Peters2a799bf2002-12-16 20:18:38 +00006#include "structmember.h"
7
8#include <time.h>
9
Alexander Belopolsky6fc4ade2010-08-05 17:34:27 +000010#include "_time.h"
Tim Peters9ddf40b2004-06-20 22:41:32 +000011
12/* Differentiate between building the core module and building extension
13 * modules.
14 */
Guido van Rossum360e4b82007-05-14 22:51:27 +000015#ifndef Py_BUILD_CORE
Tim Peters9ddf40b2004-06-20 22:41:32 +000016#define Py_BUILD_CORE
Guido van Rossum360e4b82007-05-14 22:51:27 +000017#endif
Tim Peters2a799bf2002-12-16 20:18:38 +000018#include "datetime.h"
Tim Peters9ddf40b2004-06-20 22:41:32 +000019#undef Py_BUILD_CORE
Tim Peters2a799bf2002-12-16 20:18:38 +000020
21/* We require that C int be at least 32 bits, and use int virtually
22 * everywhere. In just a few cases we use a temp long, where a Python
23 * API returns a C long. In such cases, we have to ensure that the
24 * final result fits in a C int (this can be an issue on 64-bit boxes).
25 */
26#if SIZEOF_INT < 4
Alexander Belopolskycf86e362010-07-23 19:25:47 +000027# error "_datetime.c requires that C int have at least 32 bits"
Tim Peters2a799bf2002-12-16 20:18:38 +000028#endif
29
30#define MINYEAR 1
31#define MAXYEAR 9999
Alexander Belopolskyf03a6162010-05-27 21:42:58 +000032#define MAXORDINAL 3652059 /* date(9999,12,31).toordinal() */
Tim Peters2a799bf2002-12-16 20:18:38 +000033
34/* Nine decimal digits is easy to communicate, and leaves enough room
35 * so that two delta days can be added w/o fear of overflowing a signed
36 * 32-bit int, and with plenty of room left over to absorb any possible
37 * carries from adding seconds.
38 */
39#define MAX_DELTA_DAYS 999999999
40
41/* Rename the long macros in datetime.h to more reasonable short names. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000042#define GET_YEAR PyDateTime_GET_YEAR
43#define GET_MONTH PyDateTime_GET_MONTH
44#define GET_DAY PyDateTime_GET_DAY
45#define DATE_GET_HOUR PyDateTime_DATE_GET_HOUR
46#define DATE_GET_MINUTE PyDateTime_DATE_GET_MINUTE
47#define DATE_GET_SECOND PyDateTime_DATE_GET_SECOND
48#define DATE_GET_MICROSECOND PyDateTime_DATE_GET_MICROSECOND
Tim Peters2a799bf2002-12-16 20:18:38 +000049
50/* Date accessors for date and datetime. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000051#define SET_YEAR(o, v) (((o)->data[0] = ((v) & 0xff00) >> 8), \
52 ((o)->data[1] = ((v) & 0x00ff)))
53#define SET_MONTH(o, v) (PyDateTime_GET_MONTH(o) = (v))
54#define SET_DAY(o, v) (PyDateTime_GET_DAY(o) = (v))
Tim Peters2a799bf2002-12-16 20:18:38 +000055
56/* Date/Time accessors for datetime. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000057#define DATE_SET_HOUR(o, v) (PyDateTime_DATE_GET_HOUR(o) = (v))
58#define DATE_SET_MINUTE(o, v) (PyDateTime_DATE_GET_MINUTE(o) = (v))
59#define DATE_SET_SECOND(o, v) (PyDateTime_DATE_GET_SECOND(o) = (v))
60#define DATE_SET_MICROSECOND(o, v) \
61 (((o)->data[7] = ((v) & 0xff0000) >> 16), \
62 ((o)->data[8] = ((v) & 0x00ff00) >> 8), \
63 ((o)->data[9] = ((v) & 0x0000ff)))
Tim Peters2a799bf2002-12-16 20:18:38 +000064
65/* Time accessors for time. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000066#define TIME_GET_HOUR PyDateTime_TIME_GET_HOUR
67#define TIME_GET_MINUTE PyDateTime_TIME_GET_MINUTE
68#define TIME_GET_SECOND PyDateTime_TIME_GET_SECOND
69#define TIME_GET_MICROSECOND PyDateTime_TIME_GET_MICROSECOND
70#define TIME_SET_HOUR(o, v) (PyDateTime_TIME_GET_HOUR(o) = (v))
71#define TIME_SET_MINUTE(o, v) (PyDateTime_TIME_GET_MINUTE(o) = (v))
72#define TIME_SET_SECOND(o, v) (PyDateTime_TIME_GET_SECOND(o) = (v))
73#define TIME_SET_MICROSECOND(o, v) \
74 (((o)->data[3] = ((v) & 0xff0000) >> 16), \
75 ((o)->data[4] = ((v) & 0x00ff00) >> 8), \
76 ((o)->data[5] = ((v) & 0x0000ff)))
Tim Peters2a799bf2002-12-16 20:18:38 +000077
78/* Delta accessors for timedelta. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000079#define GET_TD_DAYS(o) (((PyDateTime_Delta *)(o))->days)
80#define GET_TD_SECONDS(o) (((PyDateTime_Delta *)(o))->seconds)
81#define GET_TD_MICROSECONDS(o) (((PyDateTime_Delta *)(o))->microseconds)
Tim Peters2a799bf2002-12-16 20:18:38 +000082
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000083#define SET_TD_DAYS(o, v) ((o)->days = (v))
84#define SET_TD_SECONDS(o, v) ((o)->seconds = (v))
Tim Peters2a799bf2002-12-16 20:18:38 +000085#define SET_TD_MICROSECONDS(o, v) ((o)->microseconds = (v))
86
Tim Petersa032d2e2003-01-11 00:15:54 +000087/* p is a pointer to a time or a datetime object; HASTZINFO(p) returns
88 * p->hastzinfo.
89 */
Alexander Belopolsky73ca4402010-07-07 23:56:38 +000090#define HASTZINFO(p) (((_PyDateTime_BaseTZInfo *)(p))->hastzinfo)
91#define GET_TIME_TZINFO(p) (HASTZINFO(p) ? \
92 ((PyDateTime_Time *)(p))->tzinfo : Py_None)
93#define GET_DT_TZINFO(p) (HASTZINFO(p) ? \
94 ((PyDateTime_DateTime *)(p))->tzinfo : Py_None)
Tim Peters3f606292004-03-21 23:38:41 +000095/* M is a char or int claiming to be a valid month. The macro is equivalent
96 * to the two-sided Python test
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000097 * 1 <= M <= 12
Tim Peters3f606292004-03-21 23:38:41 +000098 */
99#define MONTH_IS_SANE(M) ((unsigned int)(M) - 1 < 12)
100
Tim Peters2a799bf2002-12-16 20:18:38 +0000101/* Forward declarations. */
102static PyTypeObject PyDateTime_DateType;
103static PyTypeObject PyDateTime_DateTimeType;
Tim Peters2a799bf2002-12-16 20:18:38 +0000104static PyTypeObject PyDateTime_DeltaType;
105static PyTypeObject PyDateTime_TimeType;
106static PyTypeObject PyDateTime_TZInfoType;
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000107static PyTypeObject PyDateTime_TimeZoneType;
Tim Peters2a799bf2002-12-16 20:18:38 +0000108
109/* ---------------------------------------------------------------------------
110 * Math utilities.
111 */
112
113/* k = i+j overflows iff k differs in sign from both inputs,
114 * iff k^i has sign bit set and k^j has sign bit set,
115 * iff (k^i)&(k^j) has sign bit set.
116 */
117#define SIGNED_ADD_OVERFLOWED(RESULT, I, J) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000118 ((((RESULT) ^ (I)) & ((RESULT) ^ (J))) < 0)
Tim Peters2a799bf2002-12-16 20:18:38 +0000119
120/* Compute Python divmod(x, y), returning the quotient and storing the
121 * remainder into *r. The quotient is the floor of x/y, and that's
122 * the real point of this. C will probably truncate instead (C99
123 * requires truncation; C89 left it implementation-defined).
124 * Simplification: we *require* that y > 0 here. That's appropriate
125 * for all the uses made of it. This simplifies the code and makes
126 * the overflow case impossible (divmod(LONG_MIN, -1) is the only
127 * overflow case).
128 */
129static int
130divmod(int x, int y, int *r)
131{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000132 int quo;
Tim Peters2a799bf2002-12-16 20:18:38 +0000133
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000134 assert(y > 0);
135 quo = x / y;
136 *r = x - quo * y;
137 if (*r < 0) {
138 --quo;
139 *r += y;
140 }
141 assert(0 <= *r && *r < y);
142 return quo;
Tim Peters2a799bf2002-12-16 20:18:38 +0000143}
144
Tim Peters5d644dd2003-01-02 16:32:54 +0000145/* Round a double to the nearest long. |x| must be small enough to fit
146 * in a C long; this is not checked.
147 */
148static long
149round_to_long(double x)
150{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000151 if (x >= 0.0)
152 x = floor(x + 0.5);
153 else
154 x = ceil(x - 0.5);
155 return (long)x;
Tim Peters5d644dd2003-01-02 16:32:54 +0000156}
157
Alexander Belopolsky1790bc42010-05-31 17:33:47 +0000158/* Nearest integer to m / n for integers m and n. Half-integer results
159 * are rounded to even.
160 */
161static PyObject *
162divide_nearest(PyObject *m, PyObject *n)
163{
164 PyObject *result;
165 PyObject *temp;
166
Mark Dickinsonfa68a612010-06-07 18:47:09 +0000167 temp = _PyLong_DivmodNear(m, n);
Alexander Belopolsky1790bc42010-05-31 17:33:47 +0000168 if (temp == NULL)
169 return NULL;
170 result = PyTuple_GET_ITEM(temp, 0);
171 Py_INCREF(result);
172 Py_DECREF(temp);
173
174 return result;
175}
176
Tim Peters2a799bf2002-12-16 20:18:38 +0000177/* ---------------------------------------------------------------------------
178 * General calendrical helper functions
179 */
180
181/* For each month ordinal in 1..12, the number of days in that month,
182 * and the number of days before that month in the same year. These
183 * are correct for non-leap years only.
184 */
185static int _days_in_month[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000186 0, /* unused; this vector uses 1-based indexing */
187 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
Tim Peters2a799bf2002-12-16 20:18:38 +0000188};
189
190static int _days_before_month[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000191 0, /* unused; this vector uses 1-based indexing */
192 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
Tim Peters2a799bf2002-12-16 20:18:38 +0000193};
194
195/* year -> 1 if leap year, else 0. */
196static int
197is_leap(int year)
198{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000199 /* Cast year to unsigned. The result is the same either way, but
200 * C can generate faster code for unsigned mod than for signed
201 * mod (especially for % 4 -- a good compiler should just grab
202 * the last 2 bits when the LHS is unsigned).
203 */
204 const unsigned int ayear = (unsigned int)year;
205 return ayear % 4 == 0 && (ayear % 100 != 0 || ayear % 400 == 0);
Tim Peters2a799bf2002-12-16 20:18:38 +0000206}
207
208/* year, month -> number of days in that month in that year */
209static int
210days_in_month(int year, int month)
211{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000212 assert(month >= 1);
213 assert(month <= 12);
214 if (month == 2 && is_leap(year))
215 return 29;
216 else
217 return _days_in_month[month];
Tim Peters2a799bf2002-12-16 20:18:38 +0000218}
219
220/* year, month -> number of days in year preceeding first day of month */
221static int
222days_before_month(int year, int month)
223{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000224 int days;
Tim Peters2a799bf2002-12-16 20:18:38 +0000225
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000226 assert(month >= 1);
227 assert(month <= 12);
228 days = _days_before_month[month];
229 if (month > 2 && is_leap(year))
230 ++days;
231 return days;
Tim Peters2a799bf2002-12-16 20:18:38 +0000232}
233
234/* year -> number of days before January 1st of year. Remember that we
235 * start with year 1, so days_before_year(1) == 0.
236 */
237static int
238days_before_year(int year)
239{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000240 int y = year - 1;
241 /* This is incorrect if year <= 0; we really want the floor
242 * here. But so long as MINYEAR is 1, the smallest year this
Alexander Belopolsky59a289d2010-10-13 22:54:34 +0000243 * can see is 1.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000244 */
Alexander Belopolsky59a289d2010-10-13 22:54:34 +0000245 assert (year >= 1);
246 return y*365 + y/4 - y/100 + y/400;
Tim Peters2a799bf2002-12-16 20:18:38 +0000247}
248
249/* Number of days in 4, 100, and 400 year cycles. That these have
250 * the correct values is asserted in the module init function.
251 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000252#define DI4Y 1461 /* days_before_year(5); days in 4 years */
253#define DI100Y 36524 /* days_before_year(101); days in 100 years */
254#define DI400Y 146097 /* days_before_year(401); days in 400 years */
Tim Peters2a799bf2002-12-16 20:18:38 +0000255
256/* ordinal -> year, month, day, considering 01-Jan-0001 as day 1. */
257static void
258ord_to_ymd(int ordinal, int *year, int *month, int *day)
259{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000260 int n, n1, n4, n100, n400, leapyear, preceding;
Tim Peters2a799bf2002-12-16 20:18:38 +0000261
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000262 /* ordinal is a 1-based index, starting at 1-Jan-1. The pattern of
263 * leap years repeats exactly every 400 years. The basic strategy is
264 * to find the closest 400-year boundary at or before ordinal, then
265 * work with the offset from that boundary to ordinal. Life is much
266 * clearer if we subtract 1 from ordinal first -- then the values
267 * of ordinal at 400-year boundaries are exactly those divisible
268 * by DI400Y:
269 *
270 * D M Y n n-1
271 * -- --- ---- ---------- ----------------
272 * 31 Dec -400 -DI400Y -DI400Y -1
273 * 1 Jan -399 -DI400Y +1 -DI400Y 400-year boundary
274 * ...
275 * 30 Dec 000 -1 -2
276 * 31 Dec 000 0 -1
277 * 1 Jan 001 1 0 400-year boundary
278 * 2 Jan 001 2 1
279 * 3 Jan 001 3 2
280 * ...
281 * 31 Dec 400 DI400Y DI400Y -1
282 * 1 Jan 401 DI400Y +1 DI400Y 400-year boundary
283 */
284 assert(ordinal >= 1);
285 --ordinal;
286 n400 = ordinal / DI400Y;
287 n = ordinal % DI400Y;
288 *year = n400 * 400 + 1;
Tim Peters2a799bf2002-12-16 20:18:38 +0000289
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000290 /* Now n is the (non-negative) offset, in days, from January 1 of
291 * year, to the desired date. Now compute how many 100-year cycles
292 * precede n.
293 * Note that it's possible for n100 to equal 4! In that case 4 full
294 * 100-year cycles precede the desired day, which implies the
295 * desired day is December 31 at the end of a 400-year cycle.
296 */
297 n100 = n / DI100Y;
298 n = n % DI100Y;
Tim Peters2a799bf2002-12-16 20:18:38 +0000299
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000300 /* Now compute how many 4-year cycles precede it. */
301 n4 = n / DI4Y;
302 n = n % DI4Y;
Tim Peters2a799bf2002-12-16 20:18:38 +0000303
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000304 /* And now how many single years. Again n1 can be 4, and again
305 * meaning that the desired day is December 31 at the end of the
306 * 4-year cycle.
307 */
308 n1 = n / 365;
309 n = n % 365;
Tim Peters2a799bf2002-12-16 20:18:38 +0000310
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000311 *year += n100 * 100 + n4 * 4 + n1;
312 if (n1 == 4 || n100 == 4) {
313 assert(n == 0);
314 *year -= 1;
315 *month = 12;
316 *day = 31;
317 return;
318 }
Tim Peters2a799bf2002-12-16 20:18:38 +0000319
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000320 /* Now the year is correct, and n is the offset from January 1. We
321 * find the month via an estimate that's either exact or one too
322 * large.
323 */
324 leapyear = n1 == 3 && (n4 != 24 || n100 == 3);
325 assert(leapyear == is_leap(*year));
326 *month = (n + 50) >> 5;
327 preceding = (_days_before_month[*month] + (*month > 2 && leapyear));
328 if (preceding > n) {
329 /* estimate is too large */
330 *month -= 1;
331 preceding -= days_in_month(*year, *month);
332 }
333 n -= preceding;
334 assert(0 <= n);
335 assert(n < days_in_month(*year, *month));
Tim Peters2a799bf2002-12-16 20:18:38 +0000336
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000337 *day = n + 1;
Tim Peters2a799bf2002-12-16 20:18:38 +0000338}
339
340/* year, month, day -> ordinal, considering 01-Jan-0001 as day 1. */
341static int
342ymd_to_ord(int year, int month, int day)
343{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000344 return days_before_year(year) + days_before_month(year, month) + day;
Tim Peters2a799bf2002-12-16 20:18:38 +0000345}
346
347/* Day of week, where Monday==0, ..., Sunday==6. 1/1/1 was a Monday. */
348static int
349weekday(int year, int month, int day)
350{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000351 return (ymd_to_ord(year, month, day) + 6) % 7;
Tim Peters2a799bf2002-12-16 20:18:38 +0000352}
353
354/* Ordinal of the Monday starting week 1 of the ISO year. Week 1 is the
355 * first calendar week containing a Thursday.
356 */
357static int
358iso_week1_monday(int year)
359{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000360 int first_day = ymd_to_ord(year, 1, 1); /* ord of 1/1 */
361 /* 0 if 1/1 is a Monday, 1 if a Tue, etc. */
362 int first_weekday = (first_day + 6) % 7;
363 /* ordinal of closest Monday at or before 1/1 */
364 int week1_monday = first_day - first_weekday;
Tim Peters2a799bf2002-12-16 20:18:38 +0000365
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000366 if (first_weekday > 3) /* if 1/1 was Fri, Sat, Sun */
367 week1_monday += 7;
368 return week1_monday;
Tim Peters2a799bf2002-12-16 20:18:38 +0000369}
370
371/* ---------------------------------------------------------------------------
372 * Range checkers.
373 */
374
375/* Check that -MAX_DELTA_DAYS <= days <= MAX_DELTA_DAYS. If so, return 0.
376 * If not, raise OverflowError and return -1.
377 */
378static int
379check_delta_day_range(int days)
380{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000381 if (-MAX_DELTA_DAYS <= days && days <= MAX_DELTA_DAYS)
382 return 0;
383 PyErr_Format(PyExc_OverflowError,
384 "days=%d; must have magnitude <= %d",
385 days, MAX_DELTA_DAYS);
386 return -1;
Tim Peters2a799bf2002-12-16 20:18:38 +0000387}
388
389/* Check that date arguments are in range. Return 0 if they are. If they
390 * aren't, raise ValueError and return -1.
391 */
392static int
393check_date_args(int year, int month, int day)
394{
395
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000396 if (year < MINYEAR || year > MAXYEAR) {
397 PyErr_SetString(PyExc_ValueError,
398 "year is out of range");
399 return -1;
400 }
401 if (month < 1 || month > 12) {
402 PyErr_SetString(PyExc_ValueError,
403 "month must be in 1..12");
404 return -1;
405 }
406 if (day < 1 || day > days_in_month(year, month)) {
407 PyErr_SetString(PyExc_ValueError,
408 "day is out of range for month");
409 return -1;
410 }
411 return 0;
Tim Peters2a799bf2002-12-16 20:18:38 +0000412}
413
414/* Check that time arguments are in range. Return 0 if they are. If they
415 * aren't, raise ValueError and return -1.
416 */
417static int
418check_time_args(int h, int m, int s, int us)
419{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000420 if (h < 0 || h > 23) {
421 PyErr_SetString(PyExc_ValueError,
422 "hour must be in 0..23");
423 return -1;
424 }
425 if (m < 0 || m > 59) {
426 PyErr_SetString(PyExc_ValueError,
427 "minute must be in 0..59");
428 return -1;
429 }
430 if (s < 0 || s > 59) {
431 PyErr_SetString(PyExc_ValueError,
432 "second must be in 0..59");
433 return -1;
434 }
435 if (us < 0 || us > 999999) {
436 PyErr_SetString(PyExc_ValueError,
437 "microsecond must be in 0..999999");
438 return -1;
439 }
440 return 0;
Tim Peters2a799bf2002-12-16 20:18:38 +0000441}
442
443/* ---------------------------------------------------------------------------
444 * Normalization utilities.
445 */
446
447/* One step of a mixed-radix conversion. A "hi" unit is equivalent to
448 * factor "lo" units. factor must be > 0. If *lo is less than 0, or
449 * at least factor, enough of *lo is converted into "hi" units so that
450 * 0 <= *lo < factor. The input values must be such that int overflow
451 * is impossible.
452 */
453static void
454normalize_pair(int *hi, int *lo, int factor)
455{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000456 assert(factor > 0);
457 assert(lo != hi);
458 if (*lo < 0 || *lo >= factor) {
459 const int num_hi = divmod(*lo, factor, lo);
460 const int new_hi = *hi + num_hi;
461 assert(! SIGNED_ADD_OVERFLOWED(new_hi, *hi, num_hi));
462 *hi = new_hi;
463 }
464 assert(0 <= *lo && *lo < factor);
Tim Peters2a799bf2002-12-16 20:18:38 +0000465}
466
467/* Fiddle days (d), seconds (s), and microseconds (us) so that
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000468 * 0 <= *s < 24*3600
469 * 0 <= *us < 1000000
Tim Peters2a799bf2002-12-16 20:18:38 +0000470 * The input values must be such that the internals don't overflow.
471 * The way this routine is used, we don't get close.
472 */
473static void
474normalize_d_s_us(int *d, int *s, int *us)
475{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000476 if (*us < 0 || *us >= 1000000) {
477 normalize_pair(s, us, 1000000);
478 /* |s| can't be bigger than about
479 * |original s| + |original us|/1000000 now.
480 */
Tim Peters2a799bf2002-12-16 20:18:38 +0000481
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000482 }
483 if (*s < 0 || *s >= 24*3600) {
484 normalize_pair(d, s, 24*3600);
485 /* |d| can't be bigger than about
486 * |original d| +
487 * (|original s| + |original us|/1000000) / (24*3600) now.
488 */
489 }
490 assert(0 <= *s && *s < 24*3600);
491 assert(0 <= *us && *us < 1000000);
Tim Peters2a799bf2002-12-16 20:18:38 +0000492}
493
494/* Fiddle years (y), months (m), and days (d) so that
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000495 * 1 <= *m <= 12
496 * 1 <= *d <= days_in_month(*y, *m)
Tim Peters2a799bf2002-12-16 20:18:38 +0000497 * The input values must be such that the internals don't overflow.
498 * The way this routine is used, we don't get close.
499 */
Alexander Belopolskyf03a6162010-05-27 21:42:58 +0000500static int
Tim Peters2a799bf2002-12-16 20:18:38 +0000501normalize_y_m_d(int *y, int *m, int *d)
502{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000503 int dim; /* # of days in month */
Tim Peters2a799bf2002-12-16 20:18:38 +0000504
Alexander Belopolsky59a289d2010-10-13 22:54:34 +0000505 /* In actual use, m is always the month component extracted from a
506 * date/datetime object. Therefore it is always in [1, 12] range.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000507 */
Alexander Belopolsky59a289d2010-10-13 22:54:34 +0000508
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000509 assert(1 <= *m && *m <= 12);
Tim Peters2a799bf2002-12-16 20:18:38 +0000510
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000511 /* Now only day can be out of bounds (year may also be out of bounds
512 * for a datetime object, but we don't care about that here).
513 * If day is out of bounds, what to do is arguable, but at least the
514 * method here is principled and explainable.
515 */
516 dim = days_in_month(*y, *m);
517 if (*d < 1 || *d > dim) {
518 /* Move day-1 days from the first of the month. First try to
519 * get off cheap if we're only one day out of range
520 * (adjustments for timezone alone can't be worse than that).
521 */
522 if (*d == 0) {
523 --*m;
524 if (*m > 0)
525 *d = days_in_month(*y, *m);
526 else {
527 --*y;
528 *m = 12;
529 *d = 31;
530 }
531 }
532 else if (*d == dim + 1) {
533 /* move forward a day */
534 ++*m;
535 *d = 1;
536 if (*m > 12) {
537 *m = 1;
538 ++*y;
539 }
540 }
541 else {
542 int ordinal = ymd_to_ord(*y, *m, 1) +
543 *d - 1;
Alexander Belopolskyf03a6162010-05-27 21:42:58 +0000544 if (ordinal < 1 || ordinal > MAXORDINAL) {
545 goto error;
546 } else {
547 ord_to_ymd(ordinal, y, m, d);
548 return 0;
549 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000550 }
551 }
552 assert(*m > 0);
553 assert(*d > 0);
Alexander Belopolskyf03a6162010-05-27 21:42:58 +0000554 if (MINYEAR <= *y && *y <= MAXYEAR)
555 return 0;
556 error:
557 PyErr_SetString(PyExc_OverflowError,
558 "date value out of range");
559 return -1;
560
Tim Peters2a799bf2002-12-16 20:18:38 +0000561}
562
563/* Fiddle out-of-bounds months and days so that the result makes some kind
564 * of sense. The parameters are both inputs and outputs. Returns < 0 on
565 * failure, where failure means the adjusted year is out of bounds.
566 */
567static int
568normalize_date(int *year, int *month, int *day)
569{
Alexander Belopolskyf03a6162010-05-27 21:42:58 +0000570 return normalize_y_m_d(year, month, day);
Tim Peters2a799bf2002-12-16 20:18:38 +0000571}
572
573/* Force all the datetime fields into range. The parameters are both
574 * inputs and outputs. Returns < 0 on error.
575 */
576static int
577normalize_datetime(int *year, int *month, int *day,
578 int *hour, int *minute, int *second,
579 int *microsecond)
580{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000581 normalize_pair(second, microsecond, 1000000);
582 normalize_pair(minute, second, 60);
583 normalize_pair(hour, minute, 60);
584 normalize_pair(day, hour, 24);
585 return normalize_date(year, month, day);
Tim Peters2a799bf2002-12-16 20:18:38 +0000586}
587
588/* ---------------------------------------------------------------------------
Tim Petersb0c854d2003-05-17 15:57:00 +0000589 * Basic object allocation: tp_alloc implementations. These allocate
590 * Python objects of the right size and type, and do the Python object-
591 * initialization bit. If there's not enough memory, they return NULL after
592 * setting MemoryError. All data members remain uninitialized trash.
593 *
594 * We abuse the tp_alloc "nitems" argument to communicate whether a tzinfo
Tim Peters03eaf8b2003-05-18 02:24:46 +0000595 * member is needed. This is ugly, imprecise, and possibly insecure.
596 * tp_basicsize for the time and datetime types is set to the size of the
597 * struct that has room for the tzinfo member, so subclasses in Python will
598 * allocate enough space for a tzinfo member whether or not one is actually
599 * needed. That's the "ugly and imprecise" parts. The "possibly insecure"
600 * part is that PyType_GenericAlloc() (which subclasses in Python end up
601 * using) just happens today to effectively ignore the nitems argument
602 * when tp_itemsize is 0, which it is for these type objects. If that
603 * changes, perhaps the callers of tp_alloc slots in this file should
604 * be changed to force a 0 nitems argument unless the type being allocated
605 * is a base type implemented in this file (so that tp_alloc is time_alloc
606 * or datetime_alloc below, which know about the nitems abuse).
Tim Petersb0c854d2003-05-17 15:57:00 +0000607 */
608
609static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000610time_alloc(PyTypeObject *type, Py_ssize_t aware)
Tim Petersb0c854d2003-05-17 15:57:00 +0000611{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000612 PyObject *self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000613
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000614 self = (PyObject *)
615 PyObject_MALLOC(aware ?
616 sizeof(PyDateTime_Time) :
617 sizeof(_PyDateTime_BaseTime));
618 if (self == NULL)
619 return (PyObject *)PyErr_NoMemory();
620 PyObject_INIT(self, type);
621 return self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000622}
623
624static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000625datetime_alloc(PyTypeObject *type, Py_ssize_t aware)
Tim Petersb0c854d2003-05-17 15:57:00 +0000626{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000627 PyObject *self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000628
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000629 self = (PyObject *)
630 PyObject_MALLOC(aware ?
631 sizeof(PyDateTime_DateTime) :
632 sizeof(_PyDateTime_BaseDateTime));
633 if (self == NULL)
634 return (PyObject *)PyErr_NoMemory();
635 PyObject_INIT(self, type);
636 return self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000637}
638
639/* ---------------------------------------------------------------------------
640 * Helpers for setting object fields. These work on pointers to the
641 * appropriate base class.
642 */
643
644/* For date and datetime. */
645static void
646set_date_fields(PyDateTime_Date *self, int y, int m, int d)
647{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000648 self->hashcode = -1;
649 SET_YEAR(self, y);
650 SET_MONTH(self, m);
651 SET_DAY(self, d);
Tim Petersb0c854d2003-05-17 15:57:00 +0000652}
653
654/* ---------------------------------------------------------------------------
655 * Create various objects, mostly without range checking.
656 */
657
658/* Create a date instance with no range checking. */
659static PyObject *
660new_date_ex(int year, int month, int day, PyTypeObject *type)
661{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000662 PyDateTime_Date *self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000663
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000664 self = (PyDateTime_Date *) (type->tp_alloc(type, 0));
665 if (self != NULL)
666 set_date_fields(self, year, month, day);
667 return (PyObject *) self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000668}
669
670#define new_date(year, month, day) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000671 new_date_ex(year, month, day, &PyDateTime_DateType)
Tim Petersb0c854d2003-05-17 15:57:00 +0000672
673/* Create a datetime instance with no range checking. */
674static PyObject *
675new_datetime_ex(int year, int month, int day, int hour, int minute,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000676 int second, int usecond, PyObject *tzinfo, PyTypeObject *type)
Tim Petersb0c854d2003-05-17 15:57:00 +0000677{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000678 PyDateTime_DateTime *self;
679 char aware = tzinfo != Py_None;
Tim Petersb0c854d2003-05-17 15:57:00 +0000680
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000681 self = (PyDateTime_DateTime *) (type->tp_alloc(type, aware));
682 if (self != NULL) {
683 self->hastzinfo = aware;
684 set_date_fields((PyDateTime_Date *)self, year, month, day);
685 DATE_SET_HOUR(self, hour);
686 DATE_SET_MINUTE(self, minute);
687 DATE_SET_SECOND(self, second);
688 DATE_SET_MICROSECOND(self, usecond);
689 if (aware) {
690 Py_INCREF(tzinfo);
691 self->tzinfo = tzinfo;
692 }
693 }
694 return (PyObject *)self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000695}
696
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000697#define new_datetime(y, m, d, hh, mm, ss, us, tzinfo) \
698 new_datetime_ex(y, m, d, hh, mm, ss, us, tzinfo, \
699 &PyDateTime_DateTimeType)
Tim Petersb0c854d2003-05-17 15:57:00 +0000700
701/* Create a time instance with no range checking. */
702static PyObject *
703new_time_ex(int hour, int minute, int second, int usecond,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000704 PyObject *tzinfo, PyTypeObject *type)
Tim Petersb0c854d2003-05-17 15:57:00 +0000705{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000706 PyDateTime_Time *self;
707 char aware = tzinfo != Py_None;
Tim Petersb0c854d2003-05-17 15:57:00 +0000708
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000709 self = (PyDateTime_Time *) (type->tp_alloc(type, aware));
710 if (self != NULL) {
711 self->hastzinfo = aware;
712 self->hashcode = -1;
713 TIME_SET_HOUR(self, hour);
714 TIME_SET_MINUTE(self, minute);
715 TIME_SET_SECOND(self, second);
716 TIME_SET_MICROSECOND(self, usecond);
717 if (aware) {
718 Py_INCREF(tzinfo);
719 self->tzinfo = tzinfo;
720 }
721 }
722 return (PyObject *)self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000723}
724
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000725#define new_time(hh, mm, ss, us, tzinfo) \
726 new_time_ex(hh, mm, ss, us, tzinfo, &PyDateTime_TimeType)
Tim Petersb0c854d2003-05-17 15:57:00 +0000727
728/* Create a timedelta instance. Normalize the members iff normalize is
729 * true. Passing false is a speed optimization, if you know for sure
730 * that seconds and microseconds are already in their proper ranges. In any
731 * case, raises OverflowError and returns NULL if the normalized days is out
732 * of range).
733 */
734static PyObject *
735new_delta_ex(int days, int seconds, int microseconds, int normalize,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000736 PyTypeObject *type)
Tim Petersb0c854d2003-05-17 15:57:00 +0000737{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000738 PyDateTime_Delta *self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000739
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000740 if (normalize)
741 normalize_d_s_us(&days, &seconds, &microseconds);
742 assert(0 <= seconds && seconds < 24*3600);
743 assert(0 <= microseconds && microseconds < 1000000);
Tim Petersb0c854d2003-05-17 15:57:00 +0000744
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000745 if (check_delta_day_range(days) < 0)
746 return NULL;
Tim Petersb0c854d2003-05-17 15:57:00 +0000747
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000748 self = (PyDateTime_Delta *) (type->tp_alloc(type, 0));
749 if (self != NULL) {
750 self->hashcode = -1;
751 SET_TD_DAYS(self, days);
752 SET_TD_SECONDS(self, seconds);
753 SET_TD_MICROSECONDS(self, microseconds);
754 }
755 return (PyObject *) self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000756}
757
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000758#define new_delta(d, s, us, normalize) \
759 new_delta_ex(d, s, us, normalize, &PyDateTime_DeltaType)
Tim Petersb0c854d2003-05-17 15:57:00 +0000760
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000761
762typedef struct
763{
764 PyObject_HEAD
765 PyObject *offset;
766 PyObject *name;
767} PyDateTime_TimeZone;
768
Victor Stinner6ced7c42011-03-21 18:15:42 +0100769/* The interned UTC timezone instance */
Alexander Belopolsky1bcbaab2010-10-14 17:03:51 +0000770static PyObject *PyDateTime_TimeZone_UTC;
Alexander Belopolskya11d8c02010-07-06 23:19:45 +0000771
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000772/* Create new timezone instance checking offset range. This
773 function does not check the name argument. Caller must assure
774 that offset is a timedelta instance and name is either NULL
775 or a unicode object. */
776static PyObject *
Alexander Belopolsky1bcbaab2010-10-14 17:03:51 +0000777create_timezone(PyObject *offset, PyObject *name)
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000778{
779 PyDateTime_TimeZone *self;
780 PyTypeObject *type = &PyDateTime_TimeZoneType;
781
782 assert(offset != NULL);
783 assert(PyDelta_Check(offset));
784 assert(name == NULL || PyUnicode_Check(name));
785
Alexander Belopolsky1bcbaab2010-10-14 17:03:51 +0000786 self = (PyDateTime_TimeZone *)(type->tp_alloc(type, 0));
787 if (self == NULL) {
788 return NULL;
789 }
790 Py_INCREF(offset);
791 self->offset = offset;
792 Py_XINCREF(name);
793 self->name = name;
794 return (PyObject *)self;
795}
796
797static int delta_bool(PyDateTime_Delta *self);
798
799static PyObject *
800new_timezone(PyObject *offset, PyObject *name)
801{
802 assert(offset != NULL);
803 assert(PyDelta_Check(offset));
804 assert(name == NULL || PyUnicode_Check(name));
805
806 if (name == NULL && delta_bool((PyDateTime_Delta *)offset) == 0) {
807 Py_INCREF(PyDateTime_TimeZone_UTC);
808 return PyDateTime_TimeZone_UTC;
809 }
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000810 if (GET_TD_MICROSECONDS(offset) != 0 || GET_TD_SECONDS(offset) % 60 != 0) {
811 PyErr_Format(PyExc_ValueError, "offset must be a timedelta"
812 " representing a whole number of minutes");
813 return NULL;
814 }
815 if ((GET_TD_DAYS(offset) == -1 && GET_TD_SECONDS(offset) == 0) ||
816 GET_TD_DAYS(offset) < -1 || GET_TD_DAYS(offset) >= 1) {
817 PyErr_Format(PyExc_ValueError, "offset must be a timedelta"
818 " strictly between -timedelta(hours=24) and"
819 " timedelta(hours=24).");
820 return NULL;
821 }
822
Alexander Belopolsky1bcbaab2010-10-14 17:03:51 +0000823 return create_timezone(offset, name);
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000824}
825
Tim Petersb0c854d2003-05-17 15:57:00 +0000826/* ---------------------------------------------------------------------------
Tim Peters2a799bf2002-12-16 20:18:38 +0000827 * tzinfo helpers.
828 */
829
Tim Peters855fe882002-12-22 03:43:39 +0000830/* Ensure that p is None or of a tzinfo subclass. Return 0 if OK; if not
831 * raise TypeError and return -1.
832 */
833static int
834check_tzinfo_subclass(PyObject *p)
835{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000836 if (p == Py_None || PyTZInfo_Check(p))
837 return 0;
838 PyErr_Format(PyExc_TypeError,
839 "tzinfo argument must be None or of a tzinfo subclass, "
840 "not type '%s'",
841 Py_TYPE(p)->tp_name);
842 return -1;
Tim Peters855fe882002-12-22 03:43:39 +0000843}
844
Tim Peters2a799bf2002-12-16 20:18:38 +0000845/* If self has a tzinfo member, return a BORROWED reference to it. Else
846 * return NULL, which is NOT AN ERROR. There are no error returns here,
847 * and the caller must not decref the result.
848 */
849static PyObject *
850get_tzinfo_member(PyObject *self)
851{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000852 PyObject *tzinfo = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +0000853
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000854 if (PyDateTime_Check(self) && HASTZINFO(self))
855 tzinfo = ((PyDateTime_DateTime *)self)->tzinfo;
856 else if (PyTime_Check(self) && HASTZINFO(self))
857 tzinfo = ((PyDateTime_Time *)self)->tzinfo;
Tim Peters2a799bf2002-12-16 20:18:38 +0000858
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000859 return tzinfo;
Tim Peters2a799bf2002-12-16 20:18:38 +0000860}
861
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000862/* Call getattr(tzinfo, name)(tzinfoarg), and check the result. tzinfo must
863 * be an instance of the tzinfo class. If the method returns None, this
864 * returns None. If the method doesn't return None or timedelta, TypeError is
865 * raised and this returns NULL. If it returns a timedelta and the value is
866 * out of range or isn't a whole number of minutes, ValueError is raised and
867 * this returns NULL. Else result is returned.
Tim Peters2a799bf2002-12-16 20:18:38 +0000868 */
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000869static PyObject *
870call_tzinfo_method(PyObject *tzinfo, char *name, PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +0000871{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000872 PyObject *offset;
Tim Peters2a799bf2002-12-16 20:18:38 +0000873
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000874 assert(tzinfo != NULL);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000875 assert(PyTZInfo_Check(tzinfo) || tzinfo == Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000876 assert(tzinfoarg != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +0000877
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000878 if (tzinfo == Py_None)
879 Py_RETURN_NONE;
880 offset = PyObject_CallMethod(tzinfo, name, "O", tzinfoarg);
881 if (offset == Py_None || offset == NULL)
882 return offset;
883 if (PyDelta_Check(offset)) {
884 if (GET_TD_MICROSECONDS(offset) != 0 || GET_TD_SECONDS(offset) % 60 != 0) {
885 Py_DECREF(offset);
886 PyErr_Format(PyExc_ValueError, "offset must be a timedelta"
887 " representing a whole number of minutes");
888 return NULL;
889 }
890 if ((GET_TD_DAYS(offset) == -1 && GET_TD_SECONDS(offset) == 0) ||
891 GET_TD_DAYS(offset) < -1 || GET_TD_DAYS(offset) >= 1) {
892 Py_DECREF(offset);
893 PyErr_Format(PyExc_ValueError, "offset must be a timedelta"
894 " strictly between -timedelta(hours=24) and"
895 " timedelta(hours=24).");
896 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000897 }
898 }
899 else {
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000900 Py_DECREF(offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000901 PyErr_Format(PyExc_TypeError,
902 "tzinfo.%s() must return None or "
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000903 "timedelta, not '%.200s'",
904 name, Py_TYPE(offset)->tp_name);
905 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000906 }
Tim Peters2a799bf2002-12-16 20:18:38 +0000907
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000908 return offset;
Tim Peters2a799bf2002-12-16 20:18:38 +0000909}
910
911/* Call tzinfo.utcoffset(tzinfoarg), and extract an integer from the
912 * result. tzinfo must be an instance of the tzinfo class. If utcoffset()
913 * returns None, call_utcoffset returns 0 and sets *none to 1. If uctoffset()
Tim Peters397301e2003-01-02 21:28:08 +0000914 * doesn't return None or timedelta, TypeError is raised and this returns -1.
915 * If utcoffset() returns an invalid timedelta (out of range, or not a whole
916 * # of minutes), ValueError is raised and this returns -1. Else *none is
917 * set to 0 and the offset is returned (as int # of minutes east of UTC).
Tim Peters2a799bf2002-12-16 20:18:38 +0000918 */
Tim Peters855fe882002-12-22 03:43:39 +0000919static PyObject *
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000920call_utcoffset(PyObject *tzinfo, PyObject *tzinfoarg)
921{
922 return call_tzinfo_method(tzinfo, "utcoffset", tzinfoarg);
Tim Peters855fe882002-12-22 03:43:39 +0000923}
924
Tim Peters2a799bf2002-12-16 20:18:38 +0000925/* Call tzinfo.dst(tzinfoarg), and extract an integer from the
926 * result. tzinfo must be an instance of the tzinfo class. If dst()
927 * returns None, call_dst returns 0 and sets *none to 1. If dst()
Tim Peters397301e2003-01-02 21:28:08 +0000928 & doesn't return None or timedelta, TypeError is raised and this
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000929 * returns -1. If dst() returns an invalid timedelta for a UTC offset,
Tim Peters397301e2003-01-02 21:28:08 +0000930 * ValueError is raised and this returns -1. Else *none is set to 0 and
931 * the offset is returned (as an int # of minutes east of UTC).
Tim Peters2a799bf2002-12-16 20:18:38 +0000932 */
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000933static PyObject *
934call_dst(PyObject *tzinfo, PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +0000935{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000936 return call_tzinfo_method(tzinfo, "dst", tzinfoarg);
Tim Peters2a799bf2002-12-16 20:18:38 +0000937}
938
Tim Petersbad8ff02002-12-30 20:52:32 +0000939/* Call tzinfo.tzname(tzinfoarg), and return the result. tzinfo must be
Tim Peters855fe882002-12-22 03:43:39 +0000940 * an instance of the tzinfo class or None. If tzinfo isn't None, and
Tim Petersbad8ff02002-12-30 20:52:32 +0000941 * tzname() doesn't return None or a string, TypeError is raised and this
Guido van Rossume3d1d412007-05-23 21:24:35 +0000942 * returns NULL. If the result is a string, we ensure it is a Unicode
943 * string.
Tim Peters2a799bf2002-12-16 20:18:38 +0000944 */
945static PyObject *
Tim Petersbad8ff02002-12-30 20:52:32 +0000946call_tzname(PyObject *tzinfo, PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +0000947{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000948 PyObject *result;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200949 _Py_IDENTIFIER(tzname);
Tim Peters2a799bf2002-12-16 20:18:38 +0000950
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000951 assert(tzinfo != NULL);
952 assert(check_tzinfo_subclass(tzinfo) >= 0);
953 assert(tzinfoarg != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +0000954
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000955 if (tzinfo == Py_None)
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000956 Py_RETURN_NONE;
Tim Peters2a799bf2002-12-16 20:18:38 +0000957
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200958 result = _PyObject_CallMethodId(tzinfo, &PyId_tzname, "O", tzinfoarg);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000959
960 if (result == NULL || result == Py_None)
961 return result;
962
963 if (!PyUnicode_Check(result)) {
964 PyErr_Format(PyExc_TypeError, "tzinfo.tzname() must "
965 "return None or a string, not '%s'",
966 Py_TYPE(result)->tp_name);
967 Py_DECREF(result);
968 result = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000969 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000970
971 return result;
Tim Peters00237032002-12-27 02:21:51 +0000972}
973
Tim Peters2a799bf2002-12-16 20:18:38 +0000974/* repr is like "someclass(arg1, arg2)". If tzinfo isn't None,
975 * stuff
976 * ", tzinfo=" + repr(tzinfo)
977 * before the closing ")".
978 */
979static PyObject *
980append_keyword_tzinfo(PyObject *repr, PyObject *tzinfo)
981{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000982 PyObject *temp;
Tim Peters2a799bf2002-12-16 20:18:38 +0000983
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000984 assert(PyUnicode_Check(repr));
985 assert(tzinfo);
986 if (tzinfo == Py_None)
987 return repr;
988 /* Get rid of the trailing ')'. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200989 assert(PyUnicode_READ_CHAR(repr, PyUnicode_GET_LENGTH(repr)-1) == ')');
990 temp = PyUnicode_Substring(repr, 0, PyUnicode_GET_LENGTH(repr) - 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000991 Py_DECREF(repr);
992 if (temp == NULL)
993 return NULL;
994 repr = PyUnicode_FromFormat("%U, tzinfo=%R)", temp, tzinfo);
995 Py_DECREF(temp);
996 return repr;
Tim Peters2a799bf2002-12-16 20:18:38 +0000997}
998
999/* ---------------------------------------------------------------------------
1000 * String format helpers.
1001 */
1002
1003static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00001004format_ctime(PyDateTime_Date *date, int hours, int minutes, int seconds)
Tim Peters2a799bf2002-12-16 20:18:38 +00001005{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001006 static const char *DayNames[] = {
1007 "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"
1008 };
1009 static const char *MonthNames[] = {
1010 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
1011 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
1012 };
Tim Peters2a799bf2002-12-16 20:18:38 +00001013
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001014 int wday = weekday(GET_YEAR(date), GET_MONTH(date), GET_DAY(date));
Tim Peters2a799bf2002-12-16 20:18:38 +00001015
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001016 return PyUnicode_FromFormat("%s %s %2d %02d:%02d:%02d %04d",
1017 DayNames[wday], MonthNames[GET_MONTH(date)-1],
1018 GET_DAY(date), hours, minutes, seconds,
1019 GET_YEAR(date));
Tim Peters2a799bf2002-12-16 20:18:38 +00001020}
1021
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001022static PyObject *delta_negative(PyDateTime_Delta *self);
1023
Tim Peters2a799bf2002-12-16 20:18:38 +00001024/* Add an hours & minutes UTC offset string to buf. buf has no more than
1025 * buflen bytes remaining. The UTC offset is gotten by calling
1026 * tzinfo.uctoffset(tzinfoarg). If that returns None, \0 is stored into
1027 * *buf, and that's all. Else the returned value is checked for sanity (an
1028 * integer in range), and if that's OK it's converted to an hours & minutes
1029 * string of the form
1030 * sign HH sep MM
1031 * Returns 0 if everything is OK. If the return value from utcoffset() is
1032 * bogus, an appropriate exception is set and -1 is returned.
1033 */
1034static int
Tim Peters328fff72002-12-20 01:31:27 +00001035format_utcoffset(char *buf, size_t buflen, const char *sep,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001036 PyObject *tzinfo, PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +00001037{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001038 PyObject *offset;
1039 int hours, minutes, seconds;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001040 char sign;
Tim Peters2a799bf2002-12-16 20:18:38 +00001041
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001042 assert(buflen >= 1);
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00001043
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001044 offset = call_utcoffset(tzinfo, tzinfoarg);
1045 if (offset == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001046 return -1;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001047 if (offset == Py_None) {
1048 Py_DECREF(offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001049 *buf = '\0';
1050 return 0;
1051 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001052 /* Offset is normalized, so it is negative if days < 0 */
1053 if (GET_TD_DAYS(offset) < 0) {
1054 PyObject *temp = offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001055 sign = '-';
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001056 offset = delta_negative((PyDateTime_Delta *)offset);
1057 Py_DECREF(temp);
1058 if (offset == NULL)
1059 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001060 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001061 else {
1062 sign = '+';
1063 }
1064 /* Offset is not negative here. */
1065 seconds = GET_TD_SECONDS(offset);
1066 Py_DECREF(offset);
1067 minutes = divmod(seconds, 60, &seconds);
1068 hours = divmod(minutes, 60, &minutes);
1069 assert(seconds == 0);
1070 /* XXX ignore sub-minute data, curently not allowed. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001071 PyOS_snprintf(buf, buflen, "%c%02d%s%02d", sign, hours, sep, minutes);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001072
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001073 return 0;
Tim Peters2a799bf2002-12-16 20:18:38 +00001074}
1075
Guido van Rossumd8595fe2007-05-23 21:36:49 +00001076static PyObject *
1077make_Zreplacement(PyObject *object, PyObject *tzinfoarg)
1078{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001079 PyObject *temp;
1080 PyObject *tzinfo = get_tzinfo_member(object);
1081 PyObject *Zreplacement = PyUnicode_FromStringAndSize(NULL, 0);
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001082 _Py_IDENTIFIER(replace);
Victor Stinner9e30aa52011-11-21 02:49:52 +01001083
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001084 if (Zreplacement == NULL)
1085 return NULL;
1086 if (tzinfo == Py_None || tzinfo == NULL)
1087 return Zreplacement;
Neal Norwitzaea70e02007-08-12 04:32:26 +00001088
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001089 assert(tzinfoarg != NULL);
1090 temp = call_tzname(tzinfo, tzinfoarg);
1091 if (temp == NULL)
1092 goto Error;
1093 if (temp == Py_None) {
1094 Py_DECREF(temp);
1095 return Zreplacement;
1096 }
Neal Norwitzaea70e02007-08-12 04:32:26 +00001097
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001098 assert(PyUnicode_Check(temp));
1099 /* Since the tzname is getting stuffed into the
1100 * format, we have to double any % signs so that
1101 * strftime doesn't treat them as format codes.
1102 */
1103 Py_DECREF(Zreplacement);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001104 Zreplacement = _PyObject_CallMethodId(temp, &PyId_replace, "ss", "%", "%%");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001105 Py_DECREF(temp);
1106 if (Zreplacement == NULL)
1107 return NULL;
1108 if (!PyUnicode_Check(Zreplacement)) {
1109 PyErr_SetString(PyExc_TypeError,
1110 "tzname.replace() did not return a string");
1111 goto Error;
1112 }
1113 return Zreplacement;
Guido van Rossumd8595fe2007-05-23 21:36:49 +00001114
1115 Error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001116 Py_DECREF(Zreplacement);
1117 return NULL;
Guido van Rossumd8595fe2007-05-23 21:36:49 +00001118}
1119
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001120static PyObject *
1121make_freplacement(PyObject *object)
1122{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001123 char freplacement[64];
1124 if (PyTime_Check(object))
1125 sprintf(freplacement, "%06d", TIME_GET_MICROSECOND(object));
1126 else if (PyDateTime_Check(object))
1127 sprintf(freplacement, "%06d", DATE_GET_MICROSECOND(object));
1128 else
1129 sprintf(freplacement, "%06d", 0);
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001130
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001131 return PyBytes_FromStringAndSize(freplacement, strlen(freplacement));
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001132}
1133
Tim Peters2a799bf2002-12-16 20:18:38 +00001134/* I sure don't want to reproduce the strftime code from the time module,
1135 * so this imports the module and calls it. All the hair is due to
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001136 * giving special meanings to the %z, %Z and %f format codes via a
1137 * preprocessing step on the format string.
Tim Petersbad8ff02002-12-30 20:52:32 +00001138 * tzinfoarg is the argument to pass to the object's tzinfo method, if
1139 * needed.
Tim Peters2a799bf2002-12-16 20:18:38 +00001140 */
1141static PyObject *
Tim Petersbad8ff02002-12-30 20:52:32 +00001142wrap_strftime(PyObject *object, PyObject *format, PyObject *timetuple,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001143 PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +00001144{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001145 PyObject *result = NULL; /* guilty until proved innocent */
Tim Peters2a799bf2002-12-16 20:18:38 +00001146
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001147 PyObject *zreplacement = NULL; /* py string, replacement for %z */
1148 PyObject *Zreplacement = NULL; /* py string, replacement for %Z */
1149 PyObject *freplacement = NULL; /* py string, replacement for %f */
Tim Peters2a799bf2002-12-16 20:18:38 +00001150
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001151 const char *pin; /* pointer to next char in input format */
1152 Py_ssize_t flen; /* length of input format */
1153 char ch; /* next char in input format */
Tim Peters2a799bf2002-12-16 20:18:38 +00001154
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001155 PyObject *newfmt = NULL; /* py string, the output format */
1156 char *pnew; /* pointer to available byte in output format */
1157 size_t totalnew; /* number bytes total in output format buffer,
1158 exclusive of trailing \0 */
1159 size_t usednew; /* number bytes used so far in output format buffer */
Tim Peters2a799bf2002-12-16 20:18:38 +00001160
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001161 const char *ptoappend; /* ptr to string to append to output buffer */
1162 Py_ssize_t ntoappend; /* # of bytes to append to output buffer */
Tim Peters2a799bf2002-12-16 20:18:38 +00001163
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001164 assert(object && format && timetuple);
1165 assert(PyUnicode_Check(format));
1166 /* Convert the input format to a C string and size */
1167 pin = _PyUnicode_AsStringAndSize(format, &flen);
1168 if (!pin)
1169 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001170
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001171 /* Scan the input format, looking for %z/%Z/%f escapes, building
1172 * a new format. Since computing the replacements for those codes
1173 * is expensive, don't unless they're actually used.
1174 */
1175 if (flen > INT_MAX - 1) {
1176 PyErr_NoMemory();
1177 goto Done;
1178 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00001179
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001180 totalnew = flen + 1; /* realistic if no %z/%Z */
1181 newfmt = PyBytes_FromStringAndSize(NULL, totalnew);
1182 if (newfmt == NULL) goto Done;
1183 pnew = PyBytes_AsString(newfmt);
1184 usednew = 0;
Tim Peters2a799bf2002-12-16 20:18:38 +00001185
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001186 while ((ch = *pin++) != '\0') {
1187 if (ch != '%') {
1188 ptoappend = pin - 1;
1189 ntoappend = 1;
1190 }
1191 else if ((ch = *pin++) == '\0') {
1192 /* There's a lone trailing %; doesn't make sense. */
1193 PyErr_SetString(PyExc_ValueError, "strftime format "
1194 "ends with raw %");
1195 goto Done;
1196 }
1197 /* A % has been seen and ch is the character after it. */
1198 else if (ch == 'z') {
1199 if (zreplacement == NULL) {
1200 /* format utcoffset */
1201 char buf[100];
1202 PyObject *tzinfo = get_tzinfo_member(object);
1203 zreplacement = PyBytes_FromStringAndSize("", 0);
1204 if (zreplacement == NULL) goto Done;
1205 if (tzinfo != Py_None && tzinfo != NULL) {
1206 assert(tzinfoarg != NULL);
1207 if (format_utcoffset(buf,
1208 sizeof(buf),
1209 "",
1210 tzinfo,
1211 tzinfoarg) < 0)
1212 goto Done;
1213 Py_DECREF(zreplacement);
1214 zreplacement =
1215 PyBytes_FromStringAndSize(buf,
1216 strlen(buf));
1217 if (zreplacement == NULL)
1218 goto Done;
1219 }
1220 }
1221 assert(zreplacement != NULL);
1222 ptoappend = PyBytes_AS_STRING(zreplacement);
1223 ntoappend = PyBytes_GET_SIZE(zreplacement);
1224 }
1225 else if (ch == 'Z') {
1226 /* format tzname */
1227 if (Zreplacement == NULL) {
1228 Zreplacement = make_Zreplacement(object,
1229 tzinfoarg);
1230 if (Zreplacement == NULL)
1231 goto Done;
1232 }
1233 assert(Zreplacement != NULL);
1234 assert(PyUnicode_Check(Zreplacement));
1235 ptoappend = _PyUnicode_AsStringAndSize(Zreplacement,
1236 &ntoappend);
Alexander Belopolskye239d232010-12-08 23:31:48 +00001237 if (ptoappend == NULL)
1238 goto Done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001239 }
1240 else if (ch == 'f') {
1241 /* format microseconds */
1242 if (freplacement == NULL) {
1243 freplacement = make_freplacement(object);
1244 if (freplacement == NULL)
1245 goto Done;
1246 }
1247 assert(freplacement != NULL);
1248 assert(PyBytes_Check(freplacement));
1249 ptoappend = PyBytes_AS_STRING(freplacement);
1250 ntoappend = PyBytes_GET_SIZE(freplacement);
1251 }
1252 else {
1253 /* percent followed by neither z nor Z */
1254 ptoappend = pin - 2;
1255 ntoappend = 2;
1256 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001257
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001258 /* Append the ntoappend chars starting at ptoappend to
1259 * the new format.
1260 */
1261 if (ntoappend == 0)
1262 continue;
1263 assert(ptoappend != NULL);
1264 assert(ntoappend > 0);
1265 while (usednew + ntoappend > totalnew) {
1266 size_t bigger = totalnew << 1;
1267 if ((bigger >> 1) != totalnew) { /* overflow */
1268 PyErr_NoMemory();
1269 goto Done;
1270 }
1271 if (_PyBytes_Resize(&newfmt, bigger) < 0)
1272 goto Done;
1273 totalnew = bigger;
1274 pnew = PyBytes_AsString(newfmt) + usednew;
1275 }
1276 memcpy(pnew, ptoappend, ntoappend);
1277 pnew += ntoappend;
1278 usednew += ntoappend;
1279 assert(usednew <= totalnew);
1280 } /* end while() */
Tim Peters2a799bf2002-12-16 20:18:38 +00001281
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001282 if (_PyBytes_Resize(&newfmt, usednew) < 0)
1283 goto Done;
1284 {
1285 PyObject *format;
1286 PyObject *time = PyImport_ImportModuleNoBlock("time");
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001288 if (time == NULL)
1289 goto Done;
1290 format = PyUnicode_FromString(PyBytes_AS_STRING(newfmt));
1291 if (format != NULL) {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001292 _Py_IDENTIFIER(strftime);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001293
1294 result = _PyObject_CallMethodId(time, &PyId_strftime, "OO",
1295 format, timetuple, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001296 Py_DECREF(format);
1297 }
1298 Py_DECREF(time);
1299 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001300 Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001301 Py_XDECREF(freplacement);
1302 Py_XDECREF(zreplacement);
1303 Py_XDECREF(Zreplacement);
1304 Py_XDECREF(newfmt);
1305 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001306}
1307
Tim Peters2a799bf2002-12-16 20:18:38 +00001308/* ---------------------------------------------------------------------------
1309 * Wrap functions from the time module. These aren't directly available
1310 * from C. Perhaps they should be.
1311 */
1312
1313/* Call time.time() and return its result (a Python float). */
1314static PyObject *
Guido van Rossumbd43e912002-12-16 20:34:55 +00001315time_time(void)
Tim Peters2a799bf2002-12-16 20:18:38 +00001316{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001317 PyObject *result = NULL;
1318 PyObject *time = PyImport_ImportModuleNoBlock("time");
Tim Peters2a799bf2002-12-16 20:18:38 +00001319
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001320 if (time != NULL) {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001321 _Py_IDENTIFIER(time);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001322
1323 result = _PyObject_CallMethodId(time, &PyId_time, "()");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001324 Py_DECREF(time);
1325 }
1326 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001327}
1328
1329/* Build a time.struct_time. The weekday and day number are automatically
1330 * computed from the y,m,d args.
1331 */
1332static PyObject *
1333build_struct_time(int y, int m, int d, int hh, int mm, int ss, int dstflag)
1334{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001335 PyObject *time;
1336 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001337
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001338 time = PyImport_ImportModuleNoBlock("time");
1339 if (time != NULL) {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001340 _Py_IDENTIFIER(struct_time);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001341
1342 result = _PyObject_CallMethodId(time, &PyId_struct_time,
1343 "((iiiiiiiii))",
1344 y, m, d,
1345 hh, mm, ss,
1346 weekday(y, m, d),
1347 days_before_month(y, m) + d,
1348 dstflag);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001349 Py_DECREF(time);
1350 }
1351 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001352}
1353
1354/* ---------------------------------------------------------------------------
1355 * Miscellaneous helpers.
1356 */
1357
Mark Dickinsone94c6792009-02-02 20:36:42 +00001358/* For various reasons, we need to use tp_richcompare instead of tp_reserved.
Tim Peters2a799bf2002-12-16 20:18:38 +00001359 * The comparisons here all most naturally compute a cmp()-like result.
1360 * This little helper turns that into a bool result for rich comparisons.
1361 */
1362static PyObject *
1363diff_to_bool(int diff, int op)
1364{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001365 PyObject *result;
1366 int istrue;
Tim Peters2a799bf2002-12-16 20:18:38 +00001367
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001368 switch (op) {
1369 case Py_EQ: istrue = diff == 0; break;
1370 case Py_NE: istrue = diff != 0; break;
1371 case Py_LE: istrue = diff <= 0; break;
1372 case Py_GE: istrue = diff >= 0; break;
1373 case Py_LT: istrue = diff < 0; break;
1374 case Py_GT: istrue = diff > 0; break;
1375 default:
1376 assert(! "op unknown");
1377 istrue = 0; /* To shut up compiler */
1378 }
1379 result = istrue ? Py_True : Py_False;
1380 Py_INCREF(result);
1381 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001382}
1383
Tim Peters07534a62003-02-07 22:50:28 +00001384/* Raises a "can't compare" TypeError and returns NULL. */
1385static PyObject *
1386cmperror(PyObject *a, PyObject *b)
1387{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001388 PyErr_Format(PyExc_TypeError,
1389 "can't compare %s to %s",
1390 Py_TYPE(a)->tp_name, Py_TYPE(b)->tp_name);
1391 return NULL;
Tim Peters07534a62003-02-07 22:50:28 +00001392}
1393
Tim Peters2a799bf2002-12-16 20:18:38 +00001394/* ---------------------------------------------------------------------------
Tim Peters2a799bf2002-12-16 20:18:38 +00001395 * Cached Python objects; these are set by the module init function.
1396 */
1397
1398/* Conversion factors. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001399static PyObject *us_per_us = NULL; /* 1 */
1400static PyObject *us_per_ms = NULL; /* 1000 */
1401static PyObject *us_per_second = NULL; /* 1000000 */
1402static PyObject *us_per_minute = NULL; /* 1e6 * 60 as Python int */
1403static PyObject *us_per_hour = NULL; /* 1e6 * 3600 as Python long */
1404static PyObject *us_per_day = NULL; /* 1e6 * 3600 * 24 as Python long */
1405static PyObject *us_per_week = NULL; /* 1e6*3600*24*7 as Python long */
Tim Peters2a799bf2002-12-16 20:18:38 +00001406static PyObject *seconds_per_day = NULL; /* 3600*24 as Python int */
1407
Tim Peters2a799bf2002-12-16 20:18:38 +00001408/* ---------------------------------------------------------------------------
1409 * Class implementations.
1410 */
1411
1412/*
1413 * PyDateTime_Delta implementation.
1414 */
1415
1416/* Convert a timedelta to a number of us,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001417 * (24*3600*self.days + self.seconds)*1000000 + self.microseconds
Tim Peters2a799bf2002-12-16 20:18:38 +00001418 * as a Python int or long.
1419 * Doing mixed-radix arithmetic by hand instead is excruciating in C,
1420 * due to ubiquitous overflow possibilities.
1421 */
1422static PyObject *
1423delta_to_microseconds(PyDateTime_Delta *self)
1424{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001425 PyObject *x1 = NULL;
1426 PyObject *x2 = NULL;
1427 PyObject *x3 = NULL;
1428 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001429
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001430 x1 = PyLong_FromLong(GET_TD_DAYS(self));
1431 if (x1 == NULL)
1432 goto Done;
1433 x2 = PyNumber_Multiply(x1, seconds_per_day); /* days in seconds */
1434 if (x2 == NULL)
1435 goto Done;
1436 Py_DECREF(x1);
1437 x1 = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001438
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001439 /* x2 has days in seconds */
1440 x1 = PyLong_FromLong(GET_TD_SECONDS(self)); /* seconds */
1441 if (x1 == NULL)
1442 goto Done;
1443 x3 = PyNumber_Add(x1, x2); /* days and seconds in seconds */
1444 if (x3 == NULL)
1445 goto Done;
1446 Py_DECREF(x1);
1447 Py_DECREF(x2);
Brett Cannonb94767f2011-02-22 20:15:44 +00001448 /* x1 = */ x2 = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001449
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001450 /* x3 has days+seconds in seconds */
1451 x1 = PyNumber_Multiply(x3, us_per_second); /* us */
1452 if (x1 == NULL)
1453 goto Done;
1454 Py_DECREF(x3);
1455 x3 = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001456
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001457 /* x1 has days+seconds in us */
1458 x2 = PyLong_FromLong(GET_TD_MICROSECONDS(self));
1459 if (x2 == NULL)
1460 goto Done;
1461 result = PyNumber_Add(x1, x2);
Tim Peters2a799bf2002-12-16 20:18:38 +00001462
1463Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001464 Py_XDECREF(x1);
1465 Py_XDECREF(x2);
1466 Py_XDECREF(x3);
1467 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001468}
1469
1470/* Convert a number of us (as a Python int or long) to a timedelta.
1471 */
1472static PyObject *
Tim Petersb0c854d2003-05-17 15:57:00 +00001473microseconds_to_delta_ex(PyObject *pyus, PyTypeObject *type)
Tim Peters2a799bf2002-12-16 20:18:38 +00001474{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001475 int us;
1476 int s;
1477 int d;
1478 long temp;
Tim Peters2a799bf2002-12-16 20:18:38 +00001479
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001480 PyObject *tuple = NULL;
1481 PyObject *num = NULL;
1482 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001483
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001484 tuple = PyNumber_Divmod(pyus, us_per_second);
1485 if (tuple == NULL)
1486 goto Done;
Tim Peters2a799bf2002-12-16 20:18:38 +00001487
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001488 num = PyTuple_GetItem(tuple, 1); /* us */
1489 if (num == NULL)
1490 goto Done;
1491 temp = PyLong_AsLong(num);
1492 num = NULL;
1493 if (temp == -1 && PyErr_Occurred())
1494 goto Done;
1495 assert(0 <= temp && temp < 1000000);
1496 us = (int)temp;
1497 if (us < 0) {
1498 /* The divisor was positive, so this must be an error. */
1499 assert(PyErr_Occurred());
1500 goto Done;
1501 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001502
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001503 num = PyTuple_GetItem(tuple, 0); /* leftover seconds */
1504 if (num == NULL)
1505 goto Done;
1506 Py_INCREF(num);
1507 Py_DECREF(tuple);
Tim Peters2a799bf2002-12-16 20:18:38 +00001508
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001509 tuple = PyNumber_Divmod(num, seconds_per_day);
1510 if (tuple == NULL)
1511 goto Done;
1512 Py_DECREF(num);
Tim Peters2a799bf2002-12-16 20:18:38 +00001513
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001514 num = PyTuple_GetItem(tuple, 1); /* seconds */
1515 if (num == NULL)
1516 goto Done;
1517 temp = PyLong_AsLong(num);
1518 num = NULL;
1519 if (temp == -1 && PyErr_Occurred())
1520 goto Done;
1521 assert(0 <= temp && temp < 24*3600);
1522 s = (int)temp;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001523
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001524 if (s < 0) {
1525 /* The divisor was positive, so this must be an error. */
1526 assert(PyErr_Occurred());
1527 goto Done;
1528 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001529
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001530 num = PyTuple_GetItem(tuple, 0); /* leftover days */
1531 if (num == NULL)
1532 goto Done;
1533 Py_INCREF(num);
1534 temp = PyLong_AsLong(num);
1535 if (temp == -1 && PyErr_Occurred())
1536 goto Done;
1537 d = (int)temp;
1538 if ((long)d != temp) {
1539 PyErr_SetString(PyExc_OverflowError, "normalized days too "
1540 "large to fit in a C int");
1541 goto Done;
1542 }
1543 result = new_delta_ex(d, s, us, 0, type);
Tim Peters2a799bf2002-12-16 20:18:38 +00001544
1545Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001546 Py_XDECREF(tuple);
1547 Py_XDECREF(num);
1548 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001549}
1550
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001551#define microseconds_to_delta(pymicros) \
1552 microseconds_to_delta_ex(pymicros, &PyDateTime_DeltaType)
Tim Petersb0c854d2003-05-17 15:57:00 +00001553
Tim Peters2a799bf2002-12-16 20:18:38 +00001554static PyObject *
1555multiply_int_timedelta(PyObject *intobj, PyDateTime_Delta *delta)
1556{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001557 PyObject *pyus_in;
1558 PyObject *pyus_out;
1559 PyObject *result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001560
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001561 pyus_in = delta_to_microseconds(delta);
1562 if (pyus_in == NULL)
1563 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001564
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001565 pyus_out = PyNumber_Multiply(pyus_in, intobj);
1566 Py_DECREF(pyus_in);
1567 if (pyus_out == NULL)
1568 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001569
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001570 result = microseconds_to_delta(pyus_out);
1571 Py_DECREF(pyus_out);
1572 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001573}
1574
1575static PyObject *
Alexander Belopolsky1790bc42010-05-31 17:33:47 +00001576multiply_float_timedelta(PyObject *floatobj, PyDateTime_Delta *delta)
1577{
1578 PyObject *result = NULL;
1579 PyObject *pyus_in = NULL, *temp, *pyus_out;
1580 PyObject *ratio = NULL;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001581 _Py_IDENTIFIER(as_integer_ratio);
Alexander Belopolsky1790bc42010-05-31 17:33:47 +00001582
1583 pyus_in = delta_to_microseconds(delta);
1584 if (pyus_in == NULL)
1585 return NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001586 ratio = _PyObject_CallMethodId(floatobj, &PyId_as_integer_ratio, NULL);
Alexander Belopolsky1790bc42010-05-31 17:33:47 +00001587 if (ratio == NULL)
1588 goto error;
1589 temp = PyNumber_Multiply(pyus_in, PyTuple_GET_ITEM(ratio, 0));
1590 Py_DECREF(pyus_in);
1591 pyus_in = NULL;
1592 if (temp == NULL)
1593 goto error;
1594 pyus_out = divide_nearest(temp, PyTuple_GET_ITEM(ratio, 1));
1595 Py_DECREF(temp);
1596 if (pyus_out == NULL)
1597 goto error;
1598 result = microseconds_to_delta(pyus_out);
1599 Py_DECREF(pyus_out);
1600 error:
1601 Py_XDECREF(pyus_in);
1602 Py_XDECREF(ratio);
1603
1604 return result;
1605}
1606
1607static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00001608divide_timedelta_int(PyDateTime_Delta *delta, PyObject *intobj)
1609{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001610 PyObject *pyus_in;
1611 PyObject *pyus_out;
1612 PyObject *result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001613
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001614 pyus_in = delta_to_microseconds(delta);
1615 if (pyus_in == NULL)
1616 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001617
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001618 pyus_out = PyNumber_FloorDivide(pyus_in, intobj);
1619 Py_DECREF(pyus_in);
1620 if (pyus_out == NULL)
1621 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001622
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001623 result = microseconds_to_delta(pyus_out);
1624 Py_DECREF(pyus_out);
1625 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001626}
1627
1628static PyObject *
Mark Dickinson7c186e22010-04-20 22:32:49 +00001629divide_timedelta_timedelta(PyDateTime_Delta *left, PyDateTime_Delta *right)
1630{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001631 PyObject *pyus_left;
1632 PyObject *pyus_right;
1633 PyObject *result;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001634
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001635 pyus_left = delta_to_microseconds(left);
1636 if (pyus_left == NULL)
1637 return NULL;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001638
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001639 pyus_right = delta_to_microseconds(right);
1640 if (pyus_right == NULL) {
1641 Py_DECREF(pyus_left);
1642 return NULL;
1643 }
Mark Dickinson7c186e22010-04-20 22:32:49 +00001644
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001645 result = PyNumber_FloorDivide(pyus_left, pyus_right);
1646 Py_DECREF(pyus_left);
1647 Py_DECREF(pyus_right);
1648 return result;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001649}
1650
1651static PyObject *
1652truedivide_timedelta_timedelta(PyDateTime_Delta *left, PyDateTime_Delta *right)
1653{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001654 PyObject *pyus_left;
1655 PyObject *pyus_right;
1656 PyObject *result;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001657
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001658 pyus_left = delta_to_microseconds(left);
1659 if (pyus_left == NULL)
1660 return NULL;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001661
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001662 pyus_right = delta_to_microseconds(right);
1663 if (pyus_right == NULL) {
1664 Py_DECREF(pyus_left);
1665 return NULL;
1666 }
Mark Dickinson7c186e22010-04-20 22:32:49 +00001667
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001668 result = PyNumber_TrueDivide(pyus_left, pyus_right);
1669 Py_DECREF(pyus_left);
1670 Py_DECREF(pyus_right);
1671 return result;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001672}
1673
1674static PyObject *
Alexander Belopolsky1790bc42010-05-31 17:33:47 +00001675truedivide_timedelta_float(PyDateTime_Delta *delta, PyObject *f)
1676{
1677 PyObject *result = NULL;
1678 PyObject *pyus_in = NULL, *temp, *pyus_out;
1679 PyObject *ratio = NULL;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001680 _Py_IDENTIFIER(as_integer_ratio);
Alexander Belopolsky1790bc42010-05-31 17:33:47 +00001681
1682 pyus_in = delta_to_microseconds(delta);
1683 if (pyus_in == NULL)
1684 return NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001685 ratio = _PyObject_CallMethodId(f, &PyId_as_integer_ratio, NULL);
Alexander Belopolsky1790bc42010-05-31 17:33:47 +00001686 if (ratio == NULL)
1687 goto error;
1688 temp = PyNumber_Multiply(pyus_in, PyTuple_GET_ITEM(ratio, 1));
1689 Py_DECREF(pyus_in);
1690 pyus_in = NULL;
1691 if (temp == NULL)
1692 goto error;
1693 pyus_out = divide_nearest(temp, PyTuple_GET_ITEM(ratio, 0));
1694 Py_DECREF(temp);
1695 if (pyus_out == NULL)
1696 goto error;
1697 result = microseconds_to_delta(pyus_out);
1698 Py_DECREF(pyus_out);
1699 error:
1700 Py_XDECREF(pyus_in);
1701 Py_XDECREF(ratio);
1702
1703 return result;
1704}
1705
1706static PyObject *
1707truedivide_timedelta_int(PyDateTime_Delta *delta, PyObject *i)
1708{
1709 PyObject *result;
1710 PyObject *pyus_in, *pyus_out;
1711 pyus_in = delta_to_microseconds(delta);
1712 if (pyus_in == NULL)
1713 return NULL;
1714 pyus_out = divide_nearest(pyus_in, i);
1715 Py_DECREF(pyus_in);
1716 if (pyus_out == NULL)
1717 return NULL;
1718 result = microseconds_to_delta(pyus_out);
1719 Py_DECREF(pyus_out);
1720
1721 return result;
1722}
1723
1724static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00001725delta_add(PyObject *left, PyObject *right)
1726{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001727 PyObject *result = Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00001728
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001729 if (PyDelta_Check(left) && PyDelta_Check(right)) {
1730 /* delta + delta */
1731 /* The C-level additions can't overflow because of the
1732 * invariant bounds.
1733 */
1734 int days = GET_TD_DAYS(left) + GET_TD_DAYS(right);
1735 int seconds = GET_TD_SECONDS(left) + GET_TD_SECONDS(right);
1736 int microseconds = GET_TD_MICROSECONDS(left) +
1737 GET_TD_MICROSECONDS(right);
1738 result = new_delta(days, seconds, microseconds, 1);
1739 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001740
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001741 if (result == Py_NotImplemented)
1742 Py_INCREF(result);
1743 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001744}
1745
1746static PyObject *
1747delta_negative(PyDateTime_Delta *self)
1748{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001749 return new_delta(-GET_TD_DAYS(self),
1750 -GET_TD_SECONDS(self),
1751 -GET_TD_MICROSECONDS(self),
1752 1);
Tim Peters2a799bf2002-12-16 20:18:38 +00001753}
1754
1755static PyObject *
1756delta_positive(PyDateTime_Delta *self)
1757{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001758 /* Could optimize this (by returning self) if this isn't a
1759 * subclass -- but who uses unary + ? Approximately nobody.
1760 */
1761 return new_delta(GET_TD_DAYS(self),
1762 GET_TD_SECONDS(self),
1763 GET_TD_MICROSECONDS(self),
1764 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00001765}
1766
1767static PyObject *
1768delta_abs(PyDateTime_Delta *self)
1769{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001770 PyObject *result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001771
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001772 assert(GET_TD_MICROSECONDS(self) >= 0);
1773 assert(GET_TD_SECONDS(self) >= 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00001774
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001775 if (GET_TD_DAYS(self) < 0)
1776 result = delta_negative(self);
1777 else
1778 result = delta_positive(self);
Tim Peters2a799bf2002-12-16 20:18:38 +00001779
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001780 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001781}
1782
1783static PyObject *
1784delta_subtract(PyObject *left, PyObject *right)
1785{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001786 PyObject *result = Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00001787
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001788 if (PyDelta_Check(left) && PyDelta_Check(right)) {
1789 /* delta - delta */
Alexander Belopolskyb6f5ec72011-04-05 20:07:38 -04001790 /* The C-level additions can't overflow because of the
1791 * invariant bounds.
1792 */
1793 int days = GET_TD_DAYS(left) - GET_TD_DAYS(right);
1794 int seconds = GET_TD_SECONDS(left) - GET_TD_SECONDS(right);
1795 int microseconds = GET_TD_MICROSECONDS(left) -
1796 GET_TD_MICROSECONDS(right);
1797 result = new_delta(days, seconds, microseconds, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001798 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001799
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001800 if (result == Py_NotImplemented)
1801 Py_INCREF(result);
1802 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001803}
1804
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001805static int
1806delta_cmp(PyObject *self, PyObject *other)
1807{
1808 int diff = GET_TD_DAYS(self) - GET_TD_DAYS(other);
1809 if (diff == 0) {
1810 diff = GET_TD_SECONDS(self) - GET_TD_SECONDS(other);
1811 if (diff == 0)
1812 diff = GET_TD_MICROSECONDS(self) -
1813 GET_TD_MICROSECONDS(other);
1814 }
1815 return diff;
1816}
1817
Tim Peters2a799bf2002-12-16 20:18:38 +00001818static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00001819delta_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters2a799bf2002-12-16 20:18:38 +00001820{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001821 if (PyDelta_Check(other)) {
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001822 int diff = delta_cmp(self, other);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001823 return diff_to_bool(diff, op);
1824 }
1825 else {
Brian Curtindfc80e32011-08-10 20:28:54 -05001826 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001827 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001828}
1829
1830static PyObject *delta_getstate(PyDateTime_Delta *self);
1831
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001832static Py_hash_t
Tim Peters2a799bf2002-12-16 20:18:38 +00001833delta_hash(PyDateTime_Delta *self)
1834{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001835 if (self->hashcode == -1) {
1836 PyObject *temp = delta_getstate(self);
1837 if (temp != NULL) {
1838 self->hashcode = PyObject_Hash(temp);
1839 Py_DECREF(temp);
1840 }
1841 }
1842 return self->hashcode;
Tim Peters2a799bf2002-12-16 20:18:38 +00001843}
1844
1845static PyObject *
1846delta_multiply(PyObject *left, PyObject *right)
1847{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001848 PyObject *result = Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00001849
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001850 if (PyDelta_Check(left)) {
1851 /* delta * ??? */
1852 if (PyLong_Check(right))
1853 result = multiply_int_timedelta(right,
1854 (PyDateTime_Delta *) left);
Alexander Belopolsky1790bc42010-05-31 17:33:47 +00001855 else if (PyFloat_Check(right))
1856 result = multiply_float_timedelta(right,
1857 (PyDateTime_Delta *) left);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001858 }
1859 else if (PyLong_Check(left))
1860 result = multiply_int_timedelta(left,
Alexander Belopolsky1790bc42010-05-31 17:33:47 +00001861 (PyDateTime_Delta *) right);
1862 else if (PyFloat_Check(left))
1863 result = multiply_float_timedelta(left,
1864 (PyDateTime_Delta *) right);
Tim Peters2a799bf2002-12-16 20:18:38 +00001865
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001866 if (result == Py_NotImplemented)
1867 Py_INCREF(result);
1868 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001869}
1870
1871static PyObject *
1872delta_divide(PyObject *left, PyObject *right)
1873{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001874 PyObject *result = Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00001875
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001876 if (PyDelta_Check(left)) {
1877 /* delta * ??? */
1878 if (PyLong_Check(right))
1879 result = divide_timedelta_int(
1880 (PyDateTime_Delta *)left,
1881 right);
1882 else if (PyDelta_Check(right))
1883 result = divide_timedelta_timedelta(
1884 (PyDateTime_Delta *)left,
1885 (PyDateTime_Delta *)right);
1886 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001887
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001888 if (result == Py_NotImplemented)
1889 Py_INCREF(result);
1890 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001891}
1892
Mark Dickinson7c186e22010-04-20 22:32:49 +00001893static PyObject *
1894delta_truedivide(PyObject *left, PyObject *right)
1895{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001896 PyObject *result = Py_NotImplemented;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001897
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001898 if (PyDelta_Check(left)) {
1899 if (PyDelta_Check(right))
1900 result = truedivide_timedelta_timedelta(
1901 (PyDateTime_Delta *)left,
1902 (PyDateTime_Delta *)right);
Alexander Belopolsky1790bc42010-05-31 17:33:47 +00001903 else if (PyFloat_Check(right))
1904 result = truedivide_timedelta_float(
1905 (PyDateTime_Delta *)left, right);
1906 else if (PyLong_Check(right))
1907 result = truedivide_timedelta_int(
1908 (PyDateTime_Delta *)left, right);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001909 }
Mark Dickinson7c186e22010-04-20 22:32:49 +00001910
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001911 if (result == Py_NotImplemented)
1912 Py_INCREF(result);
1913 return result;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001914}
1915
1916static PyObject *
1917delta_remainder(PyObject *left, PyObject *right)
1918{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001919 PyObject *pyus_left;
1920 PyObject *pyus_right;
1921 PyObject *pyus_remainder;
1922 PyObject *remainder;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001923
Brian Curtindfc80e32011-08-10 20:28:54 -05001924 if (!PyDelta_Check(left) || !PyDelta_Check(right))
1925 Py_RETURN_NOTIMPLEMENTED;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001926
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001927 pyus_left = delta_to_microseconds((PyDateTime_Delta *)left);
1928 if (pyus_left == NULL)
1929 return NULL;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001930
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001931 pyus_right = delta_to_microseconds((PyDateTime_Delta *)right);
1932 if (pyus_right == NULL) {
1933 Py_DECREF(pyus_left);
1934 return NULL;
1935 }
Mark Dickinson7c186e22010-04-20 22:32:49 +00001936
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001937 pyus_remainder = PyNumber_Remainder(pyus_left, pyus_right);
1938 Py_DECREF(pyus_left);
1939 Py_DECREF(pyus_right);
1940 if (pyus_remainder == NULL)
1941 return NULL;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001942
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001943 remainder = microseconds_to_delta(pyus_remainder);
1944 Py_DECREF(pyus_remainder);
1945 if (remainder == NULL)
1946 return NULL;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001947
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001948 return remainder;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001949}
1950
1951static PyObject *
1952delta_divmod(PyObject *left, PyObject *right)
1953{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001954 PyObject *pyus_left;
1955 PyObject *pyus_right;
1956 PyObject *divmod;
1957 PyObject *delta;
1958 PyObject *result;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001959
Brian Curtindfc80e32011-08-10 20:28:54 -05001960 if (!PyDelta_Check(left) || !PyDelta_Check(right))
1961 Py_RETURN_NOTIMPLEMENTED;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001962
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001963 pyus_left = delta_to_microseconds((PyDateTime_Delta *)left);
1964 if (pyus_left == NULL)
1965 return NULL;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001966
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001967 pyus_right = delta_to_microseconds((PyDateTime_Delta *)right);
1968 if (pyus_right == NULL) {
1969 Py_DECREF(pyus_left);
1970 return NULL;
1971 }
Mark Dickinson7c186e22010-04-20 22:32:49 +00001972
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001973 divmod = PyNumber_Divmod(pyus_left, pyus_right);
1974 Py_DECREF(pyus_left);
1975 Py_DECREF(pyus_right);
1976 if (divmod == NULL)
1977 return NULL;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001978
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001979 assert(PyTuple_Size(divmod) == 2);
1980 delta = microseconds_to_delta(PyTuple_GET_ITEM(divmod, 1));
1981 if (delta == NULL) {
1982 Py_DECREF(divmod);
1983 return NULL;
1984 }
1985 result = PyTuple_Pack(2, PyTuple_GET_ITEM(divmod, 0), delta);
1986 Py_DECREF(delta);
1987 Py_DECREF(divmod);
1988 return result;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001989}
1990
Tim Peters2a799bf2002-12-16 20:18:38 +00001991/* Fold in the value of the tag ("seconds", "weeks", etc) component of a
1992 * timedelta constructor. sofar is the # of microseconds accounted for
1993 * so far, and there are factor microseconds per current unit, the number
1994 * of which is given by num. num * factor is added to sofar in a
1995 * numerically careful way, and that's the result. Any fractional
1996 * microseconds left over (this can happen if num is a float type) are
1997 * added into *leftover.
1998 * Note that there are many ways this can give an error (NULL) return.
1999 */
2000static PyObject *
2001accum(const char* tag, PyObject *sofar, PyObject *num, PyObject *factor,
2002 double *leftover)
2003{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002004 PyObject *prod;
2005 PyObject *sum;
Tim Peters2a799bf2002-12-16 20:18:38 +00002006
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002007 assert(num != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +00002008
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002009 if (PyLong_Check(num)) {
2010 prod = PyNumber_Multiply(num, factor);
2011 if (prod == NULL)
2012 return NULL;
2013 sum = PyNumber_Add(sofar, prod);
2014 Py_DECREF(prod);
2015 return sum;
2016 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002017
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002018 if (PyFloat_Check(num)) {
2019 double dnum;
2020 double fracpart;
2021 double intpart;
2022 PyObject *x;
2023 PyObject *y;
Tim Peters2a799bf2002-12-16 20:18:38 +00002024
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002025 /* The Plan: decompose num into an integer part and a
2026 * fractional part, num = intpart + fracpart.
2027 * Then num * factor ==
2028 * intpart * factor + fracpart * factor
2029 * and the LHS can be computed exactly in long arithmetic.
2030 * The RHS is again broken into an int part and frac part.
2031 * and the frac part is added into *leftover.
2032 */
2033 dnum = PyFloat_AsDouble(num);
2034 if (dnum == -1.0 && PyErr_Occurred())
2035 return NULL;
2036 fracpart = modf(dnum, &intpart);
2037 x = PyLong_FromDouble(intpart);
2038 if (x == NULL)
2039 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002040
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002041 prod = PyNumber_Multiply(x, factor);
2042 Py_DECREF(x);
2043 if (prod == NULL)
2044 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002045
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002046 sum = PyNumber_Add(sofar, prod);
2047 Py_DECREF(prod);
2048 if (sum == NULL)
2049 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002050
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002051 if (fracpart == 0.0)
2052 return sum;
2053 /* So far we've lost no information. Dealing with the
2054 * fractional part requires float arithmetic, and may
2055 * lose a little info.
2056 */
2057 assert(PyLong_Check(factor));
2058 dnum = PyLong_AsDouble(factor);
Tim Peters2a799bf2002-12-16 20:18:38 +00002059
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002060 dnum *= fracpart;
2061 fracpart = modf(dnum, &intpart);
2062 x = PyLong_FromDouble(intpart);
2063 if (x == NULL) {
2064 Py_DECREF(sum);
2065 return NULL;
2066 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002067
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002068 y = PyNumber_Add(sum, x);
2069 Py_DECREF(sum);
2070 Py_DECREF(x);
2071 *leftover += fracpart;
2072 return y;
2073 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002074
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002075 PyErr_Format(PyExc_TypeError,
2076 "unsupported type for timedelta %s component: %s",
2077 tag, Py_TYPE(num)->tp_name);
2078 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002079}
2080
2081static PyObject *
2082delta_new(PyTypeObject *type, PyObject *args, PyObject *kw)
2083{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002084 PyObject *self = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002085
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002086 /* Argument objects. */
2087 PyObject *day = NULL;
2088 PyObject *second = NULL;
2089 PyObject *us = NULL;
2090 PyObject *ms = NULL;
2091 PyObject *minute = NULL;
2092 PyObject *hour = NULL;
2093 PyObject *week = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002094
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002095 PyObject *x = NULL; /* running sum of microseconds */
2096 PyObject *y = NULL; /* temp sum of microseconds */
2097 double leftover_us = 0.0;
Tim Peters2a799bf2002-12-16 20:18:38 +00002098
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002099 static char *keywords[] = {
2100 "days", "seconds", "microseconds", "milliseconds",
2101 "minutes", "hours", "weeks", NULL
2102 };
Tim Peters2a799bf2002-12-16 20:18:38 +00002103
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002104 if (PyArg_ParseTupleAndKeywords(args, kw, "|OOOOOOO:__new__",
2105 keywords,
2106 &day, &second, &us,
2107 &ms, &minute, &hour, &week) == 0)
2108 goto Done;
Tim Peters2a799bf2002-12-16 20:18:38 +00002109
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002110 x = PyLong_FromLong(0);
2111 if (x == NULL)
2112 goto Done;
Tim Peters2a799bf2002-12-16 20:18:38 +00002113
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002114#define CLEANUP \
2115 Py_DECREF(x); \
2116 x = y; \
2117 if (x == NULL) \
2118 goto Done
Tim Peters2a799bf2002-12-16 20:18:38 +00002119
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002120 if (us) {
2121 y = accum("microseconds", x, us, us_per_us, &leftover_us);
2122 CLEANUP;
2123 }
2124 if (ms) {
2125 y = accum("milliseconds", x, ms, us_per_ms, &leftover_us);
2126 CLEANUP;
2127 }
2128 if (second) {
2129 y = accum("seconds", x, second, us_per_second, &leftover_us);
2130 CLEANUP;
2131 }
2132 if (minute) {
2133 y = accum("minutes", x, minute, us_per_minute, &leftover_us);
2134 CLEANUP;
2135 }
2136 if (hour) {
2137 y = accum("hours", x, hour, us_per_hour, &leftover_us);
2138 CLEANUP;
2139 }
2140 if (day) {
2141 y = accum("days", x, day, us_per_day, &leftover_us);
2142 CLEANUP;
2143 }
2144 if (week) {
2145 y = accum("weeks", x, week, us_per_week, &leftover_us);
2146 CLEANUP;
2147 }
2148 if (leftover_us) {
2149 /* Round to nearest whole # of us, and add into x. */
2150 PyObject *temp = PyLong_FromLong(round_to_long(leftover_us));
2151 if (temp == NULL) {
2152 Py_DECREF(x);
2153 goto Done;
2154 }
2155 y = PyNumber_Add(x, temp);
2156 Py_DECREF(temp);
2157 CLEANUP;
2158 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002159
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002160 self = microseconds_to_delta_ex(x, type);
2161 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00002162Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002163 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00002164
2165#undef CLEANUP
2166}
2167
2168static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00002169delta_bool(PyDateTime_Delta *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00002170{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002171 return (GET_TD_DAYS(self) != 0
2172 || GET_TD_SECONDS(self) != 0
2173 || GET_TD_MICROSECONDS(self) != 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00002174}
2175
2176static PyObject *
2177delta_repr(PyDateTime_Delta *self)
2178{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002179 if (GET_TD_MICROSECONDS(self) != 0)
2180 return PyUnicode_FromFormat("%s(%d, %d, %d)",
2181 Py_TYPE(self)->tp_name,
2182 GET_TD_DAYS(self),
2183 GET_TD_SECONDS(self),
2184 GET_TD_MICROSECONDS(self));
2185 if (GET_TD_SECONDS(self) != 0)
2186 return PyUnicode_FromFormat("%s(%d, %d)",
2187 Py_TYPE(self)->tp_name,
2188 GET_TD_DAYS(self),
2189 GET_TD_SECONDS(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002190
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002191 return PyUnicode_FromFormat("%s(%d)",
2192 Py_TYPE(self)->tp_name,
2193 GET_TD_DAYS(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002194}
2195
2196static PyObject *
2197delta_str(PyDateTime_Delta *self)
2198{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002199 int us = GET_TD_MICROSECONDS(self);
2200 int seconds = GET_TD_SECONDS(self);
2201 int minutes = divmod(seconds, 60, &seconds);
2202 int hours = divmod(minutes, 60, &minutes);
2203 int days = GET_TD_DAYS(self);
Tim Peters2a799bf2002-12-16 20:18:38 +00002204
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002205 if (days) {
2206 if (us)
2207 return PyUnicode_FromFormat("%d day%s, %d:%02d:%02d.%06d",
2208 days, (days == 1 || days == -1) ? "" : "s",
2209 hours, minutes, seconds, us);
2210 else
2211 return PyUnicode_FromFormat("%d day%s, %d:%02d:%02d",
2212 days, (days == 1 || days == -1) ? "" : "s",
2213 hours, minutes, seconds);
2214 } else {
2215 if (us)
2216 return PyUnicode_FromFormat("%d:%02d:%02d.%06d",
2217 hours, minutes, seconds, us);
2218 else
2219 return PyUnicode_FromFormat("%d:%02d:%02d",
2220 hours, minutes, seconds);
2221 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002222
Tim Peters2a799bf2002-12-16 20:18:38 +00002223}
2224
Tim Peters371935f2003-02-01 01:52:50 +00002225/* Pickle support, a simple use of __reduce__. */
2226
Tim Petersb57f8f02003-02-01 02:54:15 +00002227/* __getstate__ isn't exposed */
Tim Peters2a799bf2002-12-16 20:18:38 +00002228static PyObject *
2229delta_getstate(PyDateTime_Delta *self)
2230{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002231 return Py_BuildValue("iii", GET_TD_DAYS(self),
2232 GET_TD_SECONDS(self),
2233 GET_TD_MICROSECONDS(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002234}
2235
Tim Peters2a799bf2002-12-16 20:18:38 +00002236static PyObject *
Antoine Pitroube6859d2009-11-25 23:02:32 +00002237delta_total_seconds(PyObject *self)
2238{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002239 PyObject *total_seconds;
2240 PyObject *total_microseconds;
2241 PyObject *one_million;
Mark Dickinson0381e3f2010-05-08 14:35:02 +00002242
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002243 total_microseconds = delta_to_microseconds((PyDateTime_Delta *)self);
2244 if (total_microseconds == NULL)
2245 return NULL;
Mark Dickinson0381e3f2010-05-08 14:35:02 +00002246
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002247 one_million = PyLong_FromLong(1000000L);
2248 if (one_million == NULL) {
2249 Py_DECREF(total_microseconds);
2250 return NULL;
2251 }
Mark Dickinson0381e3f2010-05-08 14:35:02 +00002252
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002253 total_seconds = PyNumber_TrueDivide(total_microseconds, one_million);
Mark Dickinson0381e3f2010-05-08 14:35:02 +00002254
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002255 Py_DECREF(total_microseconds);
2256 Py_DECREF(one_million);
2257 return total_seconds;
Antoine Pitroube6859d2009-11-25 23:02:32 +00002258}
2259
2260static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002261delta_reduce(PyDateTime_Delta* self)
2262{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002263 return Py_BuildValue("ON", Py_TYPE(self), delta_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002264}
2265
2266#define OFFSET(field) offsetof(PyDateTime_Delta, field)
2267
2268static PyMemberDef delta_members[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002269
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002270 {"days", T_INT, OFFSET(days), READONLY,
2271 PyDoc_STR("Number of days.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002272
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002273 {"seconds", T_INT, OFFSET(seconds), READONLY,
2274 PyDoc_STR("Number of seconds (>= 0 and less than 1 day).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002275
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002276 {"microseconds", T_INT, OFFSET(microseconds), READONLY,
2277 PyDoc_STR("Number of microseconds (>= 0 and less than 1 second).")},
2278 {NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00002279};
2280
2281static PyMethodDef delta_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002282 {"total_seconds", (PyCFunction)delta_total_seconds, METH_NOARGS,
2283 PyDoc_STR("Total seconds in the duration.")},
Antoine Pitroube6859d2009-11-25 23:02:32 +00002284
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002285 {"__reduce__", (PyCFunction)delta_reduce, METH_NOARGS,
2286 PyDoc_STR("__reduce__() -> (cls, state)")},
Guido van Rossum177e41a2003-01-30 22:06:23 +00002287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002288 {NULL, NULL},
Tim Peters2a799bf2002-12-16 20:18:38 +00002289};
2290
2291static char delta_doc[] =
2292PyDoc_STR("Difference between two datetime values.");
2293
2294static PyNumberMethods delta_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002295 delta_add, /* nb_add */
2296 delta_subtract, /* nb_subtract */
2297 delta_multiply, /* nb_multiply */
2298 delta_remainder, /* nb_remainder */
2299 delta_divmod, /* nb_divmod */
2300 0, /* nb_power */
2301 (unaryfunc)delta_negative, /* nb_negative */
2302 (unaryfunc)delta_positive, /* nb_positive */
2303 (unaryfunc)delta_abs, /* nb_absolute */
2304 (inquiry)delta_bool, /* nb_bool */
2305 0, /*nb_invert*/
2306 0, /*nb_lshift*/
2307 0, /*nb_rshift*/
2308 0, /*nb_and*/
2309 0, /*nb_xor*/
2310 0, /*nb_or*/
2311 0, /*nb_int*/
2312 0, /*nb_reserved*/
2313 0, /*nb_float*/
2314 0, /*nb_inplace_add*/
2315 0, /*nb_inplace_subtract*/
2316 0, /*nb_inplace_multiply*/
2317 0, /*nb_inplace_remainder*/
2318 0, /*nb_inplace_power*/
2319 0, /*nb_inplace_lshift*/
2320 0, /*nb_inplace_rshift*/
2321 0, /*nb_inplace_and*/
2322 0, /*nb_inplace_xor*/
2323 0, /*nb_inplace_or*/
2324 delta_divide, /* nb_floor_divide */
2325 delta_truedivide, /* nb_true_divide */
2326 0, /* nb_inplace_floor_divide */
2327 0, /* nb_inplace_true_divide */
Tim Peters2a799bf2002-12-16 20:18:38 +00002328};
2329
2330static PyTypeObject PyDateTime_DeltaType = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002331 PyVarObject_HEAD_INIT(NULL, 0)
2332 "datetime.timedelta", /* tp_name */
2333 sizeof(PyDateTime_Delta), /* tp_basicsize */
2334 0, /* tp_itemsize */
2335 0, /* tp_dealloc */
2336 0, /* tp_print */
2337 0, /* tp_getattr */
2338 0, /* tp_setattr */
2339 0, /* tp_reserved */
2340 (reprfunc)delta_repr, /* tp_repr */
2341 &delta_as_number, /* tp_as_number */
2342 0, /* tp_as_sequence */
2343 0, /* tp_as_mapping */
2344 (hashfunc)delta_hash, /* tp_hash */
2345 0, /* tp_call */
2346 (reprfunc)delta_str, /* tp_str */
2347 PyObject_GenericGetAttr, /* tp_getattro */
2348 0, /* tp_setattro */
2349 0, /* tp_as_buffer */
2350 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
2351 delta_doc, /* tp_doc */
2352 0, /* tp_traverse */
2353 0, /* tp_clear */
2354 delta_richcompare, /* tp_richcompare */
2355 0, /* tp_weaklistoffset */
2356 0, /* tp_iter */
2357 0, /* tp_iternext */
2358 delta_methods, /* tp_methods */
2359 delta_members, /* tp_members */
2360 0, /* tp_getset */
2361 0, /* tp_base */
2362 0, /* tp_dict */
2363 0, /* tp_descr_get */
2364 0, /* tp_descr_set */
2365 0, /* tp_dictoffset */
2366 0, /* tp_init */
2367 0, /* tp_alloc */
2368 delta_new, /* tp_new */
2369 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00002370};
2371
2372/*
2373 * PyDateTime_Date implementation.
2374 */
2375
2376/* Accessor properties. */
2377
2378static PyObject *
2379date_year(PyDateTime_Date *self, void *unused)
2380{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002381 return PyLong_FromLong(GET_YEAR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002382}
2383
2384static PyObject *
2385date_month(PyDateTime_Date *self, void *unused)
2386{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002387 return PyLong_FromLong(GET_MONTH(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002388}
2389
2390static PyObject *
2391date_day(PyDateTime_Date *self, void *unused)
2392{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002393 return PyLong_FromLong(GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002394}
2395
2396static PyGetSetDef date_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002397 {"year", (getter)date_year},
2398 {"month", (getter)date_month},
2399 {"day", (getter)date_day},
2400 {NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00002401};
2402
2403/* Constructors. */
2404
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00002405static char *date_kws[] = {"year", "month", "day", NULL};
Tim Peters12bf3392002-12-24 05:41:27 +00002406
Tim Peters2a799bf2002-12-16 20:18:38 +00002407static PyObject *
2408date_new(PyTypeObject *type, PyObject *args, PyObject *kw)
2409{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002410 PyObject *self = NULL;
2411 PyObject *state;
2412 int year;
2413 int month;
2414 int day;
Tim Peters2a799bf2002-12-16 20:18:38 +00002415
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002416 /* Check for invocation from pickle with __getstate__ state */
2417 if (PyTuple_GET_SIZE(args) == 1 &&
2418 PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) &&
2419 PyBytes_GET_SIZE(state) == _PyDateTime_DATE_DATASIZE &&
2420 MONTH_IS_SANE(PyBytes_AS_STRING(state)[2]))
2421 {
2422 PyDateTime_Date *me;
Tim Peters70533e22003-02-01 04:40:04 +00002423
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002424 me = (PyDateTime_Date *) (type->tp_alloc(type, 0));
2425 if (me != NULL) {
2426 char *pdata = PyBytes_AS_STRING(state);
2427 memcpy(me->data, pdata, _PyDateTime_DATE_DATASIZE);
2428 me->hashcode = -1;
2429 }
2430 return (PyObject *)me;
2431 }
Guido van Rossum177e41a2003-01-30 22:06:23 +00002432
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002433 if (PyArg_ParseTupleAndKeywords(args, kw, "iii", date_kws,
2434 &year, &month, &day)) {
2435 if (check_date_args(year, month, day) < 0)
2436 return NULL;
2437 self = new_date_ex(year, month, day, type);
2438 }
2439 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00002440}
2441
2442/* Return new date from localtime(t). */
2443static PyObject *
Tim Peters1b6f7a92004-06-20 02:50:16 +00002444date_local_from_time_t(PyObject *cls, double ts)
Tim Peters2a799bf2002-12-16 20:18:38 +00002445{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002446 struct tm *tm;
2447 time_t t;
2448 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002449
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002450 t = _PyTime_DoubleToTimet(ts);
2451 if (t == (time_t)-1 && PyErr_Occurred())
2452 return NULL;
2453 tm = localtime(&t);
2454 if (tm)
2455 result = PyObject_CallFunction(cls, "iii",
2456 tm->tm_year + 1900,
2457 tm->tm_mon + 1,
2458 tm->tm_mday);
2459 else
2460 PyErr_SetString(PyExc_ValueError,
2461 "timestamp out of range for "
2462 "platform localtime() function");
2463 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002464}
2465
2466/* Return new date from current time.
2467 * We say this is equivalent to fromtimestamp(time.time()), and the
2468 * only way to be sure of that is to *call* time.time(). That's not
2469 * generally the same as calling C's time.
2470 */
2471static PyObject *
2472date_today(PyObject *cls, PyObject *dummy)
2473{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002474 PyObject *time;
2475 PyObject *result;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002476 _Py_IDENTIFIER(fromtimestamp);
Tim Peters2a799bf2002-12-16 20:18:38 +00002477
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002478 time = time_time();
2479 if (time == NULL)
2480 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002481
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002482 /* Note well: today() is a class method, so this may not call
2483 * date.fromtimestamp. For example, it may call
2484 * datetime.fromtimestamp. That's why we need all the accuracy
2485 * time.time() delivers; if someone were gonzo about optimization,
2486 * date.today() could get away with plain C time().
2487 */
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002488 result = _PyObject_CallMethodId(cls, &PyId_fromtimestamp, "O", time);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002489 Py_DECREF(time);
2490 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002491}
2492
2493/* Return new date from given timestamp (Python timestamp -- a double). */
2494static PyObject *
2495date_fromtimestamp(PyObject *cls, PyObject *args)
2496{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002497 double timestamp;
2498 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002499
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002500 if (PyArg_ParseTuple(args, "d:fromtimestamp", &timestamp))
2501 result = date_local_from_time_t(cls, timestamp);
2502 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002503}
2504
2505/* Return new date from proleptic Gregorian ordinal. Raises ValueError if
2506 * the ordinal is out of range.
2507 */
2508static PyObject *
2509date_fromordinal(PyObject *cls, PyObject *args)
2510{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002511 PyObject *result = NULL;
2512 int ordinal;
Tim Peters2a799bf2002-12-16 20:18:38 +00002513
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002514 if (PyArg_ParseTuple(args, "i:fromordinal", &ordinal)) {
2515 int year;
2516 int month;
2517 int day;
Tim Peters2a799bf2002-12-16 20:18:38 +00002518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002519 if (ordinal < 1)
2520 PyErr_SetString(PyExc_ValueError, "ordinal must be "
2521 ">= 1");
2522 else {
2523 ord_to_ymd(ordinal, &year, &month, &day);
2524 result = PyObject_CallFunction(cls, "iii",
2525 year, month, day);
2526 }
2527 }
2528 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002529}
2530
2531/*
2532 * Date arithmetic.
2533 */
2534
2535/* date + timedelta -> date. If arg negate is true, subtract the timedelta
2536 * instead.
2537 */
2538static PyObject *
2539add_date_timedelta(PyDateTime_Date *date, PyDateTime_Delta *delta, int negate)
2540{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002541 PyObject *result = NULL;
2542 int year = GET_YEAR(date);
2543 int month = GET_MONTH(date);
2544 int deltadays = GET_TD_DAYS(delta);
2545 /* C-level overflow is impossible because |deltadays| < 1e9. */
2546 int day = GET_DAY(date) + (negate ? -deltadays : deltadays);
Tim Peters2a799bf2002-12-16 20:18:38 +00002547
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002548 if (normalize_date(&year, &month, &day) >= 0)
2549 result = new_date(year, month, day);
2550 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002551}
2552
2553static PyObject *
2554date_add(PyObject *left, PyObject *right)
2555{
Brian Curtindfc80e32011-08-10 20:28:54 -05002556 if (PyDateTime_Check(left) || PyDateTime_Check(right))
2557 Py_RETURN_NOTIMPLEMENTED;
2558
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002559 if (PyDate_Check(left)) {
2560 /* date + ??? */
2561 if (PyDelta_Check(right))
2562 /* date + delta */
2563 return add_date_timedelta((PyDateTime_Date *) left,
2564 (PyDateTime_Delta *) right,
2565 0);
2566 }
2567 else {
2568 /* ??? + date
2569 * 'right' must be one of us, or we wouldn't have been called
2570 */
2571 if (PyDelta_Check(left))
2572 /* delta + date */
2573 return add_date_timedelta((PyDateTime_Date *) right,
2574 (PyDateTime_Delta *) left,
2575 0);
2576 }
Brian Curtindfc80e32011-08-10 20:28:54 -05002577 Py_RETURN_NOTIMPLEMENTED;
Tim Peters2a799bf2002-12-16 20:18:38 +00002578}
2579
2580static PyObject *
2581date_subtract(PyObject *left, PyObject *right)
2582{
Brian Curtindfc80e32011-08-10 20:28:54 -05002583 if (PyDateTime_Check(left) || PyDateTime_Check(right))
2584 Py_RETURN_NOTIMPLEMENTED;
2585
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002586 if (PyDate_Check(left)) {
2587 if (PyDate_Check(right)) {
2588 /* date - date */
2589 int left_ord = ymd_to_ord(GET_YEAR(left),
2590 GET_MONTH(left),
2591 GET_DAY(left));
2592 int right_ord = ymd_to_ord(GET_YEAR(right),
2593 GET_MONTH(right),
2594 GET_DAY(right));
2595 return new_delta(left_ord - right_ord, 0, 0, 0);
2596 }
2597 if (PyDelta_Check(right)) {
2598 /* date - delta */
2599 return add_date_timedelta((PyDateTime_Date *) left,
2600 (PyDateTime_Delta *) right,
2601 1);
2602 }
2603 }
Brian Curtindfc80e32011-08-10 20:28:54 -05002604 Py_RETURN_NOTIMPLEMENTED;
Tim Peters2a799bf2002-12-16 20:18:38 +00002605}
2606
2607
2608/* Various ways to turn a date into a string. */
2609
2610static PyObject *
2611date_repr(PyDateTime_Date *self)
2612{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002613 return PyUnicode_FromFormat("%s(%d, %d, %d)",
2614 Py_TYPE(self)->tp_name,
2615 GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002616}
2617
2618static PyObject *
2619date_isoformat(PyDateTime_Date *self)
2620{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002621 return PyUnicode_FromFormat("%04d-%02d-%02d",
2622 GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002623}
2624
Tim Peterse2df5ff2003-05-02 18:39:55 +00002625/* str() calls the appropriate isoformat() method. */
Tim Peters2a799bf2002-12-16 20:18:38 +00002626static PyObject *
2627date_str(PyDateTime_Date *self)
2628{
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002629 _Py_IDENTIFIER(isoformat);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002630
2631 return _PyObject_CallMethodId((PyObject *)self, &PyId_isoformat, "()");
Tim Peters2a799bf2002-12-16 20:18:38 +00002632}
2633
2634
2635static PyObject *
2636date_ctime(PyDateTime_Date *self)
2637{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002638 return format_ctime(self, 0, 0, 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00002639}
2640
2641static PyObject *
2642date_strftime(PyDateTime_Date *self, PyObject *args, PyObject *kw)
2643{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002644 /* This method can be inherited, and needs to call the
2645 * timetuple() method appropriate to self's class.
2646 */
2647 PyObject *result;
2648 PyObject *tuple;
2649 PyObject *format;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002650 _Py_IDENTIFIER(timetuple);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002651 static char *keywords[] = {"format", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00002652
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002653 if (! PyArg_ParseTupleAndKeywords(args, kw, "U:strftime", keywords,
2654 &format))
2655 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002656
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002657 tuple = _PyObject_CallMethodId((PyObject *)self, &PyId_timetuple, "()");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002658 if (tuple == NULL)
2659 return NULL;
2660 result = wrap_strftime((PyObject *)self, format, tuple,
2661 (PyObject *)self);
2662 Py_DECREF(tuple);
2663 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002664}
2665
Eric Smith1ba31142007-09-11 18:06:02 +00002666static PyObject *
2667date_format(PyDateTime_Date *self, PyObject *args)
2668{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002669 PyObject *format;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002670 _Py_IDENTIFIER(strftime);
Eric Smith1ba31142007-09-11 18:06:02 +00002671
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002672 if (!PyArg_ParseTuple(args, "U:__format__", &format))
2673 return NULL;
Eric Smith1ba31142007-09-11 18:06:02 +00002674
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002675 /* if the format is zero length, return str(self) */
Victor Stinner9e30aa52011-11-21 02:49:52 +01002676 if (PyUnicode_GetLength(format) == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002677 return PyObject_Str((PyObject *)self);
Eric Smith1ba31142007-09-11 18:06:02 +00002678
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002679 return _PyObject_CallMethodId((PyObject *)self, &PyId_strftime, "O", format);
Eric Smith1ba31142007-09-11 18:06:02 +00002680}
2681
Tim Peters2a799bf2002-12-16 20:18:38 +00002682/* ISO methods. */
2683
2684static PyObject *
2685date_isoweekday(PyDateTime_Date *self)
2686{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002687 int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002688
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002689 return PyLong_FromLong(dow + 1);
Tim Peters2a799bf2002-12-16 20:18:38 +00002690}
2691
2692static PyObject *
2693date_isocalendar(PyDateTime_Date *self)
2694{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002695 int year = GET_YEAR(self);
2696 int week1_monday = iso_week1_monday(year);
2697 int today = ymd_to_ord(year, GET_MONTH(self), GET_DAY(self));
2698 int week;
2699 int day;
Tim Peters2a799bf2002-12-16 20:18:38 +00002700
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002701 week = divmod(today - week1_monday, 7, &day);
2702 if (week < 0) {
2703 --year;
2704 week1_monday = iso_week1_monday(year);
2705 week = divmod(today - week1_monday, 7, &day);
2706 }
2707 else if (week >= 52 && today >= iso_week1_monday(year + 1)) {
2708 ++year;
2709 week = 0;
2710 }
2711 return Py_BuildValue("iii", year, week + 1, day + 1);
Tim Peters2a799bf2002-12-16 20:18:38 +00002712}
2713
2714/* Miscellaneous methods. */
2715
Tim Peters2a799bf2002-12-16 20:18:38 +00002716static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00002717date_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters2a799bf2002-12-16 20:18:38 +00002718{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002719 if (PyDate_Check(other)) {
2720 int diff = memcmp(((PyDateTime_Date *)self)->data,
2721 ((PyDateTime_Date *)other)->data,
2722 _PyDateTime_DATE_DATASIZE);
2723 return diff_to_bool(diff, op);
2724 }
Brian Curtindfc80e32011-08-10 20:28:54 -05002725 else
2726 Py_RETURN_NOTIMPLEMENTED;
Tim Peters2a799bf2002-12-16 20:18:38 +00002727}
2728
2729static PyObject *
2730date_timetuple(PyDateTime_Date *self)
2731{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002732 return build_struct_time(GET_YEAR(self),
2733 GET_MONTH(self),
2734 GET_DAY(self),
2735 0, 0, 0, -1);
Tim Peters2a799bf2002-12-16 20:18:38 +00002736}
2737
Tim Peters12bf3392002-12-24 05:41:27 +00002738static PyObject *
2739date_replace(PyDateTime_Date *self, PyObject *args, PyObject *kw)
2740{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002741 PyObject *clone;
2742 PyObject *tuple;
2743 int year = GET_YEAR(self);
2744 int month = GET_MONTH(self);
2745 int day = GET_DAY(self);
Tim Peters12bf3392002-12-24 05:41:27 +00002746
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002747 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iii:replace", date_kws,
2748 &year, &month, &day))
2749 return NULL;
2750 tuple = Py_BuildValue("iii", year, month, day);
2751 if (tuple == NULL)
2752 return NULL;
2753 clone = date_new(Py_TYPE(self), tuple, NULL);
2754 Py_DECREF(tuple);
2755 return clone;
Tim Peters12bf3392002-12-24 05:41:27 +00002756}
2757
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002758static Py_hash_t
Guido van Rossumfd53fd62007-08-24 04:05:13 +00002759generic_hash(unsigned char *data, int len)
2760{
Gregory P. Smith5831bd22012-01-14 14:31:13 -08002761 return _Py_HashBytes(data, len);
Guido van Rossumfd53fd62007-08-24 04:05:13 +00002762}
2763
2764
2765static PyObject *date_getstate(PyDateTime_Date *self);
Tim Peters2a799bf2002-12-16 20:18:38 +00002766
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002767static Py_hash_t
Tim Peters2a799bf2002-12-16 20:18:38 +00002768date_hash(PyDateTime_Date *self)
2769{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002770 if (self->hashcode == -1)
2771 self->hashcode = generic_hash(
2772 (unsigned char *)self->data, _PyDateTime_DATE_DATASIZE);
Guido van Rossum254348e2007-11-21 19:29:53 +00002773
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002774 return self->hashcode;
Tim Peters2a799bf2002-12-16 20:18:38 +00002775}
2776
2777static PyObject *
2778date_toordinal(PyDateTime_Date *self)
2779{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002780 return PyLong_FromLong(ymd_to_ord(GET_YEAR(self), GET_MONTH(self),
2781 GET_DAY(self)));
Tim Peters2a799bf2002-12-16 20:18:38 +00002782}
2783
2784static PyObject *
2785date_weekday(PyDateTime_Date *self)
2786{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002787 int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002788
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002789 return PyLong_FromLong(dow);
Tim Peters2a799bf2002-12-16 20:18:38 +00002790}
2791
Tim Peters371935f2003-02-01 01:52:50 +00002792/* Pickle support, a simple use of __reduce__. */
Tim Peters2a799bf2002-12-16 20:18:38 +00002793
Tim Petersb57f8f02003-02-01 02:54:15 +00002794/* __getstate__ isn't exposed */
Tim Peters2a799bf2002-12-16 20:18:38 +00002795static PyObject *
Guido van Rossumfd53fd62007-08-24 04:05:13 +00002796date_getstate(PyDateTime_Date *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00002797{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002798 PyObject* field;
2799 field = PyBytes_FromStringAndSize((char*)self->data,
2800 _PyDateTime_DATE_DATASIZE);
2801 return Py_BuildValue("(N)", field);
Tim Peters2a799bf2002-12-16 20:18:38 +00002802}
2803
2804static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00002805date_reduce(PyDateTime_Date *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00002806{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002807 return Py_BuildValue("(ON)", Py_TYPE(self), date_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002808}
2809
2810static PyMethodDef date_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002811
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002812 /* Class methods: */
Guido van Rossum177e41a2003-01-30 22:06:23 +00002813
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002814 {"fromtimestamp", (PyCFunction)date_fromtimestamp, METH_VARARGS |
2815 METH_CLASS,
2816 PyDoc_STR("timestamp -> local date from a POSIX timestamp (like "
2817 "time.time()).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002818
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002819 {"fromordinal", (PyCFunction)date_fromordinal, METH_VARARGS |
2820 METH_CLASS,
2821 PyDoc_STR("int -> date corresponding to a proleptic Gregorian "
2822 "ordinal.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002823
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002824 {"today", (PyCFunction)date_today, METH_NOARGS | METH_CLASS,
2825 PyDoc_STR("Current date or datetime: same as "
2826 "self.__class__.fromtimestamp(time.time()).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002827
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002828 /* Instance methods: */
Tim Peters2a799bf2002-12-16 20:18:38 +00002829
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002830 {"ctime", (PyCFunction)date_ctime, METH_NOARGS,
2831 PyDoc_STR("Return ctime() style string.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002832
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002833 {"strftime", (PyCFunction)date_strftime, METH_VARARGS | METH_KEYWORDS,
2834 PyDoc_STR("format -> strftime() style string.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002835
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002836 {"__format__", (PyCFunction)date_format, METH_VARARGS,
2837 PyDoc_STR("Formats self with strftime.")},
Eric Smith1ba31142007-09-11 18:06:02 +00002838
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002839 {"timetuple", (PyCFunction)date_timetuple, METH_NOARGS,
2840 PyDoc_STR("Return time tuple, compatible with time.localtime().")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002841
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002842 {"isocalendar", (PyCFunction)date_isocalendar, METH_NOARGS,
2843 PyDoc_STR("Return a 3-tuple containing ISO year, week number, and "
2844 "weekday.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002845
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002846 {"isoformat", (PyCFunction)date_isoformat, METH_NOARGS,
2847 PyDoc_STR("Return string in ISO 8601 format, YYYY-MM-DD.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002848
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002849 {"isoweekday", (PyCFunction)date_isoweekday, METH_NOARGS,
2850 PyDoc_STR("Return the day of the week represented by the date.\n"
2851 "Monday == 1 ... Sunday == 7")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002852
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002853 {"toordinal", (PyCFunction)date_toordinal, METH_NOARGS,
2854 PyDoc_STR("Return proleptic Gregorian ordinal. January 1 of year "
2855 "1 is day 1.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002856
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002857 {"weekday", (PyCFunction)date_weekday, METH_NOARGS,
2858 PyDoc_STR("Return the day of the week represented by the date.\n"
2859 "Monday == 0 ... Sunday == 6")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002860
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002861 {"replace", (PyCFunction)date_replace, METH_VARARGS | METH_KEYWORDS,
2862 PyDoc_STR("Return date with new specified fields.")},
Tim Peters12bf3392002-12-24 05:41:27 +00002863
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002864 {"__reduce__", (PyCFunction)date_reduce, METH_NOARGS,
2865 PyDoc_STR("__reduce__() -> (cls, state)")},
Guido van Rossum177e41a2003-01-30 22:06:23 +00002866
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002867 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00002868};
2869
2870static char date_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00002871PyDoc_STR("date(year, month, day) --> date object");
Tim Peters2a799bf2002-12-16 20:18:38 +00002872
2873static PyNumberMethods date_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002874 date_add, /* nb_add */
2875 date_subtract, /* nb_subtract */
2876 0, /* nb_multiply */
2877 0, /* nb_remainder */
2878 0, /* nb_divmod */
2879 0, /* nb_power */
2880 0, /* nb_negative */
2881 0, /* nb_positive */
2882 0, /* nb_absolute */
2883 0, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00002884};
2885
2886static PyTypeObject PyDateTime_DateType = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002887 PyVarObject_HEAD_INIT(NULL, 0)
2888 "datetime.date", /* tp_name */
2889 sizeof(PyDateTime_Date), /* tp_basicsize */
2890 0, /* tp_itemsize */
2891 0, /* tp_dealloc */
2892 0, /* tp_print */
2893 0, /* tp_getattr */
2894 0, /* tp_setattr */
2895 0, /* tp_reserved */
2896 (reprfunc)date_repr, /* tp_repr */
2897 &date_as_number, /* tp_as_number */
2898 0, /* tp_as_sequence */
2899 0, /* tp_as_mapping */
2900 (hashfunc)date_hash, /* tp_hash */
2901 0, /* tp_call */
2902 (reprfunc)date_str, /* tp_str */
2903 PyObject_GenericGetAttr, /* tp_getattro */
2904 0, /* tp_setattro */
2905 0, /* tp_as_buffer */
2906 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
2907 date_doc, /* tp_doc */
2908 0, /* tp_traverse */
2909 0, /* tp_clear */
2910 date_richcompare, /* tp_richcompare */
2911 0, /* tp_weaklistoffset */
2912 0, /* tp_iter */
2913 0, /* tp_iternext */
2914 date_methods, /* tp_methods */
2915 0, /* tp_members */
2916 date_getset, /* tp_getset */
2917 0, /* tp_base */
2918 0, /* tp_dict */
2919 0, /* tp_descr_get */
2920 0, /* tp_descr_set */
2921 0, /* tp_dictoffset */
2922 0, /* tp_init */
2923 0, /* tp_alloc */
2924 date_new, /* tp_new */
2925 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00002926};
2927
2928/*
Tim Peters2a799bf2002-12-16 20:18:38 +00002929 * PyDateTime_TZInfo implementation.
2930 */
2931
2932/* This is a pure abstract base class, so doesn't do anything beyond
2933 * raising NotImplemented exceptions. Real tzinfo classes need
2934 * to derive from this. This is mostly for clarity, and for efficiency in
Tim Petersa9bc1682003-01-11 03:39:11 +00002935 * datetime and time constructors (their tzinfo arguments need to
Tim Peters2a799bf2002-12-16 20:18:38 +00002936 * be subclasses of this tzinfo class, which is easy and quick to check).
2937 *
2938 * Note: For reasons having to do with pickling of subclasses, we have
2939 * to allow tzinfo objects to be instantiated. This wasn't an issue
2940 * in the Python implementation (__init__() could raise NotImplementedError
2941 * there without ill effect), but doing so in the C implementation hit a
2942 * brick wall.
2943 */
2944
2945static PyObject *
2946tzinfo_nogo(const char* methodname)
2947{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002948 PyErr_Format(PyExc_NotImplementedError,
2949 "a tzinfo subclass must implement %s()",
2950 methodname);
2951 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002952}
2953
2954/* Methods. A subclass must implement these. */
2955
Tim Peters52dcce22003-01-23 16:36:11 +00002956static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002957tzinfo_tzname(PyDateTime_TZInfo *self, PyObject *dt)
2958{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002959 return tzinfo_nogo("tzname");
Tim Peters2a799bf2002-12-16 20:18:38 +00002960}
2961
Tim Peters52dcce22003-01-23 16:36:11 +00002962static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002963tzinfo_utcoffset(PyDateTime_TZInfo *self, PyObject *dt)
2964{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002965 return tzinfo_nogo("utcoffset");
Tim Peters2a799bf2002-12-16 20:18:38 +00002966}
2967
Tim Peters52dcce22003-01-23 16:36:11 +00002968static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002969tzinfo_dst(PyDateTime_TZInfo *self, PyObject *dt)
2970{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002971 return tzinfo_nogo("dst");
Tim Peters2a799bf2002-12-16 20:18:38 +00002972}
2973
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00002974
2975static PyObject *add_datetime_timedelta(PyDateTime_DateTime *date,
2976 PyDateTime_Delta *delta,
2977 int factor);
2978static PyObject *datetime_utcoffset(PyObject *self, PyObject *);
2979static PyObject *datetime_dst(PyObject *self, PyObject *);
2980
Tim Peters52dcce22003-01-23 16:36:11 +00002981static PyObject *
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00002982tzinfo_fromutc(PyDateTime_TZInfo *self, PyObject *dt)
Tim Peters52dcce22003-01-23 16:36:11 +00002983{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00002984 PyObject *result = NULL;
2985 PyObject *off = NULL, *dst = NULL;
2986 PyDateTime_Delta *delta = NULL;
Tim Peters52dcce22003-01-23 16:36:11 +00002987
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00002988 if (!PyDateTime_Check(dt)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002989 PyErr_SetString(PyExc_TypeError,
2990 "fromutc: argument must be a datetime");
2991 return NULL;
2992 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00002993 if (GET_DT_TZINFO(dt) != (PyObject *)self) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002994 PyErr_SetString(PyExc_ValueError, "fromutc: dt.tzinfo "
2995 "is not self");
2996 return NULL;
2997 }
Tim Peters52dcce22003-01-23 16:36:11 +00002998
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00002999 off = datetime_utcoffset(dt, NULL);
3000 if (off == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003001 return NULL;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003002 if (off == Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003003 PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
3004 "utcoffset() result required");
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003005 goto Fail;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003006 }
Tim Peters52dcce22003-01-23 16:36:11 +00003007
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003008 dst = datetime_dst(dt, NULL);
3009 if (dst == NULL)
3010 goto Fail;
3011 if (dst == Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003012 PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
3013 "dst() result required");
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003014 goto Fail;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003015 }
Tim Peters52dcce22003-01-23 16:36:11 +00003016
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003017 delta = (PyDateTime_Delta *)delta_subtract(off, dst);
3018 if (delta == NULL)
3019 goto Fail;
3020 result = add_datetime_timedelta((PyDateTime_DateTime *)dt, delta, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003021 if (result == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003022 goto Fail;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003023
3024 Py_DECREF(dst);
3025 dst = call_dst(GET_DT_TZINFO(dt), result);
3026 if (dst == NULL)
3027 goto Fail;
3028 if (dst == Py_None)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003029 goto Inconsistent;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003030 if (delta_bool(delta) != 0) {
3031 PyObject *temp = result;
3032 result = add_datetime_timedelta((PyDateTime_DateTime *)result,
3033 (PyDateTime_Delta *)dst, 1);
3034 Py_DECREF(temp);
3035 if (result == NULL)
3036 goto Fail;
3037 }
3038 Py_DECREF(delta);
3039 Py_DECREF(dst);
3040 Py_DECREF(off);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003041 return result;
Tim Peters52dcce22003-01-23 16:36:11 +00003042
3043Inconsistent:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003044 PyErr_SetString(PyExc_ValueError, "fromutc: tz.dst() gave"
3045 "inconsistent results; cannot convert");
Tim Peters52dcce22003-01-23 16:36:11 +00003046
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003047 /* fall thru to failure */
Tim Peters52dcce22003-01-23 16:36:11 +00003048Fail:
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003049 Py_XDECREF(off);
3050 Py_XDECREF(dst);
3051 Py_XDECREF(delta);
3052 Py_XDECREF(result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003053 return NULL;
Tim Peters52dcce22003-01-23 16:36:11 +00003054}
3055
Tim Peters2a799bf2002-12-16 20:18:38 +00003056/*
3057 * Pickle support. This is solely so that tzinfo subclasses can use
Guido van Rossum177e41a2003-01-30 22:06:23 +00003058 * pickling -- tzinfo itself is supposed to be uninstantiable.
Tim Peters2a799bf2002-12-16 20:18:38 +00003059 */
3060
Guido van Rossum177e41a2003-01-30 22:06:23 +00003061static PyObject *
3062tzinfo_reduce(PyObject *self)
3063{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003064 PyObject *args, *state, *tmp;
3065 PyObject *getinitargs, *getstate;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02003066 _Py_IDENTIFIER(__getinitargs__);
3067 _Py_IDENTIFIER(__getstate__);
Tim Peters2a799bf2002-12-16 20:18:38 +00003068
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003069 tmp = PyTuple_New(0);
3070 if (tmp == NULL)
3071 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00003072
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02003073 getinitargs = _PyObject_GetAttrId(self, &PyId___getinitargs__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003074 if (getinitargs != NULL) {
3075 args = PyObject_CallObject(getinitargs, tmp);
3076 Py_DECREF(getinitargs);
3077 if (args == NULL) {
3078 Py_DECREF(tmp);
3079 return NULL;
3080 }
3081 }
3082 else {
3083 PyErr_Clear();
3084 args = tmp;
3085 Py_INCREF(args);
3086 }
Guido van Rossum177e41a2003-01-30 22:06:23 +00003087
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02003088 getstate = _PyObject_GetAttrId(self, &PyId___getstate__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003089 if (getstate != NULL) {
3090 state = PyObject_CallObject(getstate, tmp);
3091 Py_DECREF(getstate);
3092 if (state == NULL) {
3093 Py_DECREF(args);
3094 Py_DECREF(tmp);
3095 return NULL;
3096 }
3097 }
3098 else {
3099 PyObject **dictptr;
3100 PyErr_Clear();
3101 state = Py_None;
3102 dictptr = _PyObject_GetDictPtr(self);
3103 if (dictptr && *dictptr && PyDict_Size(*dictptr))
3104 state = *dictptr;
3105 Py_INCREF(state);
3106 }
Guido van Rossum177e41a2003-01-30 22:06:23 +00003107
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003108 Py_DECREF(tmp);
Guido van Rossum177e41a2003-01-30 22:06:23 +00003109
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003110 if (state == Py_None) {
3111 Py_DECREF(state);
3112 return Py_BuildValue("(ON)", Py_TYPE(self), args);
3113 }
3114 else
3115 return Py_BuildValue("(ONN)", Py_TYPE(self), args, state);
Guido van Rossum177e41a2003-01-30 22:06:23 +00003116}
Tim Peters2a799bf2002-12-16 20:18:38 +00003117
3118static PyMethodDef tzinfo_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00003119
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003120 {"tzname", (PyCFunction)tzinfo_tzname, METH_O,
3121 PyDoc_STR("datetime -> string name of time zone.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003122
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003123 {"utcoffset", (PyCFunction)tzinfo_utcoffset, METH_O,
Sean Reifscheiderdeda8cb2010-06-04 01:51:38 +00003124 PyDoc_STR("datetime -> timedelta showing offset from UTC, negative "
3125 "values indicating West of UTC")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003126
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003127 {"dst", (PyCFunction)tzinfo_dst, METH_O,
3128 PyDoc_STR("datetime -> DST offset in minutes east of UTC.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003129
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003130 {"fromutc", (PyCFunction)tzinfo_fromutc, METH_O,
Alexander Belopolsky2f194b92010-07-03 03:35:27 +00003131 PyDoc_STR("datetime in UTC -> datetime in local time.")},
Tim Peters52dcce22003-01-23 16:36:11 +00003132
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003133 {"__reduce__", (PyCFunction)tzinfo_reduce, METH_NOARGS,
3134 PyDoc_STR("-> (cls, state)")},
Guido van Rossum177e41a2003-01-30 22:06:23 +00003135
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003136 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00003137};
3138
3139static char tzinfo_doc[] =
3140PyDoc_STR("Abstract base class for time zone info objects.");
3141
Neal Norwitz227b5332006-03-22 09:28:35 +00003142static PyTypeObject PyDateTime_TZInfoType = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003143 PyVarObject_HEAD_INIT(NULL, 0)
3144 "datetime.tzinfo", /* tp_name */
3145 sizeof(PyDateTime_TZInfo), /* tp_basicsize */
3146 0, /* tp_itemsize */
3147 0, /* tp_dealloc */
3148 0, /* tp_print */
3149 0, /* tp_getattr */
3150 0, /* tp_setattr */
3151 0, /* tp_reserved */
3152 0, /* tp_repr */
3153 0, /* tp_as_number */
3154 0, /* tp_as_sequence */
3155 0, /* tp_as_mapping */
3156 0, /* tp_hash */
3157 0, /* tp_call */
3158 0, /* tp_str */
3159 PyObject_GenericGetAttr, /* tp_getattro */
3160 0, /* tp_setattro */
3161 0, /* tp_as_buffer */
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003162 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003163 tzinfo_doc, /* tp_doc */
3164 0, /* tp_traverse */
3165 0, /* tp_clear */
3166 0, /* tp_richcompare */
3167 0, /* tp_weaklistoffset */
3168 0, /* tp_iter */
3169 0, /* tp_iternext */
3170 tzinfo_methods, /* tp_methods */
3171 0, /* tp_members */
3172 0, /* tp_getset */
3173 0, /* tp_base */
3174 0, /* tp_dict */
3175 0, /* tp_descr_get */
3176 0, /* tp_descr_set */
3177 0, /* tp_dictoffset */
3178 0, /* tp_init */
3179 0, /* tp_alloc */
3180 PyType_GenericNew, /* tp_new */
3181 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00003182};
3183
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003184static char *timezone_kws[] = {"offset", "name", NULL};
3185
3186static PyObject *
3187timezone_new(PyTypeObject *type, PyObject *args, PyObject *kw)
3188{
3189 PyObject *offset;
3190 PyObject *name = NULL;
3191 if (PyArg_ParseTupleAndKeywords(args, kw, "O!|O!:timezone", timezone_kws,
3192 &PyDateTime_DeltaType, &offset,
3193 &PyUnicode_Type, &name))
3194 return new_timezone(offset, name);
3195
3196 return NULL;
3197}
3198
3199static void
3200timezone_dealloc(PyDateTime_TimeZone *self)
3201{
3202 Py_CLEAR(self->offset);
3203 Py_CLEAR(self->name);
3204 Py_TYPE(self)->tp_free((PyObject *)self);
3205}
3206
3207static PyObject *
3208timezone_richcompare(PyDateTime_TimeZone *self,
3209 PyDateTime_TimeZone *other, int op)
3210{
Brian Curtindfc80e32011-08-10 20:28:54 -05003211 if (op != Py_EQ && op != Py_NE)
3212 Py_RETURN_NOTIMPLEMENTED;
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003213 return delta_richcompare(self->offset, other->offset, op);
3214}
3215
Benjamin Peterson8f67d082010-10-17 20:54:53 +00003216static Py_hash_t
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003217timezone_hash(PyDateTime_TimeZone *self)
3218{
3219 return delta_hash((PyDateTime_Delta *)self->offset);
3220}
3221
3222/* Check argument type passed to tzname, utcoffset, or dst methods.
3223 Returns 0 for good argument. Returns -1 and sets exception info
3224 otherwise.
3225 */
3226static int
3227_timezone_check_argument(PyObject *dt, const char *meth)
3228{
3229 if (dt == Py_None || PyDateTime_Check(dt))
3230 return 0;
3231 PyErr_Format(PyExc_TypeError, "%s(dt) argument must be a datetime instance"
3232 " or None, not %.200s", meth, Py_TYPE(dt)->tp_name);
3233 return -1;
3234}
3235
3236static PyObject *
Alexander Belopolskya11d8c02010-07-06 23:19:45 +00003237timezone_repr(PyDateTime_TimeZone *self)
3238{
3239 /* Note that although timezone is not subclassable, it is convenient
3240 to use Py_TYPE(self)->tp_name here. */
3241 const char *type_name = Py_TYPE(self)->tp_name;
3242
3243 if (((PyObject *)self) == PyDateTime_TimeZone_UTC)
3244 return PyUnicode_FromFormat("%s.utc", type_name);
3245
3246 if (self->name == NULL)
3247 return PyUnicode_FromFormat("%s(%R)", type_name, self->offset);
3248
3249 return PyUnicode_FromFormat("%s(%R, %R)", type_name, self->offset,
3250 self->name);
3251}
3252
3253
3254static PyObject *
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003255timezone_str(PyDateTime_TimeZone *self)
3256{
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003257 int hours, minutes, seconds;
3258 PyObject *offset;
3259 char sign;
3260
3261 if (self->name != NULL) {
3262 Py_INCREF(self->name);
3263 return self->name;
3264 }
3265 /* Offset is normalized, so it is negative if days < 0 */
3266 if (GET_TD_DAYS(self->offset) < 0) {
3267 sign = '-';
3268 offset = delta_negative((PyDateTime_Delta *)self->offset);
3269 if (offset == NULL)
3270 return NULL;
3271 }
3272 else {
3273 sign = '+';
3274 offset = self->offset;
3275 Py_INCREF(offset);
3276 }
3277 /* Offset is not negative here. */
3278 seconds = GET_TD_SECONDS(offset);
3279 Py_DECREF(offset);
3280 minutes = divmod(seconds, 60, &seconds);
3281 hours = divmod(minutes, 60, &minutes);
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003282 /* XXX ignore sub-minute data, curently not allowed. */
Victor Stinner6ced7c42011-03-21 18:15:42 +01003283 assert(seconds == 0);
3284 return PyUnicode_FromFormat("UTC%c%02d:%02d", sign, hours, minutes);
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003285}
3286
3287static PyObject *
3288timezone_tzname(PyDateTime_TimeZone *self, PyObject *dt)
3289{
3290 if (_timezone_check_argument(dt, "tzname") == -1)
3291 return NULL;
3292
3293 return timezone_str(self);
3294}
3295
3296static PyObject *
3297timezone_utcoffset(PyDateTime_TimeZone *self, PyObject *dt)
3298{
3299 if (_timezone_check_argument(dt, "utcoffset") == -1)
3300 return NULL;
3301
3302 Py_INCREF(self->offset);
3303 return self->offset;
3304}
3305
3306static PyObject *
3307timezone_dst(PyObject *self, PyObject *dt)
3308{
3309 if (_timezone_check_argument(dt, "dst") == -1)
3310 return NULL;
3311
3312 Py_RETURN_NONE;
3313}
3314
3315static PyObject *
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003316timezone_fromutc(PyDateTime_TimeZone *self, PyDateTime_DateTime *dt)
3317{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003318 if (!PyDateTime_Check(dt)) {
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003319 PyErr_SetString(PyExc_TypeError,
3320 "fromutc: argument must be a datetime");
3321 return NULL;
3322 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003323 if (!HASTZINFO(dt) || dt->tzinfo != (PyObject *)self) {
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003324 PyErr_SetString(PyExc_ValueError, "fromutc: dt.tzinfo "
3325 "is not self");
3326 return NULL;
3327 }
3328
3329 return add_datetime_timedelta(dt, (PyDateTime_Delta *)self->offset, 1);
3330}
3331
Alexander Belopolsky1b7046b2010-06-23 21:40:15 +00003332static PyObject *
3333timezone_getinitargs(PyDateTime_TimeZone *self)
3334{
3335 if (self->name == NULL)
3336 return Py_BuildValue("(O)", self->offset);
3337 return Py_BuildValue("(OO)", self->offset, self->name);
3338}
3339
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003340static PyMethodDef timezone_methods[] = {
3341 {"tzname", (PyCFunction)timezone_tzname, METH_O,
3342 PyDoc_STR("If name is specified when timezone is created, returns the name."
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00003343 " Otherwise returns offset as 'UTC(+|-)HH:MM'.")},
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003344
3345 {"utcoffset", (PyCFunction)timezone_utcoffset, METH_O,
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00003346 PyDoc_STR("Return fixed offset.")},
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003347
3348 {"dst", (PyCFunction)timezone_dst, METH_O,
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00003349 PyDoc_STR("Return None.")},
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003350
3351 {"fromutc", (PyCFunction)timezone_fromutc, METH_O,
3352 PyDoc_STR("datetime in UTC -> datetime in local time.")},
3353
Alexander Belopolsky1b7046b2010-06-23 21:40:15 +00003354 {"__getinitargs__", (PyCFunction)timezone_getinitargs, METH_NOARGS,
3355 PyDoc_STR("pickle support")},
3356
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003357 {NULL, NULL}
3358};
3359
3360static char timezone_doc[] =
3361PyDoc_STR("Fixed offset from UTC implementation of tzinfo.");
3362
3363static PyTypeObject PyDateTime_TimeZoneType = {
3364 PyVarObject_HEAD_INIT(NULL, 0)
3365 "datetime.timezone", /* tp_name */
3366 sizeof(PyDateTime_TimeZone), /* tp_basicsize */
3367 0, /* tp_itemsize */
3368 (destructor)timezone_dealloc, /* tp_dealloc */
3369 0, /* tp_print */
3370 0, /* tp_getattr */
3371 0, /* tp_setattr */
3372 0, /* tp_reserved */
Alexander Belopolskya11d8c02010-07-06 23:19:45 +00003373 (reprfunc)timezone_repr, /* tp_repr */
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003374 0, /* tp_as_number */
3375 0, /* tp_as_sequence */
3376 0, /* tp_as_mapping */
3377 (hashfunc)timezone_hash, /* tp_hash */
3378 0, /* tp_call */
3379 (reprfunc)timezone_str, /* tp_str */
3380 0, /* tp_getattro */
3381 0, /* tp_setattro */
3382 0, /* tp_as_buffer */
3383 Py_TPFLAGS_DEFAULT, /* tp_flags */
3384 timezone_doc, /* tp_doc */
3385 0, /* tp_traverse */
3386 0, /* tp_clear */
3387 (richcmpfunc)timezone_richcompare,/* tp_richcompare */
3388 0, /* tp_weaklistoffset */
3389 0, /* tp_iter */
3390 0, /* tp_iternext */
3391 timezone_methods, /* tp_methods */
3392 0, /* tp_members */
3393 0, /* tp_getset */
3394 &PyDateTime_TZInfoType, /* tp_base */
3395 0, /* tp_dict */
3396 0, /* tp_descr_get */
3397 0, /* tp_descr_set */
3398 0, /* tp_dictoffset */
3399 0, /* tp_init */
3400 0, /* tp_alloc */
3401 timezone_new, /* tp_new */
3402};
3403
Tim Peters2a799bf2002-12-16 20:18:38 +00003404/*
Tim Peters37f39822003-01-10 03:49:02 +00003405 * PyDateTime_Time implementation.
Tim Peters2a799bf2002-12-16 20:18:38 +00003406 */
3407
Tim Peters37f39822003-01-10 03:49:02 +00003408/* Accessor properties.
Tim Peters2a799bf2002-12-16 20:18:38 +00003409 */
3410
3411static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003412time_hour(PyDateTime_Time *self, void *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00003413{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003414 return PyLong_FromLong(TIME_GET_HOUR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00003415}
3416
Tim Peters37f39822003-01-10 03:49:02 +00003417static PyObject *
3418time_minute(PyDateTime_Time *self, void *unused)
3419{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003420 return PyLong_FromLong(TIME_GET_MINUTE(self));
Tim Peters37f39822003-01-10 03:49:02 +00003421}
3422
3423/* The name time_second conflicted with some platform header file. */
3424static PyObject *
3425py_time_second(PyDateTime_Time *self, void *unused)
3426{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003427 return PyLong_FromLong(TIME_GET_SECOND(self));
Tim Peters37f39822003-01-10 03:49:02 +00003428}
3429
3430static PyObject *
3431time_microsecond(PyDateTime_Time *self, void *unused)
3432{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003433 return PyLong_FromLong(TIME_GET_MICROSECOND(self));
Tim Peters37f39822003-01-10 03:49:02 +00003434}
3435
3436static PyObject *
3437time_tzinfo(PyDateTime_Time *self, void *unused)
3438{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003439 PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
3440 Py_INCREF(result);
3441 return result;
Tim Peters37f39822003-01-10 03:49:02 +00003442}
3443
3444static PyGetSetDef time_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003445 {"hour", (getter)time_hour},
3446 {"minute", (getter)time_minute},
3447 {"second", (getter)py_time_second},
3448 {"microsecond", (getter)time_microsecond},
3449 {"tzinfo", (getter)time_tzinfo},
3450 {NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00003451};
3452
3453/*
3454 * Constructors.
3455 */
3456
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003457static char *time_kws[] = {"hour", "minute", "second", "microsecond",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003458 "tzinfo", NULL};
Tim Peters12bf3392002-12-24 05:41:27 +00003459
Tim Peters2a799bf2002-12-16 20:18:38 +00003460static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003461time_new(PyTypeObject *type, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003462{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003463 PyObject *self = NULL;
3464 PyObject *state;
3465 int hour = 0;
3466 int minute = 0;
3467 int second = 0;
3468 int usecond = 0;
3469 PyObject *tzinfo = Py_None;
Tim Peters2a799bf2002-12-16 20:18:38 +00003470
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003471 /* Check for invocation from pickle with __getstate__ state */
3472 if (PyTuple_GET_SIZE(args) >= 1 &&
3473 PyTuple_GET_SIZE(args) <= 2 &&
3474 PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) &&
3475 PyBytes_GET_SIZE(state) == _PyDateTime_TIME_DATASIZE &&
3476 ((unsigned char) (PyBytes_AS_STRING(state)[0])) < 24)
3477 {
3478 PyDateTime_Time *me;
3479 char aware;
Tim Peters70533e22003-02-01 04:40:04 +00003480
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003481 if (PyTuple_GET_SIZE(args) == 2) {
3482 tzinfo = PyTuple_GET_ITEM(args, 1);
3483 if (check_tzinfo_subclass(tzinfo) < 0) {
3484 PyErr_SetString(PyExc_TypeError, "bad "
3485 "tzinfo state arg");
3486 return NULL;
3487 }
3488 }
3489 aware = (char)(tzinfo != Py_None);
3490 me = (PyDateTime_Time *) (type->tp_alloc(type, aware));
3491 if (me != NULL) {
3492 char *pdata = PyBytes_AS_STRING(state);
Tim Peters70533e22003-02-01 04:40:04 +00003493
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003494 memcpy(me->data, pdata, _PyDateTime_TIME_DATASIZE);
3495 me->hashcode = -1;
3496 me->hastzinfo = aware;
3497 if (aware) {
3498 Py_INCREF(tzinfo);
3499 me->tzinfo = tzinfo;
3500 }
3501 }
3502 return (PyObject *)me;
3503 }
Guido van Rossum177e41a2003-01-30 22:06:23 +00003504
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003505 if (PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO", time_kws,
3506 &hour, &minute, &second, &usecond,
3507 &tzinfo)) {
3508 if (check_time_args(hour, minute, second, usecond) < 0)
3509 return NULL;
3510 if (check_tzinfo_subclass(tzinfo) < 0)
3511 return NULL;
3512 self = new_time_ex(hour, minute, second, usecond, tzinfo,
3513 type);
3514 }
3515 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00003516}
3517
3518/*
3519 * Destructor.
3520 */
3521
3522static void
Tim Peters37f39822003-01-10 03:49:02 +00003523time_dealloc(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003524{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003525 if (HASTZINFO(self)) {
3526 Py_XDECREF(self->tzinfo);
3527 }
3528 Py_TYPE(self)->tp_free((PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00003529}
3530
3531/*
Tim Peters855fe882002-12-22 03:43:39 +00003532 * Indirect access to tzinfo methods.
Tim Peters2a799bf2002-12-16 20:18:38 +00003533 */
3534
Tim Peters2a799bf2002-12-16 20:18:38 +00003535/* These are all METH_NOARGS, so don't need to check the arglist. */
3536static PyObject *
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003537time_utcoffset(PyObject *self, PyObject *unused) {
3538 return call_utcoffset(GET_TIME_TZINFO(self), Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00003539}
3540
3541static PyObject *
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003542time_dst(PyObject *self, PyObject *unused) {
3543 return call_dst(GET_TIME_TZINFO(self), Py_None);
Tim Peters855fe882002-12-22 03:43:39 +00003544}
3545
3546static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003547time_tzname(PyDateTime_Time *self, PyObject *unused) {
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003548 return call_tzname(GET_TIME_TZINFO(self), Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00003549}
3550
3551/*
Tim Peters37f39822003-01-10 03:49:02 +00003552 * Various ways to turn a time into a string.
Tim Peters2a799bf2002-12-16 20:18:38 +00003553 */
3554
3555static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003556time_repr(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003557{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003558 const char *type_name = Py_TYPE(self)->tp_name;
3559 int h = TIME_GET_HOUR(self);
3560 int m = TIME_GET_MINUTE(self);
3561 int s = TIME_GET_SECOND(self);
3562 int us = TIME_GET_MICROSECOND(self);
3563 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00003564
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003565 if (us)
3566 result = PyUnicode_FromFormat("%s(%d, %d, %d, %d)",
3567 type_name, h, m, s, us);
3568 else if (s)
3569 result = PyUnicode_FromFormat("%s(%d, %d, %d)",
3570 type_name, h, m, s);
3571 else
3572 result = PyUnicode_FromFormat("%s(%d, %d)", type_name, h, m);
3573 if (result != NULL && HASTZINFO(self))
3574 result = append_keyword_tzinfo(result, self->tzinfo);
3575 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00003576}
3577
Tim Peters37f39822003-01-10 03:49:02 +00003578static PyObject *
3579time_str(PyDateTime_Time *self)
3580{
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02003581 _Py_IDENTIFIER(isoformat);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02003582
3583 return _PyObject_CallMethodId((PyObject *)self, &PyId_isoformat, "()");
Tim Peters37f39822003-01-10 03:49:02 +00003584}
Tim Peters2a799bf2002-12-16 20:18:38 +00003585
3586static PyObject *
Thomas Wouterscf297e42007-02-23 15:07:44 +00003587time_isoformat(PyDateTime_Time *self, PyObject *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00003588{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003589 char buf[100];
3590 PyObject *result;
3591 int us = TIME_GET_MICROSECOND(self);;
Tim Peters2a799bf2002-12-16 20:18:38 +00003592
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003593 if (us)
3594 result = PyUnicode_FromFormat("%02d:%02d:%02d.%06d",
3595 TIME_GET_HOUR(self),
3596 TIME_GET_MINUTE(self),
3597 TIME_GET_SECOND(self),
3598 us);
3599 else
3600 result = PyUnicode_FromFormat("%02d:%02d:%02d",
3601 TIME_GET_HOUR(self),
3602 TIME_GET_MINUTE(self),
3603 TIME_GET_SECOND(self));
Tim Peters37f39822003-01-10 03:49:02 +00003604
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003605 if (result == NULL || !HASTZINFO(self) || self->tzinfo == Py_None)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003606 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00003607
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003608 /* We need to append the UTC offset. */
3609 if (format_utcoffset(buf, sizeof(buf), ":", self->tzinfo,
3610 Py_None) < 0) {
3611 Py_DECREF(result);
3612 return NULL;
3613 }
3614 PyUnicode_AppendAndDel(&result, PyUnicode_FromString(buf));
3615 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00003616}
3617
Tim Peters37f39822003-01-10 03:49:02 +00003618static PyObject *
3619time_strftime(PyDateTime_Time *self, PyObject *args, PyObject *kw)
3620{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003621 PyObject *result;
3622 PyObject *tuple;
3623 PyObject *format;
3624 static char *keywords[] = {"format", NULL};
Tim Peters37f39822003-01-10 03:49:02 +00003625
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003626 if (! PyArg_ParseTupleAndKeywords(args, kw, "U:strftime", keywords,
3627 &format))
3628 return NULL;
Tim Peters37f39822003-01-10 03:49:02 +00003629
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003630 /* Python's strftime does insane things with the year part of the
3631 * timetuple. The year is forced to (the otherwise nonsensical)
Alexander Belopolskyb8bb4662011-01-08 00:13:34 +00003632 * 1900 to work around that.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003633 */
3634 tuple = Py_BuildValue("iiiiiiiii",
3635 1900, 1, 1, /* year, month, day */
3636 TIME_GET_HOUR(self),
3637 TIME_GET_MINUTE(self),
3638 TIME_GET_SECOND(self),
3639 0, 1, -1); /* weekday, daynum, dst */
3640 if (tuple == NULL)
3641 return NULL;
3642 assert(PyTuple_Size(tuple) == 9);
3643 result = wrap_strftime((PyObject *)self, format, tuple,
3644 Py_None);
3645 Py_DECREF(tuple);
3646 return result;
Tim Peters37f39822003-01-10 03:49:02 +00003647}
Tim Peters2a799bf2002-12-16 20:18:38 +00003648
3649/*
3650 * Miscellaneous methods.
3651 */
3652
Tim Peters37f39822003-01-10 03:49:02 +00003653static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00003654time_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters37f39822003-01-10 03:49:02 +00003655{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003656 PyObject *result = NULL;
3657 PyObject *offset1, *offset2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003658 int diff;
Tim Peters37f39822003-01-10 03:49:02 +00003659
Brian Curtindfc80e32011-08-10 20:28:54 -05003660 if (! PyTime_Check(other))
3661 Py_RETURN_NOTIMPLEMENTED;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003662
3663 if (GET_TIME_TZINFO(self) == GET_TIME_TZINFO(other)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003664 diff = memcmp(((PyDateTime_Time *)self)->data,
3665 ((PyDateTime_Time *)other)->data,
3666 _PyDateTime_TIME_DATASIZE);
3667 return diff_to_bool(diff, op);
3668 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003669 offset1 = time_utcoffset(self, NULL);
3670 if (offset1 == NULL)
3671 return NULL;
3672 offset2 = time_utcoffset(other, NULL);
3673 if (offset2 == NULL)
3674 goto done;
3675 /* If they're both naive, or both aware and have the same offsets,
3676 * we get off cheap. Note that if they're both naive, offset1 ==
3677 * offset2 == Py_None at this point.
3678 */
3679 if ((offset1 == offset2) ||
3680 (PyDelta_Check(offset1) && PyDelta_Check(offset2) &&
3681 delta_cmp(offset1, offset2) == 0)) {
3682 diff = memcmp(((PyDateTime_Time *)self)->data,
3683 ((PyDateTime_Time *)other)->data,
3684 _PyDateTime_TIME_DATASIZE);
3685 result = diff_to_bool(diff, op);
3686 }
3687 /* The hard case: both aware with different UTC offsets */
3688 else if (offset1 != Py_None && offset2 != Py_None) {
3689 int offsecs1, offsecs2;
3690 assert(offset1 != offset2); /* else last "if" handled it */
3691 offsecs1 = TIME_GET_HOUR(self) * 3600 +
3692 TIME_GET_MINUTE(self) * 60 +
3693 TIME_GET_SECOND(self) -
3694 GET_TD_DAYS(offset1) * 86400 -
3695 GET_TD_SECONDS(offset1);
3696 offsecs2 = TIME_GET_HOUR(other) * 3600 +
3697 TIME_GET_MINUTE(other) * 60 +
3698 TIME_GET_SECOND(other) -
3699 GET_TD_DAYS(offset2) * 86400 -
3700 GET_TD_SECONDS(offset2);
3701 diff = offsecs1 - offsecs2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003702 if (diff == 0)
3703 diff = TIME_GET_MICROSECOND(self) -
3704 TIME_GET_MICROSECOND(other);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003705 result = diff_to_bool(diff, op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003706 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003707 else {
3708 PyErr_SetString(PyExc_TypeError,
3709 "can't compare offset-naive and "
3710 "offset-aware times");
3711 }
3712 done:
3713 Py_DECREF(offset1);
3714 Py_XDECREF(offset2);
3715 return result;
Tim Peters37f39822003-01-10 03:49:02 +00003716}
3717
Benjamin Peterson8f67d082010-10-17 20:54:53 +00003718static Py_hash_t
Tim Peters37f39822003-01-10 03:49:02 +00003719time_hash(PyDateTime_Time *self)
3720{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003721 if (self->hashcode == -1) {
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003722 PyObject *offset;
Tim Peters37f39822003-01-10 03:49:02 +00003723
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003724 offset = time_utcoffset((PyObject *)self, NULL);
3725
3726 if (offset == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003727 return -1;
Tim Peters37f39822003-01-10 03:49:02 +00003728
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003729 /* Reduce this to a hash of another object. */
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003730 if (offset == Py_None)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003731 self->hashcode = generic_hash(
3732 (unsigned char *)self->data, _PyDateTime_TIME_DATASIZE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003733 else {
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003734 PyObject *temp1, *temp2;
3735 int seconds, microseconds;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003736 assert(HASTZINFO(self));
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003737 seconds = TIME_GET_HOUR(self) * 3600 +
3738 TIME_GET_MINUTE(self) * 60 +
3739 TIME_GET_SECOND(self);
3740 microseconds = TIME_GET_MICROSECOND(self);
3741 temp1 = new_delta(0, seconds, microseconds, 1);
3742 if (temp1 == NULL) {
3743 Py_DECREF(offset);
3744 return -1;
3745 }
3746 temp2 = delta_subtract(temp1, offset);
3747 Py_DECREF(temp1);
3748 if (temp2 == NULL) {
3749 Py_DECREF(offset);
3750 return -1;
3751 }
3752 self->hashcode = PyObject_Hash(temp2);
3753 Py_DECREF(temp2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003754 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003755 Py_DECREF(offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003756 }
3757 return self->hashcode;
Tim Peters37f39822003-01-10 03:49:02 +00003758}
Tim Peters2a799bf2002-12-16 20:18:38 +00003759
Tim Peters12bf3392002-12-24 05:41:27 +00003760static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003761time_replace(PyDateTime_Time *self, PyObject *args, PyObject *kw)
Tim Peters12bf3392002-12-24 05:41:27 +00003762{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003763 PyObject *clone;
3764 PyObject *tuple;
3765 int hh = TIME_GET_HOUR(self);
3766 int mm = TIME_GET_MINUTE(self);
3767 int ss = TIME_GET_SECOND(self);
3768 int us = TIME_GET_MICROSECOND(self);
3769 PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
Tim Peters12bf3392002-12-24 05:41:27 +00003770
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003771 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO:replace",
3772 time_kws,
3773 &hh, &mm, &ss, &us, &tzinfo))
3774 return NULL;
3775 tuple = Py_BuildValue("iiiiO", hh, mm, ss, us, tzinfo);
3776 if (tuple == NULL)
3777 return NULL;
3778 clone = time_new(Py_TYPE(self), tuple, NULL);
3779 Py_DECREF(tuple);
3780 return clone;
Tim Peters12bf3392002-12-24 05:41:27 +00003781}
3782
Tim Peters2a799bf2002-12-16 20:18:38 +00003783static int
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003784time_bool(PyObject *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003785{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003786 PyObject *offset, *tzinfo;
3787 int offsecs = 0;
Tim Peters2a799bf2002-12-16 20:18:38 +00003788
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003789 if (TIME_GET_SECOND(self) || TIME_GET_MICROSECOND(self)) {
3790 /* Since utcoffset is in whole minutes, nothing can
3791 * alter the conclusion that this is nonzero.
3792 */
3793 return 1;
3794 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003795 tzinfo = GET_TIME_TZINFO(self);
3796 if (tzinfo != Py_None) {
3797 offset = call_utcoffset(tzinfo, Py_None);
3798 if (offset == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003799 return -1;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003800 offsecs = GET_TD_DAYS(offset)*86400 + GET_TD_SECONDS(offset);
3801 Py_DECREF(offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003802 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003803 return (TIME_GET_MINUTE(self)*60 - offsecs + TIME_GET_HOUR(self)*3600) != 0;
Tim Peters2a799bf2002-12-16 20:18:38 +00003804}
3805
Tim Peters371935f2003-02-01 01:52:50 +00003806/* Pickle support, a simple use of __reduce__. */
Tim Peters2a799bf2002-12-16 20:18:38 +00003807
Tim Peters33e0f382003-01-10 02:05:14 +00003808/* Let basestate be the non-tzinfo data string.
Tim Peters2a799bf2002-12-16 20:18:38 +00003809 * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
3810 * So it's a tuple in any (non-error) case.
Tim Petersb57f8f02003-02-01 02:54:15 +00003811 * __getstate__ isn't exposed.
Tim Peters2a799bf2002-12-16 20:18:38 +00003812 */
3813static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003814time_getstate(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003815{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003816 PyObject *basestate;
3817 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00003818
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003819 basestate = PyBytes_FromStringAndSize((char *)self->data,
3820 _PyDateTime_TIME_DATASIZE);
3821 if (basestate != NULL) {
3822 if (! HASTZINFO(self) || self->tzinfo == Py_None)
3823 result = PyTuple_Pack(1, basestate);
3824 else
3825 result = PyTuple_Pack(2, basestate, self->tzinfo);
3826 Py_DECREF(basestate);
3827 }
3828 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00003829}
3830
3831static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00003832time_reduce(PyDateTime_Time *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00003833{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003834 return Py_BuildValue("(ON)", Py_TYPE(self), time_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00003835}
3836
Tim Peters37f39822003-01-10 03:49:02 +00003837static PyMethodDef time_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00003838
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003839 {"isoformat", (PyCFunction)time_isoformat, METH_NOARGS,
3840 PyDoc_STR("Return string in ISO 8601 format, HH:MM:SS[.mmmmmm]"
3841 "[+HH:MM].")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003842
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003843 {"strftime", (PyCFunction)time_strftime, METH_VARARGS | METH_KEYWORDS,
3844 PyDoc_STR("format -> strftime() style string.")},
Tim Peters37f39822003-01-10 03:49:02 +00003845
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003846 {"__format__", (PyCFunction)date_format, METH_VARARGS,
3847 PyDoc_STR("Formats self with strftime.")},
Eric Smith1ba31142007-09-11 18:06:02 +00003848
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003849 {"utcoffset", (PyCFunction)time_utcoffset, METH_NOARGS,
3850 PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003851
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003852 {"tzname", (PyCFunction)time_tzname, METH_NOARGS,
3853 PyDoc_STR("Return self.tzinfo.tzname(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003854
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003855 {"dst", (PyCFunction)time_dst, METH_NOARGS,
3856 PyDoc_STR("Return self.tzinfo.dst(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003857
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003858 {"replace", (PyCFunction)time_replace, METH_VARARGS | METH_KEYWORDS,
3859 PyDoc_STR("Return time with new specified fields.")},
Tim Peters12bf3392002-12-24 05:41:27 +00003860
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003861 {"__reduce__", (PyCFunction)time_reduce, METH_NOARGS,
3862 PyDoc_STR("__reduce__() -> (cls, state)")},
Guido van Rossum177e41a2003-01-30 22:06:23 +00003863
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003864 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00003865};
3866
Tim Peters37f39822003-01-10 03:49:02 +00003867static char time_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00003868PyDoc_STR("time([hour[, minute[, second[, microsecond[, tzinfo]]]]]) --> a time object\n\
3869\n\
3870All arguments are optional. tzinfo may be None, or an instance of\n\
3871a tzinfo subclass. The remaining arguments may be ints or longs.\n");
Tim Peters2a799bf2002-12-16 20:18:38 +00003872
Tim Peters37f39822003-01-10 03:49:02 +00003873static PyNumberMethods time_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003874 0, /* nb_add */
3875 0, /* nb_subtract */
3876 0, /* nb_multiply */
3877 0, /* nb_remainder */
3878 0, /* nb_divmod */
3879 0, /* nb_power */
3880 0, /* nb_negative */
3881 0, /* nb_positive */
3882 0, /* nb_absolute */
3883 (inquiry)time_bool, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00003884};
3885
Neal Norwitz227b5332006-03-22 09:28:35 +00003886static PyTypeObject PyDateTime_TimeType = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003887 PyVarObject_HEAD_INIT(NULL, 0)
3888 "datetime.time", /* tp_name */
3889 sizeof(PyDateTime_Time), /* tp_basicsize */
3890 0, /* tp_itemsize */
3891 (destructor)time_dealloc, /* tp_dealloc */
3892 0, /* tp_print */
3893 0, /* tp_getattr */
3894 0, /* tp_setattr */
3895 0, /* tp_reserved */
3896 (reprfunc)time_repr, /* tp_repr */
3897 &time_as_number, /* tp_as_number */
3898 0, /* tp_as_sequence */
3899 0, /* tp_as_mapping */
3900 (hashfunc)time_hash, /* tp_hash */
3901 0, /* tp_call */
3902 (reprfunc)time_str, /* tp_str */
3903 PyObject_GenericGetAttr, /* tp_getattro */
3904 0, /* tp_setattro */
3905 0, /* tp_as_buffer */
3906 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
3907 time_doc, /* tp_doc */
3908 0, /* tp_traverse */
3909 0, /* tp_clear */
3910 time_richcompare, /* tp_richcompare */
3911 0, /* tp_weaklistoffset */
3912 0, /* tp_iter */
3913 0, /* tp_iternext */
3914 time_methods, /* tp_methods */
3915 0, /* tp_members */
3916 time_getset, /* tp_getset */
3917 0, /* tp_base */
3918 0, /* tp_dict */
3919 0, /* tp_descr_get */
3920 0, /* tp_descr_set */
3921 0, /* tp_dictoffset */
3922 0, /* tp_init */
3923 time_alloc, /* tp_alloc */
3924 time_new, /* tp_new */
3925 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00003926};
3927
3928/*
Tim Petersa9bc1682003-01-11 03:39:11 +00003929 * PyDateTime_DateTime implementation.
Tim Peters2a799bf2002-12-16 20:18:38 +00003930 */
3931
Tim Petersa9bc1682003-01-11 03:39:11 +00003932/* Accessor properties. Properties for day, month, and year are inherited
3933 * from date.
Tim Peters2a799bf2002-12-16 20:18:38 +00003934 */
3935
3936static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003937datetime_hour(PyDateTime_DateTime *self, void *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00003938{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003939 return PyLong_FromLong(DATE_GET_HOUR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00003940}
3941
Tim Petersa9bc1682003-01-11 03:39:11 +00003942static PyObject *
3943datetime_minute(PyDateTime_DateTime *self, void *unused)
3944{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003945 return PyLong_FromLong(DATE_GET_MINUTE(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00003946}
3947
3948static PyObject *
3949datetime_second(PyDateTime_DateTime *self, void *unused)
3950{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003951 return PyLong_FromLong(DATE_GET_SECOND(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00003952}
3953
3954static PyObject *
3955datetime_microsecond(PyDateTime_DateTime *self, void *unused)
3956{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003957 return PyLong_FromLong(DATE_GET_MICROSECOND(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00003958}
3959
3960static PyObject *
3961datetime_tzinfo(PyDateTime_DateTime *self, void *unused)
3962{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003963 PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
3964 Py_INCREF(result);
3965 return result;
Tim Petersa9bc1682003-01-11 03:39:11 +00003966}
3967
3968static PyGetSetDef datetime_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003969 {"hour", (getter)datetime_hour},
3970 {"minute", (getter)datetime_minute},
3971 {"second", (getter)datetime_second},
3972 {"microsecond", (getter)datetime_microsecond},
3973 {"tzinfo", (getter)datetime_tzinfo},
3974 {NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00003975};
3976
3977/*
3978 * Constructors.
Tim Peters2a799bf2002-12-16 20:18:38 +00003979 */
3980
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003981static char *datetime_kws[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003982 "year", "month", "day", "hour", "minute", "second",
3983 "microsecond", "tzinfo", NULL
Tim Peters12bf3392002-12-24 05:41:27 +00003984};
3985
Tim Peters2a799bf2002-12-16 20:18:38 +00003986static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003987datetime_new(PyTypeObject *type, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003988{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003989 PyObject *self = NULL;
3990 PyObject *state;
3991 int year;
3992 int month;
3993 int day;
3994 int hour = 0;
3995 int minute = 0;
3996 int second = 0;
3997 int usecond = 0;
3998 PyObject *tzinfo = Py_None;
Tim Peters2a799bf2002-12-16 20:18:38 +00003999
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004000 /* Check for invocation from pickle with __getstate__ state */
4001 if (PyTuple_GET_SIZE(args) >= 1 &&
4002 PyTuple_GET_SIZE(args) <= 2 &&
4003 PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) &&
4004 PyBytes_GET_SIZE(state) == _PyDateTime_DATETIME_DATASIZE &&
4005 MONTH_IS_SANE(PyBytes_AS_STRING(state)[2]))
4006 {
4007 PyDateTime_DateTime *me;
4008 char aware;
Tim Peters70533e22003-02-01 04:40:04 +00004009
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004010 if (PyTuple_GET_SIZE(args) == 2) {
4011 tzinfo = PyTuple_GET_ITEM(args, 1);
4012 if (check_tzinfo_subclass(tzinfo) < 0) {
4013 PyErr_SetString(PyExc_TypeError, "bad "
4014 "tzinfo state arg");
4015 return NULL;
4016 }
4017 }
4018 aware = (char)(tzinfo != Py_None);
4019 me = (PyDateTime_DateTime *) (type->tp_alloc(type , aware));
4020 if (me != NULL) {
4021 char *pdata = PyBytes_AS_STRING(state);
Tim Peters70533e22003-02-01 04:40:04 +00004022
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004023 memcpy(me->data, pdata, _PyDateTime_DATETIME_DATASIZE);
4024 me->hashcode = -1;
4025 me->hastzinfo = aware;
4026 if (aware) {
4027 Py_INCREF(tzinfo);
4028 me->tzinfo = tzinfo;
4029 }
4030 }
4031 return (PyObject *)me;
4032 }
Guido van Rossum177e41a2003-01-30 22:06:23 +00004033
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004034 if (PyArg_ParseTupleAndKeywords(args, kw, "iii|iiiiO", datetime_kws,
4035 &year, &month, &day, &hour, &minute,
4036 &second, &usecond, &tzinfo)) {
4037 if (check_date_args(year, month, day) < 0)
4038 return NULL;
4039 if (check_time_args(hour, minute, second, usecond) < 0)
4040 return NULL;
4041 if (check_tzinfo_subclass(tzinfo) < 0)
4042 return NULL;
4043 self = new_datetime_ex(year, month, day,
4044 hour, minute, second, usecond,
4045 tzinfo, type);
4046 }
4047 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00004048}
4049
Tim Petersa9bc1682003-01-11 03:39:11 +00004050/* TM_FUNC is the shared type of localtime() and gmtime(). */
4051typedef struct tm *(*TM_FUNC)(const time_t *timer);
4052
4053/* Internal helper.
4054 * Build datetime from a time_t and a distinct count of microseconds.
4055 * Pass localtime or gmtime for f, to control the interpretation of timet.
4056 */
4057static PyObject *
4058datetime_from_timet_and_us(PyObject *cls, TM_FUNC f, time_t timet, int us,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004059 PyObject *tzinfo)
Tim Petersa9bc1682003-01-11 03:39:11 +00004060{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004061 struct tm *tm;
4062 PyObject *result = NULL;
Tim Petersa9bc1682003-01-11 03:39:11 +00004063
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004064 tm = f(&timet);
4065 if (tm) {
4066 /* The platform localtime/gmtime may insert leap seconds,
4067 * indicated by tm->tm_sec > 59. We don't care about them,
4068 * except to the extent that passing them on to the datetime
4069 * constructor would raise ValueError for a reason that
4070 * made no sense to the user.
4071 */
4072 if (tm->tm_sec > 59)
4073 tm->tm_sec = 59;
4074 result = PyObject_CallFunction(cls, "iiiiiiiO",
4075 tm->tm_year + 1900,
4076 tm->tm_mon + 1,
4077 tm->tm_mday,
4078 tm->tm_hour,
4079 tm->tm_min,
4080 tm->tm_sec,
4081 us,
4082 tzinfo);
4083 }
4084 else
4085 PyErr_SetString(PyExc_ValueError,
4086 "timestamp out of range for "
4087 "platform localtime()/gmtime() function");
4088 return result;
Tim Petersa9bc1682003-01-11 03:39:11 +00004089}
4090
4091/* Internal helper.
4092 * Build datetime from a Python timestamp. Pass localtime or gmtime for f,
4093 * to control the interpretation of the timestamp. Since a double doesn't
4094 * have enough bits to cover a datetime's full range of precision, it's
4095 * better to call datetime_from_timet_and_us provided you have a way
4096 * to get that much precision (e.g., C time() isn't good enough).
4097 */
4098static PyObject *
4099datetime_from_timestamp(PyObject *cls, TM_FUNC f, double timestamp,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004100 PyObject *tzinfo)
Tim Petersa9bc1682003-01-11 03:39:11 +00004101{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004102 time_t timet;
4103 double fraction;
4104 int us;
Tim Petersa9bc1682003-01-11 03:39:11 +00004105
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004106 timet = _PyTime_DoubleToTimet(timestamp);
4107 if (timet == (time_t)-1 && PyErr_Occurred())
4108 return NULL;
4109 fraction = timestamp - (double)timet;
4110 us = (int)round_to_long(fraction * 1e6);
4111 if (us < 0) {
4112 /* Truncation towards zero is not what we wanted
4113 for negative numbers (Python's mod semantics) */
4114 timet -= 1;
4115 us += 1000000;
4116 }
4117 /* If timestamp is less than one microsecond smaller than a
4118 * full second, round up. Otherwise, ValueErrors are raised
4119 * for some floats. */
4120 if (us == 1000000) {
4121 timet += 1;
4122 us = 0;
4123 }
4124 return datetime_from_timet_and_us(cls, f, timet, us, tzinfo);
Tim Petersa9bc1682003-01-11 03:39:11 +00004125}
4126
4127/* Internal helper.
4128 * Build most accurate possible datetime for current time. Pass localtime or
4129 * gmtime for f as appropriate.
4130 */
4131static PyObject *
4132datetime_best_possible(PyObject *cls, TM_FUNC f, PyObject *tzinfo)
4133{
Alexander Belopolsky6fc4ade2010-08-05 17:34:27 +00004134 _PyTime_timeval t;
4135 _PyTime_gettimeofday(&t);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004136 return datetime_from_timet_and_us(cls, f, t.tv_sec, (int)t.tv_usec,
4137 tzinfo);
Tim Petersa9bc1682003-01-11 03:39:11 +00004138}
4139
Tim Peters2a799bf2002-12-16 20:18:38 +00004140/* Return best possible local time -- this isn't constrained by the
4141 * precision of a timestamp.
4142 */
4143static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004144datetime_now(PyObject *cls, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00004145{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004146 PyObject *self;
4147 PyObject *tzinfo = Py_None;
4148 static char *keywords[] = {"tz", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00004149
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004150 if (! PyArg_ParseTupleAndKeywords(args, kw, "|O:now", keywords,
4151 &tzinfo))
4152 return NULL;
4153 if (check_tzinfo_subclass(tzinfo) < 0)
4154 return NULL;
Tim Peters10cadce2003-01-23 19:58:02 +00004155
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004156 self = datetime_best_possible(cls,
4157 tzinfo == Py_None ? localtime : gmtime,
4158 tzinfo);
4159 if (self != NULL && tzinfo != Py_None) {
4160 /* Convert UTC to tzinfo's zone. */
4161 PyObject *temp = self;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02004162 _Py_IDENTIFIER(fromutc);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02004163
4164 self = _PyObject_CallMethodId(tzinfo, &PyId_fromutc, "O", self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004165 Py_DECREF(temp);
4166 }
4167 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00004168}
4169
Tim Petersa9bc1682003-01-11 03:39:11 +00004170/* Return best possible UTC time -- this isn't constrained by the
4171 * precision of a timestamp.
4172 */
4173static PyObject *
4174datetime_utcnow(PyObject *cls, PyObject *dummy)
4175{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004176 return datetime_best_possible(cls, gmtime, Py_None);
Tim Petersa9bc1682003-01-11 03:39:11 +00004177}
4178
Tim Peters2a799bf2002-12-16 20:18:38 +00004179/* Return new local datetime from timestamp (Python timestamp -- a double). */
4180static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004181datetime_fromtimestamp(PyObject *cls, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00004182{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004183 PyObject *self;
4184 double timestamp;
4185 PyObject *tzinfo = Py_None;
4186 static char *keywords[] = {"timestamp", "tz", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00004187
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004188 if (! PyArg_ParseTupleAndKeywords(args, kw, "d|O:fromtimestamp",
4189 keywords, &timestamp, &tzinfo))
4190 return NULL;
4191 if (check_tzinfo_subclass(tzinfo) < 0)
4192 return NULL;
Tim Peters2a44a8d2003-01-23 20:53:10 +00004193
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004194 self = datetime_from_timestamp(cls,
4195 tzinfo == Py_None ? localtime : gmtime,
4196 timestamp,
4197 tzinfo);
4198 if (self != NULL && tzinfo != Py_None) {
4199 /* Convert UTC to tzinfo's zone. */
4200 PyObject *temp = self;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02004201 _Py_IDENTIFIER(fromutc);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02004202
4203 self = _PyObject_CallMethodId(tzinfo, &PyId_fromutc, "O", self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004204 Py_DECREF(temp);
4205 }
4206 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00004207}
4208
Tim Petersa9bc1682003-01-11 03:39:11 +00004209/* Return new UTC datetime from timestamp (Python timestamp -- a double). */
4210static PyObject *
4211datetime_utcfromtimestamp(PyObject *cls, PyObject *args)
4212{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004213 double timestamp;
4214 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004215
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004216 if (PyArg_ParseTuple(args, "d:utcfromtimestamp", &timestamp))
4217 result = datetime_from_timestamp(cls, gmtime, timestamp,
4218 Py_None);
4219 return result;
Tim Petersa9bc1682003-01-11 03:39:11 +00004220}
4221
Alexander Belopolskyca94f552010-06-17 18:30:34 +00004222/* Return new datetime from _strptime.strptime_datetime(). */
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004223static PyObject *
4224datetime_strptime(PyObject *cls, PyObject *args)
4225{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004226 static PyObject *module = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004227 PyObject *string, *format;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02004228 _Py_IDENTIFIER(_strptime_datetime);
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004229
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004230 if (!PyArg_ParseTuple(args, "UU:strptime", &string, &format))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004231 return NULL;
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004232
Alexander Belopolskyca94f552010-06-17 18:30:34 +00004233 if (module == NULL) {
4234 module = PyImport_ImportModuleNoBlock("_strptime");
Alexander Belopolsky311d2a92010-06-28 14:36:55 +00004235 if (module == NULL)
Alexander Belopolskyca94f552010-06-17 18:30:34 +00004236 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004237 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02004238 return _PyObject_CallMethodId(module, &PyId__strptime_datetime, "OOO",
4239 cls, string, format);
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004240}
4241
Tim Petersa9bc1682003-01-11 03:39:11 +00004242/* Return new datetime from date/datetime and time arguments. */
4243static PyObject *
4244datetime_combine(PyObject *cls, PyObject *args, PyObject *kw)
4245{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004246 static char *keywords[] = {"date", "time", NULL};
4247 PyObject *date;
4248 PyObject *time;
4249 PyObject *result = NULL;
Tim Petersa9bc1682003-01-11 03:39:11 +00004250
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004251 if (PyArg_ParseTupleAndKeywords(args, kw, "O!O!:combine", keywords,
4252 &PyDateTime_DateType, &date,
4253 &PyDateTime_TimeType, &time)) {
4254 PyObject *tzinfo = Py_None;
Tim Petersa9bc1682003-01-11 03:39:11 +00004255
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004256 if (HASTZINFO(time))
4257 tzinfo = ((PyDateTime_Time *)time)->tzinfo;
4258 result = PyObject_CallFunction(cls, "iiiiiiiO",
4259 GET_YEAR(date),
4260 GET_MONTH(date),
4261 GET_DAY(date),
4262 TIME_GET_HOUR(time),
4263 TIME_GET_MINUTE(time),
4264 TIME_GET_SECOND(time),
4265 TIME_GET_MICROSECOND(time),
4266 tzinfo);
4267 }
4268 return result;
Tim Petersa9bc1682003-01-11 03:39:11 +00004269}
Tim Peters2a799bf2002-12-16 20:18:38 +00004270
4271/*
4272 * Destructor.
4273 */
4274
4275static void
Tim Petersa9bc1682003-01-11 03:39:11 +00004276datetime_dealloc(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004277{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004278 if (HASTZINFO(self)) {
4279 Py_XDECREF(self->tzinfo);
4280 }
4281 Py_TYPE(self)->tp_free((PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00004282}
4283
4284/*
4285 * Indirect access to tzinfo methods.
4286 */
4287
Tim Peters2a799bf2002-12-16 20:18:38 +00004288/* These are all METH_NOARGS, so don't need to check the arglist. */
4289static PyObject *
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004290datetime_utcoffset(PyObject *self, PyObject *unused) {
4291 return call_utcoffset(GET_DT_TZINFO(self), self);
Tim Peters2a799bf2002-12-16 20:18:38 +00004292}
4293
4294static PyObject *
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004295datetime_dst(PyObject *self, PyObject *unused) {
4296 return call_dst(GET_DT_TZINFO(self), self);
Tim Peters855fe882002-12-22 03:43:39 +00004297}
4298
4299static PyObject *
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004300datetime_tzname(PyObject *self, PyObject *unused) {
4301 return call_tzname(GET_DT_TZINFO(self), self);
Tim Peters2a799bf2002-12-16 20:18:38 +00004302}
4303
4304/*
Tim Petersa9bc1682003-01-11 03:39:11 +00004305 * datetime arithmetic.
Tim Peters2a799bf2002-12-16 20:18:38 +00004306 */
4307
Tim Petersa9bc1682003-01-11 03:39:11 +00004308/* factor must be 1 (to add) or -1 (to subtract). The result inherits
4309 * the tzinfo state of date.
Tim Peters2a799bf2002-12-16 20:18:38 +00004310 */
4311static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004312add_datetime_timedelta(PyDateTime_DateTime *date, PyDateTime_Delta *delta,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004313 int factor)
Tim Peters2a799bf2002-12-16 20:18:38 +00004314{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004315 /* Note that the C-level additions can't overflow, because of
4316 * invariant bounds on the member values.
4317 */
4318 int year = GET_YEAR(date);
4319 int month = GET_MONTH(date);
4320 int day = GET_DAY(date) + GET_TD_DAYS(delta) * factor;
4321 int hour = DATE_GET_HOUR(date);
4322 int minute = DATE_GET_MINUTE(date);
4323 int second = DATE_GET_SECOND(date) + GET_TD_SECONDS(delta) * factor;
4324 int microsecond = DATE_GET_MICROSECOND(date) +
4325 GET_TD_MICROSECONDS(delta) * factor;
Tim Peters2a799bf2002-12-16 20:18:38 +00004326
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004327 assert(factor == 1 || factor == -1);
4328 if (normalize_datetime(&year, &month, &day,
4329 &hour, &minute, &second, &microsecond) < 0)
4330 return NULL;
4331 else
4332 return new_datetime(year, month, day,
4333 hour, minute, second, microsecond,
4334 HASTZINFO(date) ? date->tzinfo : Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004335}
4336
4337static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004338datetime_add(PyObject *left, PyObject *right)
Tim Peters2a799bf2002-12-16 20:18:38 +00004339{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004340 if (PyDateTime_Check(left)) {
4341 /* datetime + ??? */
4342 if (PyDelta_Check(right))
4343 /* datetime + delta */
4344 return add_datetime_timedelta(
4345 (PyDateTime_DateTime *)left,
4346 (PyDateTime_Delta *)right,
4347 1);
4348 }
4349 else if (PyDelta_Check(left)) {
4350 /* delta + datetime */
4351 return add_datetime_timedelta((PyDateTime_DateTime *) right,
4352 (PyDateTime_Delta *) left,
4353 1);
4354 }
Brian Curtindfc80e32011-08-10 20:28:54 -05004355 Py_RETURN_NOTIMPLEMENTED;
Tim Peters2a799bf2002-12-16 20:18:38 +00004356}
4357
4358static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004359datetime_subtract(PyObject *left, PyObject *right)
Tim Peters2a799bf2002-12-16 20:18:38 +00004360{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004361 PyObject *result = Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00004362
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004363 if (PyDateTime_Check(left)) {
4364 /* datetime - ??? */
4365 if (PyDateTime_Check(right)) {
4366 /* datetime - datetime */
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004367 PyObject *offset1, *offset2, *offdiff = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004368 int delta_d, delta_s, delta_us;
Tim Peters2a799bf2002-12-16 20:18:38 +00004369
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004370 if (GET_DT_TZINFO(left) == GET_DT_TZINFO(right)) {
4371 offset2 = offset1 = Py_None;
4372 Py_INCREF(offset1);
4373 Py_INCREF(offset2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004374 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004375 else {
4376 offset1 = datetime_utcoffset(left, NULL);
4377 if (offset1 == NULL)
4378 return NULL;
4379 offset2 = datetime_utcoffset(right, NULL);
4380 if (offset2 == NULL) {
4381 Py_DECREF(offset1);
4382 return NULL;
4383 }
4384 if ((offset1 != Py_None) != (offset2 != Py_None)) {
4385 PyErr_SetString(PyExc_TypeError,
4386 "can't subtract offset-naive and "
4387 "offset-aware datetimes");
4388 Py_DECREF(offset1);
4389 Py_DECREF(offset2);
4390 return NULL;
4391 }
4392 }
4393 if ((offset1 != offset2) &&
4394 delta_cmp(offset1, offset2) != 0) {
4395 offdiff = delta_subtract(offset1, offset2);
4396 if (offdiff == NULL) {
4397 Py_DECREF(offset1);
4398 Py_DECREF(offset2);
4399 return NULL;
4400 }
4401 }
4402 Py_DECREF(offset1);
4403 Py_DECREF(offset2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004404 delta_d = ymd_to_ord(GET_YEAR(left),
4405 GET_MONTH(left),
4406 GET_DAY(left)) -
4407 ymd_to_ord(GET_YEAR(right),
4408 GET_MONTH(right),
4409 GET_DAY(right));
4410 /* These can't overflow, since the values are
4411 * normalized. At most this gives the number of
4412 * seconds in one day.
4413 */
4414 delta_s = (DATE_GET_HOUR(left) -
4415 DATE_GET_HOUR(right)) * 3600 +
4416 (DATE_GET_MINUTE(left) -
4417 DATE_GET_MINUTE(right)) * 60 +
4418 (DATE_GET_SECOND(left) -
4419 DATE_GET_SECOND(right));
4420 delta_us = DATE_GET_MICROSECOND(left) -
4421 DATE_GET_MICROSECOND(right);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004422 result = new_delta(delta_d, delta_s, delta_us, 1);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004423 if (offdiff != NULL) {
4424 PyObject *temp = result;
4425 result = delta_subtract(result, offdiff);
4426 Py_DECREF(temp);
4427 Py_DECREF(offdiff);
4428 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004429 }
4430 else if (PyDelta_Check(right)) {
4431 /* datetime - delta */
4432 result = add_datetime_timedelta(
4433 (PyDateTime_DateTime *)left,
4434 (PyDateTime_Delta *)right,
4435 -1);
4436 }
4437 }
Tim Peters2a799bf2002-12-16 20:18:38 +00004438
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004439 if (result == Py_NotImplemented)
4440 Py_INCREF(result);
4441 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00004442}
4443
4444/* Various ways to turn a datetime into a string. */
4445
4446static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004447datetime_repr(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004448{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004449 const char *type_name = Py_TYPE(self)->tp_name;
4450 PyObject *baserepr;
Tim Peters2a799bf2002-12-16 20:18:38 +00004451
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004452 if (DATE_GET_MICROSECOND(self)) {
4453 baserepr = PyUnicode_FromFormat(
4454 "%s(%d, %d, %d, %d, %d, %d, %d)",
4455 type_name,
4456 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4457 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4458 DATE_GET_SECOND(self),
4459 DATE_GET_MICROSECOND(self));
4460 }
4461 else if (DATE_GET_SECOND(self)) {
4462 baserepr = PyUnicode_FromFormat(
4463 "%s(%d, %d, %d, %d, %d, %d)",
4464 type_name,
4465 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4466 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4467 DATE_GET_SECOND(self));
4468 }
4469 else {
4470 baserepr = PyUnicode_FromFormat(
4471 "%s(%d, %d, %d, %d, %d)",
4472 type_name,
4473 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4474 DATE_GET_HOUR(self), DATE_GET_MINUTE(self));
4475 }
4476 if (baserepr == NULL || ! HASTZINFO(self))
4477 return baserepr;
4478 return append_keyword_tzinfo(baserepr, self->tzinfo);
Tim Peters2a799bf2002-12-16 20:18:38 +00004479}
4480
Tim Petersa9bc1682003-01-11 03:39:11 +00004481static PyObject *
4482datetime_str(PyDateTime_DateTime *self)
4483{
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02004484 _Py_IDENTIFIER(isoformat);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02004485
4486 return _PyObject_CallMethodId((PyObject *)self, &PyId_isoformat, "(s)", " ");
Tim Petersa9bc1682003-01-11 03:39:11 +00004487}
Tim Peters2a799bf2002-12-16 20:18:38 +00004488
4489static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004490datetime_isoformat(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00004491{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004492 int sep = 'T';
4493 static char *keywords[] = {"sep", NULL};
4494 char buffer[100];
4495 PyObject *result;
4496 int us = DATE_GET_MICROSECOND(self);
Tim Peters2a799bf2002-12-16 20:18:38 +00004497
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004498 if (!PyArg_ParseTupleAndKeywords(args, kw, "|C:isoformat", keywords, &sep))
4499 return NULL;
4500 if (us)
4501 result = PyUnicode_FromFormat("%04d-%02d-%02d%c%02d:%02d:%02d.%06d",
4502 GET_YEAR(self), GET_MONTH(self),
4503 GET_DAY(self), (int)sep,
4504 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4505 DATE_GET_SECOND(self), us);
4506 else
4507 result = PyUnicode_FromFormat("%04d-%02d-%02d%c%02d:%02d:%02d",
4508 GET_YEAR(self), GET_MONTH(self),
4509 GET_DAY(self), (int)sep,
4510 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4511 DATE_GET_SECOND(self));
Walter Dörwaldbafa1372007-05-31 17:50:48 +00004512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004513 if (!result || !HASTZINFO(self))
4514 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00004515
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004516 /* We need to append the UTC offset. */
4517 if (format_utcoffset(buffer, sizeof(buffer), ":", self->tzinfo,
4518 (PyObject *)self) < 0) {
4519 Py_DECREF(result);
4520 return NULL;
4521 }
4522 PyUnicode_AppendAndDel(&result, PyUnicode_FromString(buffer));
4523 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00004524}
4525
Tim Petersa9bc1682003-01-11 03:39:11 +00004526static PyObject *
4527datetime_ctime(PyDateTime_DateTime *self)
4528{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004529 return format_ctime((PyDateTime_Date *)self,
4530 DATE_GET_HOUR(self),
4531 DATE_GET_MINUTE(self),
4532 DATE_GET_SECOND(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00004533}
4534
Tim Peters2a799bf2002-12-16 20:18:38 +00004535/* Miscellaneous methods. */
4536
Tim Petersa9bc1682003-01-11 03:39:11 +00004537static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00004538datetime_richcompare(PyObject *self, PyObject *other, int op)
Tim Petersa9bc1682003-01-11 03:39:11 +00004539{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004540 PyObject *result = NULL;
4541 PyObject *offset1, *offset2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004542 int diff;
Tim Petersa9bc1682003-01-11 03:39:11 +00004543
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004544 if (! PyDateTime_Check(other)) {
4545 if (PyDate_Check(other)) {
4546 /* Prevent invocation of date_richcompare. We want to
4547 return NotImplemented here to give the other object
4548 a chance. But since DateTime is a subclass of
4549 Date, if the other object is a Date, it would
4550 compute an ordering based on the date part alone,
4551 and we don't want that. So force unequal or
4552 uncomparable here in that case. */
4553 if (op == Py_EQ)
4554 Py_RETURN_FALSE;
4555 if (op == Py_NE)
4556 Py_RETURN_TRUE;
4557 return cmperror(self, other);
4558 }
Brian Curtindfc80e32011-08-10 20:28:54 -05004559 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004560 }
Tim Petersa9bc1682003-01-11 03:39:11 +00004561
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004562 if (GET_DT_TZINFO(self) == GET_DT_TZINFO(other)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004563 diff = memcmp(((PyDateTime_DateTime *)self)->data,
4564 ((PyDateTime_DateTime *)other)->data,
4565 _PyDateTime_DATETIME_DATASIZE);
4566 return diff_to_bool(diff, op);
4567 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004568 offset1 = datetime_utcoffset(self, NULL);
4569 if (offset1 == NULL)
4570 return NULL;
4571 offset2 = datetime_utcoffset(other, NULL);
4572 if (offset2 == NULL)
4573 goto done;
4574 /* If they're both naive, or both aware and have the same offsets,
4575 * we get off cheap. Note that if they're both naive, offset1 ==
4576 * offset2 == Py_None at this point.
4577 */
4578 if ((offset1 == offset2) ||
4579 (PyDelta_Check(offset1) && PyDelta_Check(offset2) &&
4580 delta_cmp(offset1, offset2) == 0)) {
4581 diff = memcmp(((PyDateTime_DateTime *)self)->data,
4582 ((PyDateTime_DateTime *)other)->data,
4583 _PyDateTime_DATETIME_DATASIZE);
4584 result = diff_to_bool(diff, op);
4585 }
4586 else if (offset1 != Py_None && offset2 != Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004587 PyDateTime_Delta *delta;
Tim Petersa9bc1682003-01-11 03:39:11 +00004588
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004589 assert(offset1 != offset2); /* else last "if" handled it */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004590 delta = (PyDateTime_Delta *)datetime_subtract((PyObject *)self,
4591 other);
4592 if (delta == NULL)
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004593 goto done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004594 diff = GET_TD_DAYS(delta);
4595 if (diff == 0)
4596 diff = GET_TD_SECONDS(delta) |
4597 GET_TD_MICROSECONDS(delta);
4598 Py_DECREF(delta);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004599 result = diff_to_bool(diff, op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004600 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004601 else {
4602 PyErr_SetString(PyExc_TypeError,
4603 "can't compare offset-naive and "
4604 "offset-aware datetimes");
4605 }
4606 done:
4607 Py_DECREF(offset1);
4608 Py_XDECREF(offset2);
4609 return result;
Tim Petersa9bc1682003-01-11 03:39:11 +00004610}
4611
Benjamin Peterson8f67d082010-10-17 20:54:53 +00004612static Py_hash_t
Tim Petersa9bc1682003-01-11 03:39:11 +00004613datetime_hash(PyDateTime_DateTime *self)
4614{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004615 if (self->hashcode == -1) {
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004616 PyObject *offset;
Tim Petersa9bc1682003-01-11 03:39:11 +00004617
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004618 offset = datetime_utcoffset((PyObject *)self, NULL);
4619
4620 if (offset == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004621 return -1;
Tim Petersa9bc1682003-01-11 03:39:11 +00004622
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004623 /* Reduce this to a hash of another object. */
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004624 if (offset == Py_None)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004625 self->hashcode = generic_hash(
4626 (unsigned char *)self->data, _PyDateTime_DATETIME_DATASIZE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004627 else {
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004628 PyObject *temp1, *temp2;
4629 int days, seconds;
Tim Petersa9bc1682003-01-11 03:39:11 +00004630
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004631 assert(HASTZINFO(self));
4632 days = ymd_to_ord(GET_YEAR(self),
4633 GET_MONTH(self),
4634 GET_DAY(self));
4635 seconds = DATE_GET_HOUR(self) * 3600 +
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004636 DATE_GET_MINUTE(self) * 60 +
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004637 DATE_GET_SECOND(self);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004638 temp1 = new_delta(days, seconds,
4639 DATE_GET_MICROSECOND(self),
4640 1);
4641 if (temp1 == NULL) {
4642 Py_DECREF(offset);
4643 return -1;
4644 }
4645 temp2 = delta_subtract(temp1, offset);
4646 Py_DECREF(temp1);
4647 if (temp2 == NULL) {
4648 Py_DECREF(offset);
4649 return -1;
4650 }
4651 self->hashcode = PyObject_Hash(temp2);
4652 Py_DECREF(temp2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004653 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004654 Py_DECREF(offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004655 }
4656 return self->hashcode;
Tim Petersa9bc1682003-01-11 03:39:11 +00004657}
Tim Peters2a799bf2002-12-16 20:18:38 +00004658
4659static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004660datetime_replace(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters12bf3392002-12-24 05:41:27 +00004661{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004662 PyObject *clone;
4663 PyObject *tuple;
4664 int y = GET_YEAR(self);
4665 int m = GET_MONTH(self);
4666 int d = GET_DAY(self);
4667 int hh = DATE_GET_HOUR(self);
4668 int mm = DATE_GET_MINUTE(self);
4669 int ss = DATE_GET_SECOND(self);
4670 int us = DATE_GET_MICROSECOND(self);
4671 PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
Tim Peters12bf3392002-12-24 05:41:27 +00004672
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004673 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiiiiO:replace",
4674 datetime_kws,
4675 &y, &m, &d, &hh, &mm, &ss, &us,
4676 &tzinfo))
4677 return NULL;
4678 tuple = Py_BuildValue("iiiiiiiO", y, m, d, hh, mm, ss, us, tzinfo);
4679 if (tuple == NULL)
4680 return NULL;
4681 clone = datetime_new(Py_TYPE(self), tuple, NULL);
4682 Py_DECREF(tuple);
4683 return clone;
Tim Peters12bf3392002-12-24 05:41:27 +00004684}
4685
4686static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004687datetime_astimezone(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters80475bb2002-12-25 07:40:55 +00004688{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004689 PyObject *result;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004690 PyObject *offset;
4691 PyObject *temp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004692 PyObject *tzinfo;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02004693 _Py_IDENTIFIER(fromutc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004694 static char *keywords[] = {"tz", NULL};
Tim Peters80475bb2002-12-25 07:40:55 +00004695
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004696 if (! PyArg_ParseTupleAndKeywords(args, kw, "O!:astimezone", keywords,
4697 &PyDateTime_TZInfoType, &tzinfo))
4698 return NULL;
Tim Peters80475bb2002-12-25 07:40:55 +00004699
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004700 if (!HASTZINFO(self) || self->tzinfo == Py_None)
4701 goto NeedAware;
Tim Peters521fc152002-12-31 17:36:56 +00004702
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004703 /* Conversion to self's own time zone is a NOP. */
4704 if (self->tzinfo == tzinfo) {
4705 Py_INCREF(self);
4706 return (PyObject *)self;
4707 }
Tim Peters521fc152002-12-31 17:36:56 +00004708
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004709 /* Convert self to UTC. */
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004710 offset = datetime_utcoffset((PyObject *)self, NULL);
4711 if (offset == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004712 return NULL;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004713 if (offset == Py_None) {
4714 Py_DECREF(offset);
4715 NeedAware:
4716 PyErr_SetString(PyExc_ValueError, "astimezone() cannot be applied to "
4717 "a naive datetime");
4718 return NULL;
4719 }
Tim Petersf3615152003-01-01 21:51:37 +00004720
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004721 /* result = self - offset */
4722 result = add_datetime_timedelta(self,
4723 (PyDateTime_Delta *)offset, -1);
4724 Py_DECREF(offset);
4725 if (result == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004726 return NULL;
Tim Peters52dcce22003-01-23 16:36:11 +00004727
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004728 /* Attach new tzinfo and let fromutc() do the rest. */
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004729 temp = ((PyDateTime_DateTime *)result)->tzinfo;
4730 ((PyDateTime_DateTime *)result)->tzinfo = tzinfo;
4731 Py_INCREF(tzinfo);
4732 Py_DECREF(temp);
Tim Peters52dcce22003-01-23 16:36:11 +00004733
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004734 temp = result;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02004735 result = _PyObject_CallMethodId(tzinfo, &PyId_fromutc, "O", temp);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004736 Py_DECREF(temp);
4737
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004738 return result;
Tim Peters80475bb2002-12-25 07:40:55 +00004739}
4740
4741static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004742datetime_timetuple(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004743{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004744 int dstflag = -1;
Tim Peters2a799bf2002-12-16 20:18:38 +00004745
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004746 if (HASTZINFO(self) && self->tzinfo != Py_None) {
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004747 PyObject * dst;
Tim Peters2a799bf2002-12-16 20:18:38 +00004748
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004749 dst = call_dst(self->tzinfo, (PyObject *)self);
4750 if (dst == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004751 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004752
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004753 if (dst != Py_None)
4754 dstflag = delta_bool((PyDateTime_Delta *)dst);
4755 Py_DECREF(dst);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004756 }
4757 return build_struct_time(GET_YEAR(self),
4758 GET_MONTH(self),
4759 GET_DAY(self),
4760 DATE_GET_HOUR(self),
4761 DATE_GET_MINUTE(self),
4762 DATE_GET_SECOND(self),
4763 dstflag);
Tim Peters2a799bf2002-12-16 20:18:38 +00004764}
4765
4766static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004767datetime_getdate(PyDateTime_DateTime *self)
4768{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004769 return new_date(GET_YEAR(self),
4770 GET_MONTH(self),
4771 GET_DAY(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00004772}
4773
4774static PyObject *
4775datetime_gettime(PyDateTime_DateTime *self)
4776{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004777 return new_time(DATE_GET_HOUR(self),
4778 DATE_GET_MINUTE(self),
4779 DATE_GET_SECOND(self),
4780 DATE_GET_MICROSECOND(self),
4781 Py_None);
Tim Petersa9bc1682003-01-11 03:39:11 +00004782}
4783
4784static PyObject *
4785datetime_gettimetz(PyDateTime_DateTime *self)
4786{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004787 return new_time(DATE_GET_HOUR(self),
4788 DATE_GET_MINUTE(self),
4789 DATE_GET_SECOND(self),
4790 DATE_GET_MICROSECOND(self),
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004791 GET_DT_TZINFO(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00004792}
4793
4794static PyObject *
4795datetime_utctimetuple(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004796{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004797 int y, m, d, hh, mm, ss;
4798 PyObject *tzinfo;
4799 PyDateTime_DateTime *utcself;
Tim Peters2a799bf2002-12-16 20:18:38 +00004800
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004801 tzinfo = GET_DT_TZINFO(self);
4802 if (tzinfo == Py_None) {
4803 utcself = self;
4804 Py_INCREF(utcself);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004805 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004806 else {
4807 PyObject *offset;
4808 offset = call_utcoffset(tzinfo, (PyObject *)self);
4809 if (offset == NULL)
Alexander Belopolsky75f94c22010-06-21 15:21:14 +00004810 return NULL;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004811 if (offset == Py_None) {
4812 Py_DECREF(offset);
4813 utcself = self;
4814 Py_INCREF(utcself);
4815 }
4816 else {
4817 utcself = (PyDateTime_DateTime *)add_datetime_timedelta(self,
4818 (PyDateTime_Delta *)offset, -1);
4819 Py_DECREF(offset);
4820 if (utcself == NULL)
4821 return NULL;
4822 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004823 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004824 y = GET_YEAR(utcself);
4825 m = GET_MONTH(utcself);
4826 d = GET_DAY(utcself);
4827 hh = DATE_GET_HOUR(utcself);
4828 mm = DATE_GET_MINUTE(utcself);
4829 ss = DATE_GET_SECOND(utcself);
4830
4831 Py_DECREF(utcself);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004832 return build_struct_time(y, m, d, hh, mm, ss, 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00004833}
4834
Tim Peters371935f2003-02-01 01:52:50 +00004835/* Pickle support, a simple use of __reduce__. */
Tim Peters33e0f382003-01-10 02:05:14 +00004836
Tim Petersa9bc1682003-01-11 03:39:11 +00004837/* Let basestate be the non-tzinfo data string.
Tim Peters2a799bf2002-12-16 20:18:38 +00004838 * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
4839 * So it's a tuple in any (non-error) case.
Tim Petersb57f8f02003-02-01 02:54:15 +00004840 * __getstate__ isn't exposed.
Tim Peters2a799bf2002-12-16 20:18:38 +00004841 */
4842static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004843datetime_getstate(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004844{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004845 PyObject *basestate;
4846 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004847
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004848 basestate = PyBytes_FromStringAndSize((char *)self->data,
4849 _PyDateTime_DATETIME_DATASIZE);
4850 if (basestate != NULL) {
4851 if (! HASTZINFO(self) || self->tzinfo == Py_None)
4852 result = PyTuple_Pack(1, basestate);
4853 else
4854 result = PyTuple_Pack(2, basestate, self->tzinfo);
4855 Py_DECREF(basestate);
4856 }
4857 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00004858}
4859
4860static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00004861datetime_reduce(PyDateTime_DateTime *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00004862{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004863 return Py_BuildValue("(ON)", Py_TYPE(self), datetime_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00004864}
4865
Tim Petersa9bc1682003-01-11 03:39:11 +00004866static PyMethodDef datetime_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00004867
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004868 /* Class methods: */
Tim Peters2a799bf2002-12-16 20:18:38 +00004869
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004870 {"now", (PyCFunction)datetime_now,
4871 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
4872 PyDoc_STR("[tz] -> new datetime with tz's local day and time.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004873
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004874 {"utcnow", (PyCFunction)datetime_utcnow,
4875 METH_NOARGS | METH_CLASS,
4876 PyDoc_STR("Return a new datetime representing UTC day and time.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00004877
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004878 {"fromtimestamp", (PyCFunction)datetime_fromtimestamp,
4879 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
4880 PyDoc_STR("timestamp[, tz] -> tz's local time from POSIX timestamp.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004881
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004882 {"utcfromtimestamp", (PyCFunction)datetime_utcfromtimestamp,
4883 METH_VARARGS | METH_CLASS,
4884 PyDoc_STR("timestamp -> UTC datetime from a POSIX timestamp "
4885 "(like time.time()).")},
Tim Petersa9bc1682003-01-11 03:39:11 +00004886
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004887 {"strptime", (PyCFunction)datetime_strptime,
4888 METH_VARARGS | METH_CLASS,
4889 PyDoc_STR("string, format -> new datetime parsed from a string "
4890 "(like time.strptime()).")},
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004891
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004892 {"combine", (PyCFunction)datetime_combine,
4893 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
4894 PyDoc_STR("date, time -> datetime with same date and time fields")},
Tim Petersa9bc1682003-01-11 03:39:11 +00004895
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004896 /* Instance methods: */
Guido van Rossum177e41a2003-01-30 22:06:23 +00004897
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004898 {"date", (PyCFunction)datetime_getdate, METH_NOARGS,
4899 PyDoc_STR("Return date object with same year, month and day.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00004900
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004901 {"time", (PyCFunction)datetime_gettime, METH_NOARGS,
4902 PyDoc_STR("Return time object with same time but with tzinfo=None.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00004903
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004904 {"timetz", (PyCFunction)datetime_gettimetz, METH_NOARGS,
4905 PyDoc_STR("Return time object with same time and tzinfo.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00004906
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004907 {"ctime", (PyCFunction)datetime_ctime, METH_NOARGS,
4908 PyDoc_STR("Return ctime() style string.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00004909
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004910 {"timetuple", (PyCFunction)datetime_timetuple, METH_NOARGS,
4911 PyDoc_STR("Return time tuple, compatible with time.localtime().")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004912
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004913 {"utctimetuple", (PyCFunction)datetime_utctimetuple, METH_NOARGS,
4914 PyDoc_STR("Return UTC time tuple, compatible with time.localtime().")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004915
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004916 {"isoformat", (PyCFunction)datetime_isoformat, METH_VARARGS | METH_KEYWORDS,
4917 PyDoc_STR("[sep] -> string in ISO 8601 format, "
4918 "YYYY-MM-DDTHH:MM:SS[.mmmmmm][+HH:MM].\n\n"
4919 "sep is used to separate the year from the time, and "
4920 "defaults to 'T'.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004921
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004922 {"utcoffset", (PyCFunction)datetime_utcoffset, METH_NOARGS,
4923 PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004924
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004925 {"tzname", (PyCFunction)datetime_tzname, METH_NOARGS,
4926 PyDoc_STR("Return self.tzinfo.tzname(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004927
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004928 {"dst", (PyCFunction)datetime_dst, METH_NOARGS,
4929 PyDoc_STR("Return self.tzinfo.dst(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004930
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004931 {"replace", (PyCFunction)datetime_replace, METH_VARARGS | METH_KEYWORDS,
4932 PyDoc_STR("Return datetime with new specified fields.")},
Tim Peters12bf3392002-12-24 05:41:27 +00004933
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004934 {"astimezone", (PyCFunction)datetime_astimezone, METH_VARARGS | METH_KEYWORDS,
4935 PyDoc_STR("tz -> convert to local time in new timezone tz\n")},
Tim Peters80475bb2002-12-25 07:40:55 +00004936
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004937 {"__reduce__", (PyCFunction)datetime_reduce, METH_NOARGS,
4938 PyDoc_STR("__reduce__() -> (cls, state)")},
Guido van Rossum177e41a2003-01-30 22:06:23 +00004939
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004940 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00004941};
4942
Tim Petersa9bc1682003-01-11 03:39:11 +00004943static char datetime_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00004944PyDoc_STR("datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]])\n\
4945\n\
4946The year, month and day arguments are required. tzinfo may be None, or an\n\
4947instance of a tzinfo subclass. The remaining arguments may be ints or longs.\n");
Tim Peters2a799bf2002-12-16 20:18:38 +00004948
Tim Petersa9bc1682003-01-11 03:39:11 +00004949static PyNumberMethods datetime_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004950 datetime_add, /* nb_add */
4951 datetime_subtract, /* nb_subtract */
4952 0, /* nb_multiply */
4953 0, /* nb_remainder */
4954 0, /* nb_divmod */
4955 0, /* nb_power */
4956 0, /* nb_negative */
4957 0, /* nb_positive */
4958 0, /* nb_absolute */
4959 0, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00004960};
4961
Neal Norwitz227b5332006-03-22 09:28:35 +00004962static PyTypeObject PyDateTime_DateTimeType = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004963 PyVarObject_HEAD_INIT(NULL, 0)
4964 "datetime.datetime", /* tp_name */
4965 sizeof(PyDateTime_DateTime), /* tp_basicsize */
4966 0, /* tp_itemsize */
4967 (destructor)datetime_dealloc, /* tp_dealloc */
4968 0, /* tp_print */
4969 0, /* tp_getattr */
4970 0, /* tp_setattr */
4971 0, /* tp_reserved */
4972 (reprfunc)datetime_repr, /* tp_repr */
4973 &datetime_as_number, /* tp_as_number */
4974 0, /* tp_as_sequence */
4975 0, /* tp_as_mapping */
4976 (hashfunc)datetime_hash, /* tp_hash */
4977 0, /* tp_call */
4978 (reprfunc)datetime_str, /* tp_str */
4979 PyObject_GenericGetAttr, /* tp_getattro */
4980 0, /* tp_setattro */
4981 0, /* tp_as_buffer */
4982 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
4983 datetime_doc, /* tp_doc */
4984 0, /* tp_traverse */
4985 0, /* tp_clear */
4986 datetime_richcompare, /* tp_richcompare */
4987 0, /* tp_weaklistoffset */
4988 0, /* tp_iter */
4989 0, /* tp_iternext */
4990 datetime_methods, /* tp_methods */
4991 0, /* tp_members */
4992 datetime_getset, /* tp_getset */
4993 &PyDateTime_DateType, /* tp_base */
4994 0, /* tp_dict */
4995 0, /* tp_descr_get */
4996 0, /* tp_descr_set */
4997 0, /* tp_dictoffset */
4998 0, /* tp_init */
4999 datetime_alloc, /* tp_alloc */
5000 datetime_new, /* tp_new */
5001 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00005002};
5003
5004/* ---------------------------------------------------------------------------
5005 * Module methods and initialization.
5006 */
5007
5008static PyMethodDef module_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005009 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00005010};
5011
Tim Peters9ddf40b2004-06-20 22:41:32 +00005012/* C API. Clients get at this via PyDateTime_IMPORT, defined in
5013 * datetime.h.
5014 */
5015static PyDateTime_CAPI CAPI = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005016 &PyDateTime_DateType,
5017 &PyDateTime_DateTimeType,
5018 &PyDateTime_TimeType,
5019 &PyDateTime_DeltaType,
5020 &PyDateTime_TZInfoType,
5021 new_date_ex,
5022 new_datetime_ex,
5023 new_time_ex,
5024 new_delta_ex,
5025 datetime_fromtimestamp,
5026 date_fromtimestamp
Tim Peters9ddf40b2004-06-20 22:41:32 +00005027};
5028
5029
Martin v. Löwis1a214512008-06-11 05:26:20 +00005030
5031static struct PyModuleDef datetimemodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005032 PyModuleDef_HEAD_INIT,
Alexander Belopolskycf86e362010-07-23 19:25:47 +00005033 "_datetime",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005034 "Fast implementation of the datetime type.",
5035 -1,
5036 module_methods,
5037 NULL,
5038 NULL,
5039 NULL,
5040 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00005041};
5042
Tim Peters2a799bf2002-12-16 20:18:38 +00005043PyMODINIT_FUNC
Alexander Belopolskycf86e362010-07-23 19:25:47 +00005044PyInit__datetime(void)
Tim Peters2a799bf2002-12-16 20:18:38 +00005045{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005046 PyObject *m; /* a module object */
5047 PyObject *d; /* its dict */
5048 PyObject *x;
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00005049 PyObject *delta;
Tim Peters2a799bf2002-12-16 20:18:38 +00005050
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005051 m = PyModule_Create(&datetimemodule);
5052 if (m == NULL)
5053 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00005054
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005055 if (PyType_Ready(&PyDateTime_DateType) < 0)
5056 return NULL;
5057 if (PyType_Ready(&PyDateTime_DateTimeType) < 0)
5058 return NULL;
5059 if (PyType_Ready(&PyDateTime_DeltaType) < 0)
5060 return NULL;
5061 if (PyType_Ready(&PyDateTime_TimeType) < 0)
5062 return NULL;
5063 if (PyType_Ready(&PyDateTime_TZInfoType) < 0)
5064 return NULL;
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00005065 if (PyType_Ready(&PyDateTime_TimeZoneType) < 0)
5066 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00005067
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005068 /* timedelta values */
5069 d = PyDateTime_DeltaType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00005070
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005071 x = new_delta(0, 0, 1, 0);
5072 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
5073 return NULL;
5074 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005075
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005076 x = new_delta(-MAX_DELTA_DAYS, 0, 0, 0);
5077 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
5078 return NULL;
5079 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005080
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005081 x = new_delta(MAX_DELTA_DAYS, 24*3600-1, 1000000-1, 0);
5082 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
5083 return NULL;
5084 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005085
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005086 /* date values */
5087 d = PyDateTime_DateType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00005088
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005089 x = new_date(1, 1, 1);
5090 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
5091 return NULL;
5092 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005093
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005094 x = new_date(MAXYEAR, 12, 31);
5095 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
5096 return NULL;
5097 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005098
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005099 x = new_delta(1, 0, 0, 0);
5100 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
5101 return NULL;
5102 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005103
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005104 /* time values */
5105 d = PyDateTime_TimeType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00005106
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005107 x = new_time(0, 0, 0, 0, Py_None);
5108 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
5109 return NULL;
5110 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005112 x = new_time(23, 59, 59, 999999, Py_None);
5113 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
5114 return NULL;
5115 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005116
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005117 x = new_delta(0, 0, 1, 0);
5118 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
5119 return NULL;
5120 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005121
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005122 /* datetime values */
5123 d = PyDateTime_DateTimeType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00005124
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005125 x = new_datetime(1, 1, 1, 0, 0, 0, 0, Py_None);
5126 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
5127 return NULL;
5128 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005129
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005130 x = new_datetime(MAXYEAR, 12, 31, 23, 59, 59, 999999, Py_None);
5131 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
5132 return NULL;
5133 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005134
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005135 x = new_delta(0, 0, 1, 0);
5136 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
5137 return NULL;
5138 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005139
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00005140 /* timezone values */
5141 d = PyDateTime_TimeZoneType.tp_dict;
5142
5143 delta = new_delta(0, 0, 0, 0);
5144 if (delta == NULL)
5145 return NULL;
Alexander Belopolsky1bcbaab2010-10-14 17:03:51 +00005146 x = create_timezone(delta, NULL);
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00005147 Py_DECREF(delta);
5148 if (x == NULL || PyDict_SetItemString(d, "utc", x) < 0)
5149 return NULL;
Alexander Belopolskya11d8c02010-07-06 23:19:45 +00005150 PyDateTime_TimeZone_UTC = x;
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00005151
5152 delta = new_delta(-1, 60, 0, 1); /* -23:59 */
5153 if (delta == NULL)
5154 return NULL;
Alexander Belopolsky1bcbaab2010-10-14 17:03:51 +00005155 x = create_timezone(delta, NULL);
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00005156 Py_DECREF(delta);
5157 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
5158 return NULL;
5159 Py_DECREF(x);
5160
5161 delta = new_delta(0, (23 * 60 + 59) * 60, 0, 0); /* +23:59 */
5162 if (delta == NULL)
5163 return NULL;
Alexander Belopolsky1bcbaab2010-10-14 17:03:51 +00005164 x = create_timezone(delta, NULL);
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00005165 Py_DECREF(delta);
5166 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
5167 return NULL;
5168 Py_DECREF(x);
5169
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005170 /* module initialization */
5171 PyModule_AddIntConstant(m, "MINYEAR", MINYEAR);
5172 PyModule_AddIntConstant(m, "MAXYEAR", MAXYEAR);
Tim Peters2a799bf2002-12-16 20:18:38 +00005173
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005174 Py_INCREF(&PyDateTime_DateType);
5175 PyModule_AddObject(m, "date", (PyObject *) &PyDateTime_DateType);
Tim Peters2a799bf2002-12-16 20:18:38 +00005176
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005177 Py_INCREF(&PyDateTime_DateTimeType);
5178 PyModule_AddObject(m, "datetime",
5179 (PyObject *)&PyDateTime_DateTimeType);
Tim Petersa9bc1682003-01-11 03:39:11 +00005180
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005181 Py_INCREF(&PyDateTime_TimeType);
5182 PyModule_AddObject(m, "time", (PyObject *) &PyDateTime_TimeType);
Tim Petersa9bc1682003-01-11 03:39:11 +00005183
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005184 Py_INCREF(&PyDateTime_DeltaType);
5185 PyModule_AddObject(m, "timedelta", (PyObject *) &PyDateTime_DeltaType);
Tim Peters2a799bf2002-12-16 20:18:38 +00005186
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005187 Py_INCREF(&PyDateTime_TZInfoType);
5188 PyModule_AddObject(m, "tzinfo", (PyObject *) &PyDateTime_TZInfoType);
Tim Peters2a799bf2002-12-16 20:18:38 +00005189
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00005190 Py_INCREF(&PyDateTime_TimeZoneType);
5191 PyModule_AddObject(m, "timezone", (PyObject *) &PyDateTime_TimeZoneType);
5192
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005193 x = PyCapsule_New(&CAPI, PyDateTime_CAPSULE_NAME, NULL);
5194 if (x == NULL)
5195 return NULL;
5196 PyModule_AddObject(m, "datetime_CAPI", x);
Tim Peters9ddf40b2004-06-20 22:41:32 +00005197
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005198 /* A 4-year cycle has an extra leap day over what we'd get from
5199 * pasting together 4 single years.
5200 */
5201 assert(DI4Y == 4 * 365 + 1);
5202 assert(DI4Y == days_before_year(4+1));
Tim Peters2a799bf2002-12-16 20:18:38 +00005203
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005204 /* Similarly, a 400-year cycle has an extra leap day over what we'd
5205 * get from pasting together 4 100-year cycles.
5206 */
5207 assert(DI400Y == 4 * DI100Y + 1);
5208 assert(DI400Y == days_before_year(400+1));
Tim Peters2a799bf2002-12-16 20:18:38 +00005209
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005210 /* OTOH, a 100-year cycle has one fewer leap day than we'd get from
5211 * pasting together 25 4-year cycles.
5212 */
5213 assert(DI100Y == 25 * DI4Y - 1);
5214 assert(DI100Y == days_before_year(100+1));
Tim Peters2a799bf2002-12-16 20:18:38 +00005215
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005216 us_per_us = PyLong_FromLong(1);
5217 us_per_ms = PyLong_FromLong(1000);
5218 us_per_second = PyLong_FromLong(1000000);
5219 us_per_minute = PyLong_FromLong(60000000);
5220 seconds_per_day = PyLong_FromLong(24 * 3600);
5221 if (us_per_us == NULL || us_per_ms == NULL || us_per_second == NULL ||
5222 us_per_minute == NULL || seconds_per_day == NULL)
5223 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00005224
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005225 /* The rest are too big for 32-bit ints, but even
5226 * us_per_week fits in 40 bits, so doubles should be exact.
5227 */
5228 us_per_hour = PyLong_FromDouble(3600000000.0);
5229 us_per_day = PyLong_FromDouble(86400000000.0);
5230 us_per_week = PyLong_FromDouble(604800000000.0);
5231 if (us_per_hour == NULL || us_per_day == NULL || us_per_week == NULL)
5232 return NULL;
5233 return m;
Tim Peters2a799bf2002-12-16 20:18:38 +00005234}
Tim Petersf3615152003-01-01 21:51:37 +00005235
5236/* ---------------------------------------------------------------------------
Tim Petersa9bc1682003-01-11 03:39:11 +00005237Some time zone algebra. For a datetime x, let
Tim Petersf3615152003-01-01 21:51:37 +00005238 x.n = x stripped of its timezone -- its naive time.
5239 x.o = x.utcoffset(), and assuming that doesn't raise an exception or
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005240 return None
Tim Petersf3615152003-01-01 21:51:37 +00005241 x.d = x.dst(), and assuming that doesn't raise an exception or
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005242 return None
Tim Petersf3615152003-01-01 21:51:37 +00005243 x.s = x's standard offset, x.o - x.d
5244
5245Now some derived rules, where k is a duration (timedelta).
5246
52471. x.o = x.s + x.d
5248 This follows from the definition of x.s.
5249
Tim Petersc5dc4da2003-01-02 17:55:03 +000052502. If x and y have the same tzinfo member, x.s = y.s.
Tim Petersf3615152003-01-01 21:51:37 +00005251 This is actually a requirement, an assumption we need to make about
5252 sane tzinfo classes.
5253
52543. The naive UTC time corresponding to x is x.n - x.o.
5255 This is again a requirement for a sane tzinfo class.
5256
52574. (x+k).s = x.s
Tim Peters8bb5ad22003-01-24 02:44:45 +00005258 This follows from #2, and that datimetimetz+timedelta preserves tzinfo.
Tim Petersf3615152003-01-01 21:51:37 +00005259
Tim Petersc5dc4da2003-01-02 17:55:03 +000052605. (x+k).n = x.n + k
Tim Petersf3615152003-01-01 21:51:37 +00005261 Again follows from how arithmetic is defined.
5262
Tim Peters8bb5ad22003-01-24 02:44:45 +00005263Now we can explain tz.fromutc(x). Let's assume it's an interesting case
Tim Petersf3615152003-01-01 21:51:37 +00005264(meaning that the various tzinfo methods exist, and don't blow up or return
5265None when called).
5266
Tim Petersa9bc1682003-01-11 03:39:11 +00005267The function wants to return a datetime y with timezone tz, equivalent to x.
Tim Peters8bb5ad22003-01-24 02:44:45 +00005268x is already in UTC.
Tim Petersf3615152003-01-01 21:51:37 +00005269
5270By #3, we want
5271
Tim Peters8bb5ad22003-01-24 02:44:45 +00005272 y.n - y.o = x.n [1]
Tim Petersf3615152003-01-01 21:51:37 +00005273
5274The algorithm starts by attaching tz to x.n, and calling that y. So
5275x.n = y.n at the start. Then it wants to add a duration k to y, so that [1]
5276becomes true; in effect, we want to solve [2] for k:
5277
Tim Peters8bb5ad22003-01-24 02:44:45 +00005278 (y+k).n - (y+k).o = x.n [2]
Tim Petersf3615152003-01-01 21:51:37 +00005279
5280By #1, this is the same as
5281
Tim Peters8bb5ad22003-01-24 02:44:45 +00005282 (y+k).n - ((y+k).s + (y+k).d) = x.n [3]
Tim Petersf3615152003-01-01 21:51:37 +00005283
5284By #5, (y+k).n = y.n + k, which equals x.n + k because x.n=y.n at the start.
5285Substituting that into [3],
5286
Tim Peters8bb5ad22003-01-24 02:44:45 +00005287 x.n + k - (y+k).s - (y+k).d = x.n; the x.n terms cancel, leaving
5288 k - (y+k).s - (y+k).d = 0; rearranging,
5289 k = (y+k).s - (y+k).d; by #4, (y+k).s == y.s, so
5290 k = y.s - (y+k).d
Tim Petersf3615152003-01-01 21:51:37 +00005291
Tim Peters8bb5ad22003-01-24 02:44:45 +00005292On the RHS, (y+k).d can't be computed directly, but y.s can be, and we
5293approximate k by ignoring the (y+k).d term at first. Note that k can't be
5294very large, since all offset-returning methods return a duration of magnitude
5295less than 24 hours. For that reason, if y is firmly in std time, (y+k).d must
5296be 0, so ignoring it has no consequence then.
Tim Petersf3615152003-01-01 21:51:37 +00005297
5298In any case, the new value is
5299
Tim Peters8bb5ad22003-01-24 02:44:45 +00005300 z = y + y.s [4]
Tim Petersf3615152003-01-01 21:51:37 +00005301
Tim Peters8bb5ad22003-01-24 02:44:45 +00005302It's helpful to step back at look at [4] from a higher level: it's simply
5303mapping from UTC to tz's standard time.
Tim Petersc5dc4da2003-01-02 17:55:03 +00005304
5305At this point, if
5306
Tim Peters8bb5ad22003-01-24 02:44:45 +00005307 z.n - z.o = x.n [5]
Tim Petersc5dc4da2003-01-02 17:55:03 +00005308
5309we have an equivalent time, and are almost done. The insecurity here is
Tim Petersf3615152003-01-01 21:51:37 +00005310at the start of daylight time. Picture US Eastern for concreteness. The wall
5311time 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 +00005312sense then. The docs ask that an Eastern tzinfo class consider such a time to
5313be EDT (because it's "after 2"), which is a redundant spelling of 1:MM EST
5314on the day DST starts. We want to return the 1:MM EST spelling because that's
Tim Petersf3615152003-01-01 21:51:37 +00005315the only spelling that makes sense on the local wall clock.
5316
Tim Petersc5dc4da2003-01-02 17:55:03 +00005317In fact, if [5] holds at this point, we do have the standard-time spelling,
5318but that takes a bit of proof. We first prove a stronger result. What's the
5319difference between the LHS and RHS of [5]? Let
Tim Petersf3615152003-01-01 21:51:37 +00005320
Tim Peters8bb5ad22003-01-24 02:44:45 +00005321 diff = x.n - (z.n - z.o) [6]
Tim Petersf3615152003-01-01 21:51:37 +00005322
Tim Petersc5dc4da2003-01-02 17:55:03 +00005323Now
5324 z.n = by [4]
Tim Peters8bb5ad22003-01-24 02:44:45 +00005325 (y + y.s).n = by #5
5326 y.n + y.s = since y.n = x.n
5327 x.n + y.s = since z and y are have the same tzinfo member,
5328 y.s = z.s by #2
5329 x.n + z.s
Tim Petersf3615152003-01-01 21:51:37 +00005330
Tim Petersc5dc4da2003-01-02 17:55:03 +00005331Plugging that back into [6] gives
Tim Petersf3615152003-01-01 21:51:37 +00005332
Tim Petersc5dc4da2003-01-02 17:55:03 +00005333 diff =
Tim Peters8bb5ad22003-01-24 02:44:45 +00005334 x.n - ((x.n + z.s) - z.o) = expanding
5335 x.n - x.n - z.s + z.o = cancelling
5336 - z.s + z.o = by #2
Tim Petersc5dc4da2003-01-02 17:55:03 +00005337 z.d
Tim Petersf3615152003-01-01 21:51:37 +00005338
Tim Petersc5dc4da2003-01-02 17:55:03 +00005339So diff = z.d.
Tim Petersf3615152003-01-01 21:51:37 +00005340
Tim Petersc5dc4da2003-01-02 17:55:03 +00005341If [5] is true now, diff = 0, so z.d = 0 too, and we have the standard-time
Tim Peters8bb5ad22003-01-24 02:44:45 +00005342spelling we wanted in the endcase described above. We're done. Contrarily,
5343if z.d = 0, then we have a UTC equivalent, and are also done.
Tim Petersf3615152003-01-01 21:51:37 +00005344
Tim Petersc5dc4da2003-01-02 17:55:03 +00005345If [5] is not true now, diff = z.d != 0, and z.d is the offset we need to
5346add to z (in effect, z is in tz's standard time, and we need to shift the
Tim Peters8bb5ad22003-01-24 02:44:45 +00005347local clock into tz's daylight time).
Tim Petersf3615152003-01-01 21:51:37 +00005348
Tim Petersc5dc4da2003-01-02 17:55:03 +00005349Let
Tim Petersf3615152003-01-01 21:51:37 +00005350
Tim Peters4fede1a2003-01-04 00:26:59 +00005351 z' = z + z.d = z + diff [7]
Tim Petersc3bb26a2003-01-02 03:14:59 +00005352
Tim Peters4fede1a2003-01-04 00:26:59 +00005353and we can again ask whether
Tim Petersc3bb26a2003-01-02 03:14:59 +00005354
Tim Peters8bb5ad22003-01-24 02:44:45 +00005355 z'.n - z'.o = x.n [8]
Tim Petersc3bb26a2003-01-02 03:14:59 +00005356
Tim Peters8bb5ad22003-01-24 02:44:45 +00005357If so, we're done. If not, the tzinfo class is insane, according to the
5358assumptions we've made. This also requires a bit of proof. As before, let's
5359compute the difference between the LHS and RHS of [8] (and skipping some of
5360the justifications for the kinds of substitutions we've done several times
5361already):
Tim Peters4fede1a2003-01-04 00:26:59 +00005362
Tim Peters8bb5ad22003-01-24 02:44:45 +00005363 diff' = x.n - (z'.n - z'.o) = replacing z'.n via [7]
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005364 x.n - (z.n + diff - z'.o) = replacing diff via [6]
5365 x.n - (z.n + x.n - (z.n - z.o) - z'.o) =
5366 x.n - z.n - x.n + z.n - z.o + z'.o = cancel x.n
5367 - z.n + z.n - z.o + z'.o = cancel z.n
5368 - z.o + z'.o = #1 twice
5369 -z.s - z.d + z'.s + z'.d = z and z' have same tzinfo
5370 z'.d - z.d
Tim Peters4fede1a2003-01-04 00:26:59 +00005371
5372So 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 +00005373we've found the UTC-equivalent so are done. In fact, we stop with [7] and
5374return z', not bothering to compute z'.d.
Tim Peters4fede1a2003-01-04 00:26:59 +00005375
Tim Peters8bb5ad22003-01-24 02:44:45 +00005376How could z.d and z'd differ? z' = z + z.d [7], so merely moving z' by
5377a dst() offset, and starting *from* a time already in DST (we know z.d != 0),
5378would have to change the result dst() returns: we start in DST, and moving
5379a little further into it takes us out of DST.
Tim Peters4fede1a2003-01-04 00:26:59 +00005380
Tim Peters8bb5ad22003-01-24 02:44:45 +00005381There isn't a sane case where this can happen. The closest it gets is at
5382the end of DST, where there's an hour in UTC with no spelling in a hybrid
5383tzinfo class. In US Eastern, that's 5:MM UTC = 0:MM EST = 1:MM EDT. During
5384that hour, on an Eastern clock 1:MM is taken as being in standard time (6:MM
5385UTC) because the docs insist on that, but 0:MM is taken as being in daylight
5386time (4:MM UTC). There is no local time mapping to 5:MM UTC. The local
5387clock jumps from 1:59 back to 1:00 again, and repeats the 1:MM hour in
5388standard time. Since that's what the local clock *does*, we want to map both
5389UTC hours 5:MM and 6:MM to 1:MM Eastern. The result is ambiguous
Tim Peters4fede1a2003-01-04 00:26:59 +00005390in local time, but so it goes -- it's the way the local clock works.
5391
Tim Peters8bb5ad22003-01-24 02:44:45 +00005392When x = 5:MM UTC is the input to this algorithm, x.o=0, y.o=-5 and y.d=0,
5393so z=0:MM. z.d=60 (minutes) then, so [5] doesn't hold and we keep going.
5394z' = 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 +00005395(correctly) concludes that z' is not UTC-equivalent to x.
5396
5397Because we know z.d said z was in daylight time (else [5] would have held and
5398we would have stopped then), and we know z.d != z'.d (else [8] would have held
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +00005399and we would have stopped then), and there are only 2 possible values dst() can
Tim Peters4fede1a2003-01-04 00:26:59 +00005400return in Eastern, it follows that z'.d must be 0 (which it is in the example,
5401but the reasoning doesn't depend on the example -- it depends on there being
5402two possible dst() outcomes, one zero and the other non-zero). Therefore
Tim Peters8bb5ad22003-01-24 02:44:45 +00005403z' must be in standard time, and is the spelling we want in this case.
5404
5405Note again that z' is not UTC-equivalent as far as the hybrid tzinfo class is
5406concerned (because it takes z' as being in standard time rather than the
5407daylight time we intend here), but returning it gives the real-life "local
5408clock repeats an hour" behavior when mapping the "unspellable" UTC hour into
5409tz.
5410
5411When the input is 6:MM, z=1:MM and z.d=0, and we stop at once, again with
5412the 1:MM standard time spelling we want.
5413
5414So how can this break? One of the assumptions must be violated. Two
5415possibilities:
5416
54171) [2] effectively says that y.s is invariant across all y belong to a given
5418 time zone. This isn't true if, for political reasons or continental drift,
5419 a region decides to change its base offset from UTC.
5420
54212) There may be versions of "double daylight" time where the tail end of
5422 the analysis gives up a step too early. I haven't thought about that
5423 enough to say.
5424
5425In any case, it's clear that the default fromutc() is strong enough to handle
5426"almost all" time zones: so long as the standard offset is invariant, it
5427doesn't matter if daylight time transition points change from year to year, or
5428if daylight time is skipped in some years; it doesn't matter how large or
5429small dst() may get within its bounds; and it doesn't even matter if some
5430perverse time zone returns a negative dst()). So a breaking case must be
5431pretty bizarre, and a tzinfo subclass can override fromutc() if it is.
Tim Petersf3615152003-01-01 21:51:37 +00005432--------------------------------------------------------------------------- */