blob: e818c5cfdc4d2fa8c035ca4e22cf161dc3c9614d [file] [log] [blame]
Tim Peters2a799bf2002-12-16 20:18:38 +00001/* C implementation for the date/time type documented at
2 * http://www.zope.org/Members/fdrake/DateTimeWiki/FrontPage
3 */
4
Gregory P. Smith137d8242008-06-02 04:05:52 +00005#define PY_SSIZE_T_CLEAN
6
Tim Peters2a799bf2002-12-16 20:18:38 +00007#include "Python.h"
8#include "modsupport.h"
9#include "structmember.h"
10
11#include <time.h>
12
Tim Peters1b6f7a92004-06-20 02:50:16 +000013#include "timefuncs.h"
Tim Peters9ddf40b2004-06-20 22:41:32 +000014
15/* Differentiate between building the core module and building extension
16 * modules.
17 */
Kristján Valur Jónsson7a0da192007-04-30 15:17:46 +000018#ifndef Py_BUILD_CORE
Tim Peters9ddf40b2004-06-20 22:41:32 +000019#define Py_BUILD_CORE
Kristján Valur Jónsson7a0da192007-04-30 15:17:46 +000020#endif
Tim Peters2a799bf2002-12-16 20:18:38 +000021#include "datetime.h"
Tim Peters9ddf40b2004-06-20 22:41:32 +000022#undef Py_BUILD_CORE
Tim Peters2a799bf2002-12-16 20:18:38 +000023
24/* We require that C int be at least 32 bits, and use int virtually
25 * everywhere. In just a few cases we use a temp long, where a Python
26 * API returns a C long. In such cases, we have to ensure that the
27 * final result fits in a C int (this can be an issue on 64-bit boxes).
28 */
29#if SIZEOF_INT < 4
Antoine Pitrouc83ea132010-05-09 14:46:46 +000030# error "datetime.c requires that C int have at least 32 bits"
Tim Peters2a799bf2002-12-16 20:18:38 +000031#endif
32
33#define MINYEAR 1
34#define MAXYEAR 9999
Alexander Belopolsky9292ee02010-05-27 20:55:27 +000035#define MAXORDINAL 3652059 /* date(9999,12,31).toordinal() */
Tim Peters2a799bf2002-12-16 20:18:38 +000036
37/* Nine decimal digits is easy to communicate, and leaves enough room
38 * so that two delta days can be added w/o fear of overflowing a signed
39 * 32-bit int, and with plenty of room left over to absorb any possible
40 * carries from adding seconds.
41 */
42#define MAX_DELTA_DAYS 999999999
43
44/* Rename the long macros in datetime.h to more reasonable short names. */
Antoine Pitrouc83ea132010-05-09 14:46:46 +000045#define GET_YEAR PyDateTime_GET_YEAR
46#define GET_MONTH PyDateTime_GET_MONTH
47#define GET_DAY PyDateTime_GET_DAY
48#define DATE_GET_HOUR PyDateTime_DATE_GET_HOUR
49#define DATE_GET_MINUTE PyDateTime_DATE_GET_MINUTE
50#define DATE_GET_SECOND PyDateTime_DATE_GET_SECOND
51#define DATE_GET_MICROSECOND PyDateTime_DATE_GET_MICROSECOND
Tim Peters2a799bf2002-12-16 20:18:38 +000052
53/* Date accessors for date and datetime. */
Antoine Pitrouc83ea132010-05-09 14:46:46 +000054#define SET_YEAR(o, v) (((o)->data[0] = ((v) & 0xff00) >> 8), \
55 ((o)->data[1] = ((v) & 0x00ff)))
56#define SET_MONTH(o, v) (PyDateTime_GET_MONTH(o) = (v))
57#define SET_DAY(o, v) (PyDateTime_GET_DAY(o) = (v))
Tim Peters2a799bf2002-12-16 20:18:38 +000058
59/* Date/Time accessors for datetime. */
Antoine Pitrouc83ea132010-05-09 14:46:46 +000060#define DATE_SET_HOUR(o, v) (PyDateTime_DATE_GET_HOUR(o) = (v))
61#define DATE_SET_MINUTE(o, v) (PyDateTime_DATE_GET_MINUTE(o) = (v))
62#define DATE_SET_SECOND(o, v) (PyDateTime_DATE_GET_SECOND(o) = (v))
63#define DATE_SET_MICROSECOND(o, v) \
64 (((o)->data[7] = ((v) & 0xff0000) >> 16), \
65 ((o)->data[8] = ((v) & 0x00ff00) >> 8), \
66 ((o)->data[9] = ((v) & 0x0000ff)))
Tim Peters2a799bf2002-12-16 20:18:38 +000067
68/* Time accessors for time. */
Antoine Pitrouc83ea132010-05-09 14:46:46 +000069#define TIME_GET_HOUR PyDateTime_TIME_GET_HOUR
70#define TIME_GET_MINUTE PyDateTime_TIME_GET_MINUTE
71#define TIME_GET_SECOND PyDateTime_TIME_GET_SECOND
72#define TIME_GET_MICROSECOND PyDateTime_TIME_GET_MICROSECOND
73#define TIME_SET_HOUR(o, v) (PyDateTime_TIME_GET_HOUR(o) = (v))
74#define TIME_SET_MINUTE(o, v) (PyDateTime_TIME_GET_MINUTE(o) = (v))
75#define TIME_SET_SECOND(o, v) (PyDateTime_TIME_GET_SECOND(o) = (v))
76#define TIME_SET_MICROSECOND(o, v) \
77 (((o)->data[3] = ((v) & 0xff0000) >> 16), \
78 ((o)->data[4] = ((v) & 0x00ff00) >> 8), \
79 ((o)->data[5] = ((v) & 0x0000ff)))
Tim Peters2a799bf2002-12-16 20:18:38 +000080
81/* Delta accessors for timedelta. */
Antoine Pitrouc83ea132010-05-09 14:46:46 +000082#define GET_TD_DAYS(o) (((PyDateTime_Delta *)(o))->days)
83#define GET_TD_SECONDS(o) (((PyDateTime_Delta *)(o))->seconds)
84#define GET_TD_MICROSECONDS(o) (((PyDateTime_Delta *)(o))->microseconds)
Tim Peters2a799bf2002-12-16 20:18:38 +000085
Antoine Pitrouc83ea132010-05-09 14:46:46 +000086#define SET_TD_DAYS(o, v) ((o)->days = (v))
87#define SET_TD_SECONDS(o, v) ((o)->seconds = (v))
Tim Peters2a799bf2002-12-16 20:18:38 +000088#define SET_TD_MICROSECONDS(o, v) ((o)->microseconds = (v))
89
Tim Petersa032d2e2003-01-11 00:15:54 +000090/* p is a pointer to a time or a datetime object; HASTZINFO(p) returns
91 * p->hastzinfo.
92 */
Antoine Pitrouc83ea132010-05-09 14:46:46 +000093#define HASTZINFO(p) (((_PyDateTime_BaseTZInfo *)(p))->hastzinfo)
Tim Petersa032d2e2003-01-11 00:15:54 +000094
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 Pitrouc83ea132010-05-09 14:46:46 +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;
Tim Peters2a799bf2002-12-16 20:18:38 +0000107
108/* ---------------------------------------------------------------------------
109 * Math utilities.
110 */
111
112/* k = i+j overflows iff k differs in sign from both inputs,
113 * iff k^i has sign bit set and k^j has sign bit set,
114 * iff (k^i)&(k^j) has sign bit set.
115 */
116#define SIGNED_ADD_OVERFLOWED(RESULT, I, J) \
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000117 ((((RESULT) ^ (I)) & ((RESULT) ^ (J))) < 0)
Tim Peters2a799bf2002-12-16 20:18:38 +0000118
119/* Compute Python divmod(x, y), returning the quotient and storing the
120 * remainder into *r. The quotient is the floor of x/y, and that's
121 * the real point of this. C will probably truncate instead (C99
122 * requires truncation; C89 left it implementation-defined).
123 * Simplification: we *require* that y > 0 here. That's appropriate
124 * for all the uses made of it. This simplifies the code and makes
125 * the overflow case impossible (divmod(LONG_MIN, -1) is the only
126 * overflow case).
127 */
128static int
129divmod(int x, int y, int *r)
130{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000131 int quo;
Tim Peters2a799bf2002-12-16 20:18:38 +0000132
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000133 assert(y > 0);
134 quo = x / y;
135 *r = x - quo * y;
136 if (*r < 0) {
137 --quo;
138 *r += y;
139 }
140 assert(0 <= *r && *r < y);
141 return quo;
Tim Peters2a799bf2002-12-16 20:18:38 +0000142}
143
Tim Peters5d644dd2003-01-02 16:32:54 +0000144/* Round a double to the nearest long. |x| must be small enough to fit
145 * in a C long; this is not checked.
146 */
147static long
148round_to_long(double x)
149{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000150 if (x >= 0.0)
151 x = floor(x + 0.5);
152 else
153 x = ceil(x - 0.5);
154 return (long)x;
Tim Peters5d644dd2003-01-02 16:32:54 +0000155}
156
Tim Peters2a799bf2002-12-16 20:18:38 +0000157/* ---------------------------------------------------------------------------
158 * General calendrical helper functions
159 */
160
161/* For each month ordinal in 1..12, the number of days in that month,
162 * and the number of days before that month in the same year. These
163 * are correct for non-leap years only.
164 */
165static int _days_in_month[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000166 0, /* unused; this vector uses 1-based indexing */
167 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
Tim Peters2a799bf2002-12-16 20:18:38 +0000168};
169
170static int _days_before_month[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000171 0, /* unused; this vector uses 1-based indexing */
172 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
Tim Peters2a799bf2002-12-16 20:18:38 +0000173};
174
175/* year -> 1 if leap year, else 0. */
176static int
177is_leap(int year)
178{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000179 /* Cast year to unsigned. The result is the same either way, but
180 * C can generate faster code for unsigned mod than for signed
181 * mod (especially for % 4 -- a good compiler should just grab
182 * the last 2 bits when the LHS is unsigned).
183 */
184 const unsigned int ayear = (unsigned int)year;
185 return ayear % 4 == 0 && (ayear % 100 != 0 || ayear % 400 == 0);
Tim Peters2a799bf2002-12-16 20:18:38 +0000186}
187
188/* year, month -> number of days in that month in that year */
189static int
190days_in_month(int year, int month)
191{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000192 assert(month >= 1);
193 assert(month <= 12);
194 if (month == 2 && is_leap(year))
195 return 29;
196 else
197 return _days_in_month[month];
Tim Peters2a799bf2002-12-16 20:18:38 +0000198}
199
Martin Panterb1d867f2016-05-26 05:28:50 +0000200/* year, month -> number of days in year preceding first day of month */
Tim Peters2a799bf2002-12-16 20:18:38 +0000201static int
202days_before_month(int year, int month)
203{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000204 int days;
Tim Peters2a799bf2002-12-16 20:18:38 +0000205
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000206 assert(month >= 1);
207 assert(month <= 12);
208 days = _days_before_month[month];
209 if (month > 2 && is_leap(year))
210 ++days;
211 return days;
Tim Peters2a799bf2002-12-16 20:18:38 +0000212}
213
214/* year -> number of days before January 1st of year. Remember that we
215 * start with year 1, so days_before_year(1) == 0.
216 */
217static int
218days_before_year(int year)
219{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000220 int y = year - 1;
221 /* This is incorrect if year <= 0; we really want the floor
222 * here. But so long as MINYEAR is 1, the smallest year this
223 * can see is 0 (this can happen in some normalization endcases),
224 * so we'll just special-case that.
225 */
226 assert (year >= 0);
227 if (y >= 0)
228 return y*365 + y/4 - y/100 + y/400;
229 else {
230 assert(y == -1);
231 return -366;
232 }
Tim Peters2a799bf2002-12-16 20:18:38 +0000233}
234
235/* Number of days in 4, 100, and 400 year cycles. That these have
236 * the correct values is asserted in the module init function.
237 */
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000238#define DI4Y 1461 /* days_before_year(5); days in 4 years */
239#define DI100Y 36524 /* days_before_year(101); days in 100 years */
240#define DI400Y 146097 /* days_before_year(401); days in 400 years */
Tim Peters2a799bf2002-12-16 20:18:38 +0000241
242/* ordinal -> year, month, day, considering 01-Jan-0001 as day 1. */
243static void
244ord_to_ymd(int ordinal, int *year, int *month, int *day)
245{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000246 int n, n1, n4, n100, n400, leapyear, preceding;
Tim Peters2a799bf2002-12-16 20:18:38 +0000247
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000248 /* ordinal is a 1-based index, starting at 1-Jan-1. The pattern of
249 * leap years repeats exactly every 400 years. The basic strategy is
250 * to find the closest 400-year boundary at or before ordinal, then
251 * work with the offset from that boundary to ordinal. Life is much
252 * clearer if we subtract 1 from ordinal first -- then the values
253 * of ordinal at 400-year boundaries are exactly those divisible
254 * by DI400Y:
255 *
256 * D M Y n n-1
257 * -- --- ---- ---------- ----------------
258 * 31 Dec -400 -DI400Y -DI400Y -1
259 * 1 Jan -399 -DI400Y +1 -DI400Y 400-year boundary
260 * ...
261 * 30 Dec 000 -1 -2
262 * 31 Dec 000 0 -1
263 * 1 Jan 001 1 0 400-year boundary
264 * 2 Jan 001 2 1
265 * 3 Jan 001 3 2
266 * ...
267 * 31 Dec 400 DI400Y DI400Y -1
268 * 1 Jan 401 DI400Y +1 DI400Y 400-year boundary
269 */
270 assert(ordinal >= 1);
271 --ordinal;
272 n400 = ordinal / DI400Y;
273 n = ordinal % DI400Y;
274 *year = n400 * 400 + 1;
Tim Peters2a799bf2002-12-16 20:18:38 +0000275
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000276 /* Now n is the (non-negative) offset, in days, from January 1 of
277 * year, to the desired date. Now compute how many 100-year cycles
278 * precede n.
279 * Note that it's possible for n100 to equal 4! In that case 4 full
280 * 100-year cycles precede the desired day, which implies the
281 * desired day is December 31 at the end of a 400-year cycle.
282 */
283 n100 = n / DI100Y;
284 n = n % DI100Y;
Tim Peters2a799bf2002-12-16 20:18:38 +0000285
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000286 /* Now compute how many 4-year cycles precede it. */
287 n4 = n / DI4Y;
288 n = n % DI4Y;
Tim Peters2a799bf2002-12-16 20:18:38 +0000289
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000290 /* And now how many single years. Again n1 can be 4, and again
291 * meaning that the desired day is December 31 at the end of the
292 * 4-year cycle.
293 */
294 n1 = n / 365;
295 n = n % 365;
Tim Peters2a799bf2002-12-16 20:18:38 +0000296
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000297 *year += n100 * 100 + n4 * 4 + n1;
298 if (n1 == 4 || n100 == 4) {
299 assert(n == 0);
300 *year -= 1;
301 *month = 12;
302 *day = 31;
303 return;
304 }
Tim Peters2a799bf2002-12-16 20:18:38 +0000305
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000306 /* Now the year is correct, and n is the offset from January 1. We
307 * find the month via an estimate that's either exact or one too
308 * large.
309 */
310 leapyear = n1 == 3 && (n4 != 24 || n100 == 3);
311 assert(leapyear == is_leap(*year));
312 *month = (n + 50) >> 5;
313 preceding = (_days_before_month[*month] + (*month > 2 && leapyear));
314 if (preceding > n) {
315 /* estimate is too large */
316 *month -= 1;
317 preceding -= days_in_month(*year, *month);
318 }
319 n -= preceding;
320 assert(0 <= n);
321 assert(n < days_in_month(*year, *month));
Tim Peters2a799bf2002-12-16 20:18:38 +0000322
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000323 *day = n + 1;
Tim Peters2a799bf2002-12-16 20:18:38 +0000324}
325
326/* year, month, day -> ordinal, considering 01-Jan-0001 as day 1. */
327static int
328ymd_to_ord(int year, int month, int day)
329{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000330 return days_before_year(year) + days_before_month(year, month) + day;
Tim Peters2a799bf2002-12-16 20:18:38 +0000331}
332
333/* Day of week, where Monday==0, ..., Sunday==6. 1/1/1 was a Monday. */
334static int
335weekday(int year, int month, int day)
336{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000337 return (ymd_to_ord(year, month, day) + 6) % 7;
Tim Peters2a799bf2002-12-16 20:18:38 +0000338}
339
340/* Ordinal of the Monday starting week 1 of the ISO year. Week 1 is the
341 * first calendar week containing a Thursday.
342 */
343static int
344iso_week1_monday(int year)
345{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000346 int first_day = ymd_to_ord(year, 1, 1); /* ord of 1/1 */
347 /* 0 if 1/1 is a Monday, 1 if a Tue, etc. */
348 int first_weekday = (first_day + 6) % 7;
349 /* ordinal of closest Monday at or before 1/1 */
350 int week1_monday = first_day - first_weekday;
Tim Peters2a799bf2002-12-16 20:18:38 +0000351
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000352 if (first_weekday > 3) /* if 1/1 was Fri, Sat, Sun */
353 week1_monday += 7;
354 return week1_monday;
Tim Peters2a799bf2002-12-16 20:18:38 +0000355}
356
357/* ---------------------------------------------------------------------------
358 * Range checkers.
359 */
360
361/* Check that -MAX_DELTA_DAYS <= days <= MAX_DELTA_DAYS. If so, return 0.
362 * If not, raise OverflowError and return -1.
363 */
364static int
365check_delta_day_range(int days)
366{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000367 if (-MAX_DELTA_DAYS <= days && days <= MAX_DELTA_DAYS)
368 return 0;
369 PyErr_Format(PyExc_OverflowError,
370 "days=%d; must have magnitude <= %d",
371 days, MAX_DELTA_DAYS);
372 return -1;
Tim Peters2a799bf2002-12-16 20:18:38 +0000373}
374
375/* Check that date arguments are in range. Return 0 if they are. If they
376 * aren't, raise ValueError and return -1.
377 */
378static int
379check_date_args(int year, int month, int day)
380{
381
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000382 if (year < MINYEAR || year > MAXYEAR) {
383 PyErr_SetString(PyExc_ValueError,
384 "year is out of range");
385 return -1;
386 }
387 if (month < 1 || month > 12) {
388 PyErr_SetString(PyExc_ValueError,
389 "month must be in 1..12");
390 return -1;
391 }
392 if (day < 1 || day > days_in_month(year, month)) {
393 PyErr_SetString(PyExc_ValueError,
394 "day is out of range for month");
395 return -1;
396 }
397 return 0;
Tim Peters2a799bf2002-12-16 20:18:38 +0000398}
399
400/* Check that time arguments are in range. Return 0 if they are. If they
401 * aren't, raise ValueError and return -1.
402 */
403static int
404check_time_args(int h, int m, int s, int us)
405{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000406 if (h < 0 || h > 23) {
407 PyErr_SetString(PyExc_ValueError,
408 "hour must be in 0..23");
409 return -1;
410 }
411 if (m < 0 || m > 59) {
412 PyErr_SetString(PyExc_ValueError,
413 "minute must be in 0..59");
414 return -1;
415 }
416 if (s < 0 || s > 59) {
417 PyErr_SetString(PyExc_ValueError,
418 "second must be in 0..59");
419 return -1;
420 }
421 if (us < 0 || us > 999999) {
422 PyErr_SetString(PyExc_ValueError,
423 "microsecond must be in 0..999999");
424 return -1;
425 }
426 return 0;
Tim Peters2a799bf2002-12-16 20:18:38 +0000427}
428
429/* ---------------------------------------------------------------------------
430 * Normalization utilities.
431 */
432
433/* One step of a mixed-radix conversion. A "hi" unit is equivalent to
434 * factor "lo" units. factor must be > 0. If *lo is less than 0, or
435 * at least factor, enough of *lo is converted into "hi" units so that
436 * 0 <= *lo < factor. The input values must be such that int overflow
437 * is impossible.
438 */
439static void
440normalize_pair(int *hi, int *lo, int factor)
441{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000442 assert(factor > 0);
443 assert(lo != hi);
444 if (*lo < 0 || *lo >= factor) {
445 const int num_hi = divmod(*lo, factor, lo);
446 const int new_hi = *hi + num_hi;
447 assert(! SIGNED_ADD_OVERFLOWED(new_hi, *hi, num_hi));
448 *hi = new_hi;
449 }
450 assert(0 <= *lo && *lo < factor);
Tim Peters2a799bf2002-12-16 20:18:38 +0000451}
452
453/* Fiddle days (d), seconds (s), and microseconds (us) so that
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000454 * 0 <= *s < 24*3600
455 * 0 <= *us < 1000000
Tim Peters2a799bf2002-12-16 20:18:38 +0000456 * The input values must be such that the internals don't overflow.
457 * The way this routine is used, we don't get close.
458 */
459static void
460normalize_d_s_us(int *d, int *s, int *us)
461{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000462 if (*us < 0 || *us >= 1000000) {
463 normalize_pair(s, us, 1000000);
464 /* |s| can't be bigger than about
465 * |original s| + |original us|/1000000 now.
466 */
Tim Peters2a799bf2002-12-16 20:18:38 +0000467
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000468 }
469 if (*s < 0 || *s >= 24*3600) {
470 normalize_pair(d, s, 24*3600);
471 /* |d| can't be bigger than about
472 * |original d| +
473 * (|original s| + |original us|/1000000) / (24*3600) now.
474 */
475 }
476 assert(0 <= *s && *s < 24*3600);
477 assert(0 <= *us && *us < 1000000);
Tim Peters2a799bf2002-12-16 20:18:38 +0000478}
479
480/* Fiddle years (y), months (m), and days (d) so that
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000481 * 1 <= *m <= 12
482 * 1 <= *d <= days_in_month(*y, *m)
Tim Peters2a799bf2002-12-16 20:18:38 +0000483 * The input values must be such that the internals don't overflow.
484 * The way this routine is used, we don't get close.
485 */
Alexander Belopolsky9292ee02010-05-27 20:55:27 +0000486static int
Tim Peters2a799bf2002-12-16 20:18:38 +0000487normalize_y_m_d(int *y, int *m, int *d)
488{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000489 int dim; /* # of days in month */
Tim Peters2a799bf2002-12-16 20:18:38 +0000490
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000491 /* This gets muddy: the proper range for day can't be determined
492 * without knowing the correct month and year, but if day is, e.g.,
493 * plus or minus a million, the current month and year values make
494 * no sense (and may also be out of bounds themselves).
495 * Saying 12 months == 1 year should be non-controversial.
496 */
497 if (*m < 1 || *m > 12) {
498 --*m;
499 normalize_pair(y, m, 12);
500 ++*m;
501 /* |y| can't be bigger than about
502 * |original y| + |original m|/12 now.
503 */
504 }
505 assert(1 <= *m && *m <= 12);
Tim Peters2a799bf2002-12-16 20:18:38 +0000506
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000507 /* Now only day can be out of bounds (year may also be out of bounds
508 * for a datetime object, but we don't care about that here).
509 * If day is out of bounds, what to do is arguable, but at least the
510 * method here is principled and explainable.
511 */
512 dim = days_in_month(*y, *m);
513 if (*d < 1 || *d > dim) {
514 /* Move day-1 days from the first of the month. First try to
515 * get off cheap if we're only one day out of range
516 * (adjustments for timezone alone can't be worse than that).
517 */
518 if (*d == 0) {
519 --*m;
520 if (*m > 0)
521 *d = days_in_month(*y, *m);
522 else {
523 --*y;
524 *m = 12;
525 *d = 31;
526 }
527 }
528 else if (*d == dim + 1) {
529 /* move forward a day */
530 ++*m;
531 *d = 1;
532 if (*m > 12) {
533 *m = 1;
534 ++*y;
535 }
536 }
537 else {
538 int ordinal = ymd_to_ord(*y, *m, 1) +
539 *d - 1;
Alexander Belopolsky9292ee02010-05-27 20:55:27 +0000540 if (ordinal < 1 || ordinal > MAXORDINAL) {
541 goto error;
542 } else {
543 ord_to_ymd(ordinal, y, m, d);
544 return 0;
545 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000546 }
547 }
548 assert(*m > 0);
549 assert(*d > 0);
Alexander Belopolsky9292ee02010-05-27 20:55:27 +0000550 if (MINYEAR <= *y && *y <= MAXYEAR)
551 return 0;
552 error:
553 PyErr_SetString(PyExc_OverflowError,
554 "date value out of range");
555 return -1;
556
Tim Peters2a799bf2002-12-16 20:18:38 +0000557}
558
559/* Fiddle out-of-bounds months and days so that the result makes some kind
560 * of sense. The parameters are both inputs and outputs. Returns < 0 on
561 * failure, where failure means the adjusted year is out of bounds.
562 */
563static int
564normalize_date(int *year, int *month, int *day)
565{
Alexander Belopolsky9292ee02010-05-27 20:55:27 +0000566 return normalize_y_m_d(year, month, day);
Tim Peters2a799bf2002-12-16 20:18:38 +0000567}
568
569/* Force all the datetime fields into range. The parameters are both
570 * inputs and outputs. Returns < 0 on error.
571 */
572static int
573normalize_datetime(int *year, int *month, int *day,
574 int *hour, int *minute, int *second,
575 int *microsecond)
576{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000577 normalize_pair(second, microsecond, 1000000);
578 normalize_pair(minute, second, 60);
579 normalize_pair(hour, minute, 60);
580 normalize_pair(day, hour, 24);
581 return normalize_date(year, month, day);
Tim Peters2a799bf2002-12-16 20:18:38 +0000582}
583
584/* ---------------------------------------------------------------------------
Tim Petersb0c854d2003-05-17 15:57:00 +0000585 * Basic object allocation: tp_alloc implementations. These allocate
586 * Python objects of the right size and type, and do the Python object-
587 * initialization bit. If there's not enough memory, they return NULL after
588 * setting MemoryError. All data members remain uninitialized trash.
589 *
590 * We abuse the tp_alloc "nitems" argument to communicate whether a tzinfo
Tim Peters03eaf8b2003-05-18 02:24:46 +0000591 * member is needed. This is ugly, imprecise, and possibly insecure.
592 * tp_basicsize for the time and datetime types is set to the size of the
593 * struct that has room for the tzinfo member, so subclasses in Python will
594 * allocate enough space for a tzinfo member whether or not one is actually
595 * needed. That's the "ugly and imprecise" parts. The "possibly insecure"
596 * part is that PyType_GenericAlloc() (which subclasses in Python end up
597 * using) just happens today to effectively ignore the nitems argument
598 * when tp_itemsize is 0, which it is for these type objects. If that
599 * changes, perhaps the callers of tp_alloc slots in this file should
600 * be changed to force a 0 nitems argument unless the type being allocated
601 * is a base type implemented in this file (so that tp_alloc is time_alloc
602 * or datetime_alloc below, which know about the nitems abuse).
Tim Petersb0c854d2003-05-17 15:57:00 +0000603 */
604
605static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000606time_alloc(PyTypeObject *type, Py_ssize_t aware)
Tim Petersb0c854d2003-05-17 15:57:00 +0000607{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000608 PyObject *self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000609
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000610 self = (PyObject *)
611 PyObject_MALLOC(aware ?
612 sizeof(PyDateTime_Time) :
613 sizeof(_PyDateTime_BaseTime));
614 if (self == NULL)
615 return (PyObject *)PyErr_NoMemory();
Martin Panter646b5282016-06-21 23:58:05 +0000616 (void)PyObject_INIT(self, type);
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000617 return self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000618}
619
620static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000621datetime_alloc(PyTypeObject *type, Py_ssize_t aware)
Tim Petersb0c854d2003-05-17 15:57:00 +0000622{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000623 PyObject *self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000624
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000625 self = (PyObject *)
626 PyObject_MALLOC(aware ?
627 sizeof(PyDateTime_DateTime) :
628 sizeof(_PyDateTime_BaseDateTime));
629 if (self == NULL)
630 return (PyObject *)PyErr_NoMemory();
Martin Panter646b5282016-06-21 23:58:05 +0000631 (void)PyObject_INIT(self, type);
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000632 return self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000633}
634
635/* ---------------------------------------------------------------------------
636 * Helpers for setting object fields. These work on pointers to the
637 * appropriate base class.
638 */
639
640/* For date and datetime. */
641static void
642set_date_fields(PyDateTime_Date *self, int y, int m, int d)
643{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000644 self->hashcode = -1;
645 SET_YEAR(self, y);
646 SET_MONTH(self, m);
647 SET_DAY(self, d);
Tim Petersb0c854d2003-05-17 15:57:00 +0000648}
649
650/* ---------------------------------------------------------------------------
651 * Create various objects, mostly without range checking.
652 */
653
654/* Create a date instance with no range checking. */
655static PyObject *
656new_date_ex(int year, int month, int day, PyTypeObject *type)
657{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000658 PyDateTime_Date *self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000659
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000660 self = (PyDateTime_Date *) (type->tp_alloc(type, 0));
661 if (self != NULL)
662 set_date_fields(self, year, month, day);
663 return (PyObject *) self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000664}
665
666#define new_date(year, month, day) \
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000667 new_date_ex(year, month, day, &PyDateTime_DateType)
Tim Petersb0c854d2003-05-17 15:57:00 +0000668
669/* Create a datetime instance with no range checking. */
670static PyObject *
671new_datetime_ex(int year, int month, int day, int hour, int minute,
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000672 int second, int usecond, PyObject *tzinfo, PyTypeObject *type)
Tim Petersb0c854d2003-05-17 15:57:00 +0000673{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000674 PyDateTime_DateTime *self;
675 char aware = tzinfo != Py_None;
Tim Petersb0c854d2003-05-17 15:57:00 +0000676
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000677 self = (PyDateTime_DateTime *) (type->tp_alloc(type, aware));
678 if (self != NULL) {
679 self->hastzinfo = aware;
680 set_date_fields((PyDateTime_Date *)self, year, month, day);
681 DATE_SET_HOUR(self, hour);
682 DATE_SET_MINUTE(self, minute);
683 DATE_SET_SECOND(self, second);
684 DATE_SET_MICROSECOND(self, usecond);
685 if (aware) {
686 Py_INCREF(tzinfo);
687 self->tzinfo = tzinfo;
688 }
689 }
690 return (PyObject *)self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000691}
692
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000693#define new_datetime(y, m, d, hh, mm, ss, us, tzinfo) \
694 new_datetime_ex(y, m, d, hh, mm, ss, us, tzinfo, \
695 &PyDateTime_DateTimeType)
Tim Petersb0c854d2003-05-17 15:57:00 +0000696
697/* Create a time instance with no range checking. */
698static PyObject *
699new_time_ex(int hour, int minute, int second, int usecond,
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000700 PyObject *tzinfo, PyTypeObject *type)
Tim Petersb0c854d2003-05-17 15:57:00 +0000701{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000702 PyDateTime_Time *self;
703 char aware = tzinfo != Py_None;
Tim Petersb0c854d2003-05-17 15:57:00 +0000704
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000705 self = (PyDateTime_Time *) (type->tp_alloc(type, aware));
706 if (self != NULL) {
707 self->hastzinfo = aware;
708 self->hashcode = -1;
709 TIME_SET_HOUR(self, hour);
710 TIME_SET_MINUTE(self, minute);
711 TIME_SET_SECOND(self, second);
712 TIME_SET_MICROSECOND(self, usecond);
713 if (aware) {
714 Py_INCREF(tzinfo);
715 self->tzinfo = tzinfo;
716 }
717 }
718 return (PyObject *)self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000719}
720
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000721#define new_time(hh, mm, ss, us, tzinfo) \
722 new_time_ex(hh, mm, ss, us, tzinfo, &PyDateTime_TimeType)
Tim Petersb0c854d2003-05-17 15:57:00 +0000723
724/* Create a timedelta instance. Normalize the members iff normalize is
725 * true. Passing false is a speed optimization, if you know for sure
726 * that seconds and microseconds are already in their proper ranges. In any
727 * case, raises OverflowError and returns NULL if the normalized days is out
728 * of range).
729 */
730static PyObject *
731new_delta_ex(int days, int seconds, int microseconds, int normalize,
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000732 PyTypeObject *type)
Tim Petersb0c854d2003-05-17 15:57:00 +0000733{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000734 PyDateTime_Delta *self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000735
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000736 if (normalize)
737 normalize_d_s_us(&days, &seconds, &microseconds);
738 assert(0 <= seconds && seconds < 24*3600);
739 assert(0 <= microseconds && microseconds < 1000000);
Tim Petersb0c854d2003-05-17 15:57:00 +0000740
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000741 if (check_delta_day_range(days) < 0)
742 return NULL;
Tim Petersb0c854d2003-05-17 15:57:00 +0000743
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000744 self = (PyDateTime_Delta *) (type->tp_alloc(type, 0));
745 if (self != NULL) {
746 self->hashcode = -1;
747 SET_TD_DAYS(self, days);
748 SET_TD_SECONDS(self, seconds);
749 SET_TD_MICROSECONDS(self, microseconds);
750 }
751 return (PyObject *) self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000752}
753
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000754#define new_delta(d, s, us, normalize) \
755 new_delta_ex(d, s, us, normalize, &PyDateTime_DeltaType)
Tim Petersb0c854d2003-05-17 15:57:00 +0000756
757/* ---------------------------------------------------------------------------
Tim Peters2a799bf2002-12-16 20:18:38 +0000758 * tzinfo helpers.
759 */
760
Tim Peters855fe882002-12-22 03:43:39 +0000761/* Ensure that p is None or of a tzinfo subclass. Return 0 if OK; if not
762 * raise TypeError and return -1.
763 */
764static int
765check_tzinfo_subclass(PyObject *p)
766{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000767 if (p == Py_None || PyTZInfo_Check(p))
768 return 0;
769 PyErr_Format(PyExc_TypeError,
770 "tzinfo argument must be None or of a tzinfo subclass, "
771 "not type '%s'",
772 Py_TYPE(p)->tp_name);
773 return -1;
Tim Peters855fe882002-12-22 03:43:39 +0000774}
775
Tim Petersbad8ff02002-12-30 20:52:32 +0000776/* Return tzinfo.methname(tzinfoarg), without any checking of results.
Tim Peters855fe882002-12-22 03:43:39 +0000777 * If tzinfo is None, returns None.
778 */
779static PyObject *
Tim Petersbad8ff02002-12-30 20:52:32 +0000780call_tzinfo_method(PyObject *tzinfo, char *methname, PyObject *tzinfoarg)
Tim Peters855fe882002-12-22 03:43:39 +0000781{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000782 PyObject *result;
Tim Peters855fe882002-12-22 03:43:39 +0000783
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000784 assert(tzinfo && methname && tzinfoarg);
785 assert(check_tzinfo_subclass(tzinfo) >= 0);
786 if (tzinfo == Py_None) {
787 result = Py_None;
788 Py_INCREF(result);
789 }
790 else
791 result = PyObject_CallMethod(tzinfo, methname, "O", tzinfoarg);
792 return result;
Tim Peters855fe882002-12-22 03:43:39 +0000793}
794
Tim Peters2a799bf2002-12-16 20:18:38 +0000795/* If self has a tzinfo member, return a BORROWED reference to it. Else
796 * return NULL, which is NOT AN ERROR. There are no error returns here,
797 * and the caller must not decref the result.
798 */
799static PyObject *
800get_tzinfo_member(PyObject *self)
801{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000802 PyObject *tzinfo = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +0000803
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000804 if (PyDateTime_Check(self) && HASTZINFO(self))
805 tzinfo = ((PyDateTime_DateTime *)self)->tzinfo;
806 else if (PyTime_Check(self) && HASTZINFO(self))
807 tzinfo = ((PyDateTime_Time *)self)->tzinfo;
Tim Peters2a799bf2002-12-16 20:18:38 +0000808
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000809 return tzinfo;
Tim Peters2a799bf2002-12-16 20:18:38 +0000810}
811
Tim Petersbad8ff02002-12-30 20:52:32 +0000812/* Call getattr(tzinfo, name)(tzinfoarg), and extract an int from the
Tim Peters2a799bf2002-12-16 20:18:38 +0000813 * result. tzinfo must be an instance of the tzinfo class. If the method
814 * returns None, this returns 0 and sets *none to 1. If the method doesn't
Tim Peters397301e2003-01-02 21:28:08 +0000815 * return None or timedelta, TypeError is raised and this returns -1. If it
816 * returnsa timedelta and the value is out of range or isn't a whole number
817 * of minutes, ValueError is raised and this returns -1.
Tim Peters2a799bf2002-12-16 20:18:38 +0000818 * Else *none is set to 0 and the integer method result is returned.
819 */
820static int
821call_utc_tzinfo_method(PyObject *tzinfo, char *name, PyObject *tzinfoarg,
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000822 int *none)
Tim Peters2a799bf2002-12-16 20:18:38 +0000823{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000824 PyObject *u;
825 int result = -1;
Tim Peters2a799bf2002-12-16 20:18:38 +0000826
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000827 assert(tzinfo != NULL);
828 assert(PyTZInfo_Check(tzinfo));
829 assert(tzinfoarg != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +0000830
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000831 *none = 0;
832 u = call_tzinfo_method(tzinfo, name, tzinfoarg);
833 if (u == NULL)
834 return -1;
Tim Peters2a799bf2002-12-16 20:18:38 +0000835
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000836 else if (u == Py_None) {
837 result = 0;
838 *none = 1;
839 }
840 else if (PyDelta_Check(u)) {
841 const int days = GET_TD_DAYS(u);
842 if (days < -1 || days > 0)
843 result = 24*60; /* trigger ValueError below */
844 else {
845 /* next line can't overflow because we know days
846 * is -1 or 0 now
847 */
848 int ss = days * 24 * 3600 + GET_TD_SECONDS(u);
849 result = divmod(ss, 60, &ss);
850 if (ss || GET_TD_MICROSECONDS(u)) {
851 PyErr_Format(PyExc_ValueError,
852 "tzinfo.%s() must return a "
853 "whole number of minutes",
854 name);
855 result = -1;
856 }
857 }
858 }
859 else {
860 PyErr_Format(PyExc_TypeError,
861 "tzinfo.%s() must return None or "
862 "timedelta, not '%s'",
863 name, Py_TYPE(u)->tp_name);
864 }
Tim Peters2a799bf2002-12-16 20:18:38 +0000865
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000866 Py_DECREF(u);
867 if (result < -1439 || result > 1439) {
868 PyErr_Format(PyExc_ValueError,
869 "tzinfo.%s() returned %d; must be in "
870 "-1439 .. 1439",
871 name, result);
872 result = -1;
873 }
874 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +0000875}
876
877/* Call tzinfo.utcoffset(tzinfoarg), and extract an integer from the
878 * result. tzinfo must be an instance of the tzinfo class. If utcoffset()
879 * returns None, call_utcoffset returns 0 and sets *none to 1. If uctoffset()
Tim Peters397301e2003-01-02 21:28:08 +0000880 * doesn't return None or timedelta, TypeError is raised and this returns -1.
881 * If utcoffset() returns an invalid timedelta (out of range, or not a whole
882 * # of minutes), ValueError is raised and this returns -1. Else *none is
883 * set to 0 and the offset is returned (as int # of minutes east of UTC).
Tim Peters2a799bf2002-12-16 20:18:38 +0000884 */
885static int
886call_utcoffset(PyObject *tzinfo, PyObject *tzinfoarg, int *none)
887{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000888 return call_utc_tzinfo_method(tzinfo, "utcoffset", tzinfoarg, none);
Tim Peters2a799bf2002-12-16 20:18:38 +0000889}
890
Tim Petersbad8ff02002-12-30 20:52:32 +0000891/* Call tzinfo.name(tzinfoarg), and return the offset as a timedelta or None.
892 */
Tim Peters855fe882002-12-22 03:43:39 +0000893static PyObject *
Tim Petersbad8ff02002-12-30 20:52:32 +0000894offset_as_timedelta(PyObject *tzinfo, char *name, PyObject *tzinfoarg) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000895 PyObject *result;
Tim Peters855fe882002-12-22 03:43:39 +0000896
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000897 assert(tzinfo && name && tzinfoarg);
898 if (tzinfo == Py_None) {
899 result = Py_None;
900 Py_INCREF(result);
901 }
902 else {
903 int none;
904 int offset = call_utc_tzinfo_method(tzinfo, name, tzinfoarg,
905 &none);
906 if (offset < 0 && PyErr_Occurred())
907 return NULL;
908 if (none) {
909 result = Py_None;
910 Py_INCREF(result);
911 }
912 else
913 result = new_delta(0, offset * 60, 0, 1);
914 }
915 return result;
Tim Peters855fe882002-12-22 03:43:39 +0000916}
917
Tim Peters2a799bf2002-12-16 20:18:38 +0000918/* Call tzinfo.dst(tzinfoarg), and extract an integer from the
919 * result. tzinfo must be an instance of the tzinfo class. If dst()
920 * returns None, call_dst returns 0 and sets *none to 1. If dst()
Tim Peters397301e2003-01-02 21:28:08 +0000921 & doesn't return None or timedelta, TypeError is raised and this
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000922 * returns -1. If dst() returns an invalid timedelta for a UTC offset,
Tim Peters397301e2003-01-02 21:28:08 +0000923 * ValueError is raised and this returns -1. Else *none is set to 0 and
924 * the offset is returned (as an int # of minutes east of UTC).
Tim Peters2a799bf2002-12-16 20:18:38 +0000925 */
926static int
927call_dst(PyObject *tzinfo, PyObject *tzinfoarg, int *none)
928{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000929 return call_utc_tzinfo_method(tzinfo, "dst", tzinfoarg, none);
Tim Peters2a799bf2002-12-16 20:18:38 +0000930}
931
Tim Petersbad8ff02002-12-30 20:52:32 +0000932/* Call tzinfo.tzname(tzinfoarg), and return the result. tzinfo must be
Tim Peters855fe882002-12-22 03:43:39 +0000933 * an instance of the tzinfo class or None. If tzinfo isn't None, and
Tim Petersbad8ff02002-12-30 20:52:32 +0000934 * tzname() doesn't return None or a string, TypeError is raised and this
Tim Peters855fe882002-12-22 03:43:39 +0000935 * returns NULL.
Tim Peters2a799bf2002-12-16 20:18:38 +0000936 */
937static PyObject *
Tim Petersbad8ff02002-12-30 20:52:32 +0000938call_tzname(PyObject *tzinfo, PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +0000939{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000940 PyObject *result;
Tim Peters2a799bf2002-12-16 20:18:38 +0000941
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000942 assert(tzinfo != NULL);
943 assert(check_tzinfo_subclass(tzinfo) >= 0);
944 assert(tzinfoarg != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +0000945
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000946 if (tzinfo == Py_None) {
947 result = Py_None;
948 Py_INCREF(result);
949 }
950 else
951 result = PyObject_CallMethod(tzinfo, "tzname", "O", tzinfoarg);
Tim Peters855fe882002-12-22 03:43:39 +0000952
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000953 if (result != NULL && result != Py_None && ! PyString_Check(result)) {
954 PyErr_Format(PyExc_TypeError, "tzinfo.tzname() must "
955 "return None or a string, not '%s'",
956 Py_TYPE(result)->tp_name);
957 Py_DECREF(result);
958 result = NULL;
959 }
960 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +0000961}
962
963typedef enum {
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000964 /* an exception has been set; the caller should pass it on */
965 OFFSET_ERROR,
Tim Peters2a799bf2002-12-16 20:18:38 +0000966
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000967 /* type isn't date, datetime, or time subclass */
968 OFFSET_UNKNOWN,
Tim Peters2a799bf2002-12-16 20:18:38 +0000969
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000970 /* date,
971 * datetime with !hastzinfo
972 * datetime with None tzinfo,
973 * datetime where utcoffset() returns None
974 * time with !hastzinfo
975 * time with None tzinfo,
976 * time where utcoffset() returns None
977 */
978 OFFSET_NAIVE,
Tim Peters2a799bf2002-12-16 20:18:38 +0000979
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000980 /* time or datetime where utcoffset() doesn't return None */
981 OFFSET_AWARE
Tim Peters2a799bf2002-12-16 20:18:38 +0000982} naivety;
983
Tim Peters14b69412002-12-22 18:10:22 +0000984/* Classify an object as to whether it's naive or offset-aware. See
Tim Peters2a799bf2002-12-16 20:18:38 +0000985 * the "naivety" typedef for details. If the type is aware, *offset is set
986 * to minutes east of UTC (as returned by the tzinfo.utcoffset() method).
Tim Peters14b69412002-12-22 18:10:22 +0000987 * If the type is offset-naive (or unknown, or error), *offset is set to 0.
Tim Peterse39a80c2002-12-30 21:28:52 +0000988 * tzinfoarg is the argument to pass to the tzinfo.utcoffset() method.
Tim Peters2a799bf2002-12-16 20:18:38 +0000989 */
990static naivety
Tim Peterse39a80c2002-12-30 21:28:52 +0000991classify_utcoffset(PyObject *op, PyObject *tzinfoarg, int *offset)
Tim Peters2a799bf2002-12-16 20:18:38 +0000992{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000993 int none;
994 PyObject *tzinfo;
Tim Peters2a799bf2002-12-16 20:18:38 +0000995
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000996 assert(tzinfoarg != NULL);
997 *offset = 0;
998 tzinfo = get_tzinfo_member(op); /* NULL means no tzinfo, not error */
999 if (tzinfo == Py_None)
1000 return OFFSET_NAIVE;
1001 if (tzinfo == NULL) {
1002 /* note that a datetime passes the PyDate_Check test */
1003 return (PyTime_Check(op) || PyDate_Check(op)) ?
1004 OFFSET_NAIVE : OFFSET_UNKNOWN;
1005 }
1006 *offset = call_utcoffset(tzinfo, tzinfoarg, &none);
1007 if (*offset == -1 && PyErr_Occurred())
1008 return OFFSET_ERROR;
1009 return none ? OFFSET_NAIVE : OFFSET_AWARE;
Tim Peters2a799bf2002-12-16 20:18:38 +00001010}
1011
Tim Peters00237032002-12-27 02:21:51 +00001012/* Classify two objects as to whether they're naive or offset-aware.
1013 * This isn't quite the same as calling classify_utcoffset() twice: for
1014 * binary operations (comparison and subtraction), we generally want to
1015 * ignore the tzinfo members if they're identical. This is by design,
1016 * so that results match "naive" expectations when mixing objects from a
1017 * single timezone. So in that case, this sets both offsets to 0 and
1018 * both naiveties to OFFSET_NAIVE.
1019 * The function returns 0 if everything's OK, and -1 on error.
1020 */
1021static int
1022classify_two_utcoffsets(PyObject *o1, int *offset1, naivety *n1,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001023 PyObject *tzinfoarg1,
1024 PyObject *o2, int *offset2, naivety *n2,
1025 PyObject *tzinfoarg2)
Tim Peters00237032002-12-27 02:21:51 +00001026{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001027 if (get_tzinfo_member(o1) == get_tzinfo_member(o2)) {
1028 *offset1 = *offset2 = 0;
1029 *n1 = *n2 = OFFSET_NAIVE;
1030 }
1031 else {
1032 *n1 = classify_utcoffset(o1, tzinfoarg1, offset1);
1033 if (*n1 == OFFSET_ERROR)
1034 return -1;
1035 *n2 = classify_utcoffset(o2, tzinfoarg2, offset2);
1036 if (*n2 == OFFSET_ERROR)
1037 return -1;
1038 }
1039 return 0;
Tim Peters00237032002-12-27 02:21:51 +00001040}
1041
Tim Peters2a799bf2002-12-16 20:18:38 +00001042/* repr is like "someclass(arg1, arg2)". If tzinfo isn't None,
1043 * stuff
1044 * ", tzinfo=" + repr(tzinfo)
1045 * before the closing ")".
1046 */
1047static PyObject *
1048append_keyword_tzinfo(PyObject *repr, PyObject *tzinfo)
1049{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001050 PyObject *temp;
Tim Peters2a799bf2002-12-16 20:18:38 +00001051
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001052 assert(PyString_Check(repr));
1053 assert(tzinfo);
1054 if (tzinfo == Py_None)
1055 return repr;
1056 /* Get rid of the trailing ')'. */
1057 assert(PyString_AsString(repr)[PyString_Size(repr)-1] == ')');
1058 temp = PyString_FromStringAndSize(PyString_AsString(repr),
1059 PyString_Size(repr) - 1);
1060 Py_DECREF(repr);
1061 if (temp == NULL)
1062 return NULL;
1063 repr = temp;
Tim Peters2a799bf2002-12-16 20:18:38 +00001064
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001065 /* Append ", tzinfo=". */
1066 PyString_ConcatAndDel(&repr, PyString_FromString(", tzinfo="));
Tim Peters2a799bf2002-12-16 20:18:38 +00001067
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001068 /* Append repr(tzinfo). */
1069 PyString_ConcatAndDel(&repr, PyObject_Repr(tzinfo));
Tim Peters2a799bf2002-12-16 20:18:38 +00001070
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001071 /* Add a closing paren. */
1072 PyString_ConcatAndDel(&repr, PyString_FromString(")"));
1073 return repr;
Tim Peters2a799bf2002-12-16 20:18:38 +00001074}
1075
1076/* ---------------------------------------------------------------------------
1077 * String format helpers.
1078 */
1079
1080static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00001081format_ctime(PyDateTime_Date *date, int hours, int minutes, int seconds)
Tim Peters2a799bf2002-12-16 20:18:38 +00001082{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001083 static const char *DayNames[] = {
1084 "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"
1085 };
1086 static const char *MonthNames[] = {
1087 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
1088 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
1089 };
Tim Peters2a799bf2002-12-16 20:18:38 +00001090
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001091 char buffer[128];
1092 int wday = weekday(GET_YEAR(date), GET_MONTH(date), GET_DAY(date));
Tim Peters2a799bf2002-12-16 20:18:38 +00001093
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001094 PyOS_snprintf(buffer, sizeof(buffer), "%s %s %2d %02d:%02d:%02d %04d",
1095 DayNames[wday], MonthNames[GET_MONTH(date) - 1],
1096 GET_DAY(date), hours, minutes, seconds,
1097 GET_YEAR(date));
1098 return PyString_FromString(buffer);
Tim Peters2a799bf2002-12-16 20:18:38 +00001099}
1100
1101/* Add an hours & minutes UTC offset string to buf. buf has no more than
1102 * buflen bytes remaining. The UTC offset is gotten by calling
1103 * tzinfo.uctoffset(tzinfoarg). If that returns None, \0 is stored into
1104 * *buf, and that's all. Else the returned value is checked for sanity (an
1105 * integer in range), and if that's OK it's converted to an hours & minutes
1106 * string of the form
1107 * sign HH sep MM
1108 * Returns 0 if everything is OK. If the return value from utcoffset() is
1109 * bogus, an appropriate exception is set and -1 is returned.
1110 */
1111static int
Tim Peters328fff72002-12-20 01:31:27 +00001112format_utcoffset(char *buf, size_t buflen, const char *sep,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001113 PyObject *tzinfo, PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +00001114{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001115 int offset;
1116 int hours;
1117 int minutes;
1118 char sign;
1119 int none;
Tim Peters2a799bf2002-12-16 20:18:38 +00001120
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001121 assert(buflen >= 1);
Gregory P. Smith9d534572008-06-11 07:41:16 +00001122
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001123 offset = call_utcoffset(tzinfo, tzinfoarg, &none);
1124 if (offset == -1 && PyErr_Occurred())
1125 return -1;
1126 if (none) {
1127 *buf = '\0';
1128 return 0;
1129 }
1130 sign = '+';
1131 if (offset < 0) {
1132 sign = '-';
1133 offset = - offset;
1134 }
1135 hours = divmod(offset, 60, &minutes);
1136 PyOS_snprintf(buf, buflen, "%c%02d%s%02d", sign, hours, sep, minutes);
1137 return 0;
Tim Peters2a799bf2002-12-16 20:18:38 +00001138}
1139
Skip Montanarofc070d22008-03-15 16:04:45 +00001140static PyObject *
1141make_freplacement(PyObject *object)
1142{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001143 char freplacement[64];
1144 if (PyTime_Check(object))
1145 sprintf(freplacement, "%06d", TIME_GET_MICROSECOND(object));
1146 else if (PyDateTime_Check(object))
1147 sprintf(freplacement, "%06d", DATE_GET_MICROSECOND(object));
1148 else
1149 sprintf(freplacement, "%06d", 0);
Skip Montanarofc070d22008-03-15 16:04:45 +00001150
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001151 return PyString_FromStringAndSize(freplacement, strlen(freplacement));
Skip Montanarofc070d22008-03-15 16:04:45 +00001152}
1153
Tim Peters2a799bf2002-12-16 20:18:38 +00001154/* I sure don't want to reproduce the strftime code from the time module,
1155 * so this imports the module and calls it. All the hair is due to
Skip Montanarofc070d22008-03-15 16:04:45 +00001156 * giving special meanings to the %z, %Z and %f format codes via a
1157 * preprocessing step on the format string.
Tim Petersbad8ff02002-12-30 20:52:32 +00001158 * tzinfoarg is the argument to pass to the object's tzinfo method, if
1159 * needed.
Tim Peters2a799bf2002-12-16 20:18:38 +00001160 */
1161static PyObject *
Gregory P. Smith137d8242008-06-02 04:05:52 +00001162wrap_strftime(PyObject *object, const char *format, size_t format_len,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001163 PyObject *timetuple, PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +00001164{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001165 PyObject *result = NULL; /* guilty until proved innocent */
Tim Peters2a799bf2002-12-16 20:18:38 +00001166
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001167 PyObject *zreplacement = NULL; /* py string, replacement for %z */
1168 PyObject *Zreplacement = NULL; /* py string, replacement for %Z */
1169 PyObject *freplacement = NULL; /* py string, replacement for %f */
Tim Peters2a799bf2002-12-16 20:18:38 +00001170
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001171 const char *pin; /* pointer to next char in input format */
1172 char ch; /* next char in input format */
Tim Peters2a799bf2002-12-16 20:18:38 +00001173
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001174 PyObject *newfmt = NULL; /* py string, the output format */
1175 char *pnew; /* pointer to available byte in output format */
1176 size_t totalnew; /* number bytes total in output format buffer,
1177 exclusive of trailing \0 */
1178 size_t usednew; /* number bytes used so far in output format buffer */
Tim Peters2a799bf2002-12-16 20:18:38 +00001179
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001180 const char *ptoappend; /* ptr to string to append to output buffer */
1181 size_t ntoappend; /* # of bytes to append to output buffer */
Tim Peters2a799bf2002-12-16 20:18:38 +00001182
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001183 assert(object && format && timetuple);
Tim Peters2a799bf2002-12-16 20:18:38 +00001184
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001185 /* Give up if the year is before 1900.
1186 * Python strftime() plays games with the year, and different
1187 * games depending on whether envar PYTHON2K is set. This makes
1188 * years before 1900 a nightmare, even if the platform strftime
1189 * supports them (and not all do).
1190 * We could get a lot farther here by avoiding Python's strftime
1191 * wrapper and calling the C strftime() directly, but that isn't
1192 * an option in the Python implementation of this module.
1193 */
1194 {
1195 long year;
1196 PyObject *pyyear = PySequence_GetItem(timetuple, 0);
1197 if (pyyear == NULL) return NULL;
1198 assert(PyInt_Check(pyyear));
1199 year = PyInt_AsLong(pyyear);
1200 Py_DECREF(pyyear);
1201 if (year < 1900) {
1202 PyErr_Format(PyExc_ValueError, "year=%ld is before "
1203 "1900; the datetime strftime() "
1204 "methods require year >= 1900",
1205 year);
1206 return NULL;
1207 }
1208 }
Tim Petersd6844152002-12-22 20:58:42 +00001209
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001210 /* Scan the input format, looking for %z/%Z/%f escapes, building
1211 * a new format. Since computing the replacements for those codes
1212 * is expensive, don't unless they're actually used.
1213 */
1214 if (format_len > INT_MAX - 1) {
1215 PyErr_NoMemory();
1216 goto Done;
1217 }
Gregory P. Smith9d534572008-06-11 07:41:16 +00001218
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001219 totalnew = format_len + 1; /* realistic if no %z/%Z/%f */
1220 newfmt = PyString_FromStringAndSize(NULL, totalnew);
1221 if (newfmt == NULL) goto Done;
1222 pnew = PyString_AsString(newfmt);
1223 usednew = 0;
Tim Peters2a799bf2002-12-16 20:18:38 +00001224
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001225 pin = format;
1226 while ((ch = *pin++) != '\0') {
1227 if (ch != '%') {
1228 ptoappend = pin - 1;
1229 ntoappend = 1;
1230 }
1231 else if ((ch = *pin++) == '\0') {
1232 /* There's a lone trailing %; doesn't make sense. */
1233 PyErr_SetString(PyExc_ValueError, "strftime format "
1234 "ends with raw %");
1235 goto Done;
1236 }
1237 /* A % has been seen and ch is the character after it. */
1238 else if (ch == 'z') {
1239 if (zreplacement == NULL) {
1240 /* format utcoffset */
1241 char buf[100];
1242 PyObject *tzinfo = get_tzinfo_member(object);
1243 zreplacement = PyString_FromString("");
1244 if (zreplacement == NULL) goto Done;
1245 if (tzinfo != Py_None && tzinfo != NULL) {
1246 assert(tzinfoarg != NULL);
1247 if (format_utcoffset(buf,
1248 sizeof(buf),
1249 "",
1250 tzinfo,
1251 tzinfoarg) < 0)
1252 goto Done;
1253 Py_DECREF(zreplacement);
1254 zreplacement = PyString_FromString(buf);
1255 if (zreplacement == NULL) goto Done;
1256 }
1257 }
1258 assert(zreplacement != NULL);
1259 ptoappend = PyString_AS_STRING(zreplacement);
1260 ntoappend = PyString_GET_SIZE(zreplacement);
1261 }
1262 else if (ch == 'Z') {
1263 /* format tzname */
1264 if (Zreplacement == NULL) {
1265 PyObject *tzinfo = get_tzinfo_member(object);
1266 Zreplacement = PyString_FromString("");
1267 if (Zreplacement == NULL) goto Done;
1268 if (tzinfo != Py_None && tzinfo != NULL) {
1269 PyObject *temp;
1270 assert(tzinfoarg != NULL);
1271 temp = call_tzname(tzinfo, tzinfoarg);
1272 if (temp == NULL) goto Done;
1273 if (temp != Py_None) {
1274 assert(PyString_Check(temp));
1275 /* Since the tzname is getting
1276 * stuffed into the format, we
1277 * have to double any % signs
1278 * so that strftime doesn't
1279 * treat them as format codes.
1280 */
1281 Py_DECREF(Zreplacement);
1282 Zreplacement = PyObject_CallMethod(
1283 temp, "replace",
1284 "ss", "%", "%%");
1285 Py_DECREF(temp);
1286 if (Zreplacement == NULL)
1287 goto Done;
1288 if (!PyString_Check(Zreplacement)) {
1289 PyErr_SetString(PyExc_TypeError, "tzname.replace() did not return a string");
1290 goto Done;
1291 }
1292 }
1293 else
1294 Py_DECREF(temp);
1295 }
1296 }
1297 assert(Zreplacement != NULL);
1298 ptoappend = PyString_AS_STRING(Zreplacement);
1299 ntoappend = PyString_GET_SIZE(Zreplacement);
1300 }
1301 else if (ch == 'f') {
1302 /* format microseconds */
1303 if (freplacement == NULL) {
1304 freplacement = make_freplacement(object);
1305 if (freplacement == NULL)
1306 goto Done;
1307 }
1308 assert(freplacement != NULL);
1309 assert(PyString_Check(freplacement));
1310 ptoappend = PyString_AS_STRING(freplacement);
1311 ntoappend = PyString_GET_SIZE(freplacement);
1312 }
1313 else {
1314 /* percent followed by neither z nor Z */
1315 ptoappend = pin - 2;
1316 ntoappend = 2;
1317 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001318
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001319 /* Append the ntoappend chars starting at ptoappend to
1320 * the new format.
1321 */
1322 assert(ptoappend != NULL);
1323 assert(ntoappend >= 0);
1324 if (ntoappend == 0)
1325 continue;
1326 while (usednew + ntoappend > totalnew) {
1327 size_t bigger = totalnew << 1;
1328 if ((bigger >> 1) != totalnew) { /* overflow */
1329 PyErr_NoMemory();
1330 goto Done;
1331 }
1332 if (_PyString_Resize(&newfmt, bigger) < 0)
1333 goto Done;
1334 totalnew = bigger;
1335 pnew = PyString_AsString(newfmt) + usednew;
1336 }
1337 memcpy(pnew, ptoappend, ntoappend);
1338 pnew += ntoappend;
1339 usednew += ntoappend;
1340 assert(usednew <= totalnew);
1341 } /* end while() */
Tim Peters2a799bf2002-12-16 20:18:38 +00001342
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001343 if (_PyString_Resize(&newfmt, usednew) < 0)
1344 goto Done;
1345 {
1346 PyObject *time = PyImport_ImportModuleNoBlock("time");
1347 if (time == NULL)
1348 goto Done;
1349 result = PyObject_CallMethod(time, "strftime", "OO",
1350 newfmt, timetuple);
1351 Py_DECREF(time);
1352 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001353 Done:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001354 Py_XDECREF(freplacement);
1355 Py_XDECREF(zreplacement);
1356 Py_XDECREF(Zreplacement);
1357 Py_XDECREF(newfmt);
1358 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001359}
1360
1361static char *
1362isoformat_date(PyDateTime_Date *dt, char buffer[], int bufflen)
1363{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001364 int x;
1365 x = PyOS_snprintf(buffer, bufflen,
1366 "%04d-%02d-%02d",
1367 GET_YEAR(dt), GET_MONTH(dt), GET_DAY(dt));
1368 assert(bufflen >= x);
1369 return buffer + x;
Tim Peters2a799bf2002-12-16 20:18:38 +00001370}
1371
Amaury Forgeot d'Arc8645a5c2009-12-29 22:03:38 +00001372static char *
Tim Peters2a799bf2002-12-16 20:18:38 +00001373isoformat_time(PyDateTime_DateTime *dt, char buffer[], int bufflen)
1374{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001375 int x;
1376 int us = DATE_GET_MICROSECOND(dt);
Tim Peters2a799bf2002-12-16 20:18:38 +00001377
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001378 x = PyOS_snprintf(buffer, bufflen,
1379 "%02d:%02d:%02d",
1380 DATE_GET_HOUR(dt),
1381 DATE_GET_MINUTE(dt),
1382 DATE_GET_SECOND(dt));
1383 assert(bufflen >= x);
1384 if (us)
1385 x += PyOS_snprintf(buffer + x, bufflen - x, ".%06d", us);
1386 assert(bufflen >= x);
1387 return buffer + x;
Tim Peters2a799bf2002-12-16 20:18:38 +00001388}
1389
1390/* ---------------------------------------------------------------------------
1391 * Wrap functions from the time module. These aren't directly available
1392 * from C. Perhaps they should be.
1393 */
1394
1395/* Call time.time() and return its result (a Python float). */
1396static PyObject *
Guido van Rossumbd43e912002-12-16 20:34:55 +00001397time_time(void)
Tim Peters2a799bf2002-12-16 20:18:38 +00001398{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001399 PyObject *result = NULL;
1400 PyObject *time = PyImport_ImportModuleNoBlock("time");
Tim Peters2a799bf2002-12-16 20:18:38 +00001401
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001402 if (time != NULL) {
1403 result = PyObject_CallMethod(time, "time", "()");
1404 Py_DECREF(time);
1405 }
1406 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001407}
1408
1409/* Build a time.struct_time. The weekday and day number are automatically
1410 * computed from the y,m,d args.
1411 */
1412static PyObject *
1413build_struct_time(int y, int m, int d, int hh, int mm, int ss, int dstflag)
1414{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001415 PyObject *time;
1416 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001417
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001418 time = PyImport_ImportModuleNoBlock("time");
1419 if (time != NULL) {
1420 result = PyObject_CallMethod(time, "struct_time",
1421 "((iiiiiiiii))",
1422 y, m, d,
1423 hh, mm, ss,
1424 weekday(y, m, d),
1425 days_before_month(y, m) + d,
1426 dstflag);
1427 Py_DECREF(time);
1428 }
1429 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001430}
1431
1432/* ---------------------------------------------------------------------------
1433 * Miscellaneous helpers.
1434 */
1435
1436/* For obscure reasons, we need to use tp_richcompare instead of tp_compare.
1437 * The comparisons here all most naturally compute a cmp()-like result.
1438 * This little helper turns that into a bool result for rich comparisons.
1439 */
1440static PyObject *
1441diff_to_bool(int diff, int op)
1442{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001443 PyObject *result;
1444 int istrue;
Tim Peters2a799bf2002-12-16 20:18:38 +00001445
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001446 switch (op) {
1447 case Py_EQ: istrue = diff == 0; break;
1448 case Py_NE: istrue = diff != 0; break;
1449 case Py_LE: istrue = diff <= 0; break;
1450 case Py_GE: istrue = diff >= 0; break;
1451 case Py_LT: istrue = diff < 0; break;
1452 case Py_GT: istrue = diff > 0; break;
1453 default:
1454 assert(! "op unknown");
1455 istrue = 0; /* To shut up compiler */
1456 }
1457 result = istrue ? Py_True : Py_False;
1458 Py_INCREF(result);
1459 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001460}
1461
Tim Peters07534a62003-02-07 22:50:28 +00001462/* Raises a "can't compare" TypeError and returns NULL. */
1463static PyObject *
1464cmperror(PyObject *a, PyObject *b)
1465{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001466 PyErr_Format(PyExc_TypeError,
1467 "can't compare %s to %s",
1468 Py_TYPE(a)->tp_name, Py_TYPE(b)->tp_name);
1469 return NULL;
Tim Peters07534a62003-02-07 22:50:28 +00001470}
1471
Tim Peters2a799bf2002-12-16 20:18:38 +00001472/* ---------------------------------------------------------------------------
Tim Peters2a799bf2002-12-16 20:18:38 +00001473 * Cached Python objects; these are set by the module init function.
1474 */
1475
1476/* Conversion factors. */
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001477static PyObject *us_per_us = NULL; /* 1 */
1478static PyObject *us_per_ms = NULL; /* 1000 */
1479static PyObject *us_per_second = NULL; /* 1000000 */
1480static PyObject *us_per_minute = NULL; /* 1e6 * 60 as Python int */
1481static PyObject *us_per_hour = NULL; /* 1e6 * 3600 as Python long */
1482static PyObject *us_per_day = NULL; /* 1e6 * 3600 * 24 as Python long */
1483static PyObject *us_per_week = NULL; /* 1e6*3600*24*7 as Python long */
Tim Peters2a799bf2002-12-16 20:18:38 +00001484static PyObject *seconds_per_day = NULL; /* 3600*24 as Python int */
1485
Tim Peters2a799bf2002-12-16 20:18:38 +00001486/* ---------------------------------------------------------------------------
1487 * Class implementations.
1488 */
1489
1490/*
1491 * PyDateTime_Delta implementation.
1492 */
1493
1494/* Convert a timedelta to a number of us,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001495 * (24*3600*self.days + self.seconds)*1000000 + self.microseconds
Tim Peters2a799bf2002-12-16 20:18:38 +00001496 * as a Python int or long.
1497 * Doing mixed-radix arithmetic by hand instead is excruciating in C,
1498 * due to ubiquitous overflow possibilities.
1499 */
1500static PyObject *
1501delta_to_microseconds(PyDateTime_Delta *self)
1502{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001503 PyObject *x1 = NULL;
1504 PyObject *x2 = NULL;
1505 PyObject *x3 = NULL;
1506 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001507
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001508 x1 = PyInt_FromLong(GET_TD_DAYS(self));
1509 if (x1 == NULL)
1510 goto Done;
1511 x2 = PyNumber_Multiply(x1, seconds_per_day); /* days in seconds */
1512 if (x2 == NULL)
1513 goto Done;
1514 Py_DECREF(x1);
1515 x1 = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001516
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001517 /* x2 has days in seconds */
1518 x1 = PyInt_FromLong(GET_TD_SECONDS(self)); /* seconds */
1519 if (x1 == NULL)
1520 goto Done;
1521 x3 = PyNumber_Add(x1, x2); /* days and seconds in seconds */
1522 if (x3 == NULL)
1523 goto Done;
1524 Py_DECREF(x1);
1525 Py_DECREF(x2);
1526 x2 = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001527
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001528 /* x3 has days+seconds in seconds */
1529 x1 = PyNumber_Multiply(x3, us_per_second); /* us */
1530 if (x1 == NULL)
1531 goto Done;
1532 Py_DECREF(x3);
1533 x3 = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001534
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001535 /* x1 has days+seconds in us */
1536 x2 = PyInt_FromLong(GET_TD_MICROSECONDS(self));
1537 if (x2 == NULL)
1538 goto Done;
1539 result = PyNumber_Add(x1, x2);
Serhiy Storchaka5ef883b2017-10-23 19:57:04 +03001540 assert(result == NULL || PyInt_CheckExact(result) || PyLong_CheckExact(result));
Tim Peters2a799bf2002-12-16 20:18:38 +00001541
1542Done:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001543 Py_XDECREF(x1);
1544 Py_XDECREF(x2);
1545 Py_XDECREF(x3);
1546 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001547}
1548
1549/* Convert a number of us (as a Python int or long) to a timedelta.
1550 */
1551static PyObject *
Tim Petersb0c854d2003-05-17 15:57:00 +00001552microseconds_to_delta_ex(PyObject *pyus, PyTypeObject *type)
Tim Peters2a799bf2002-12-16 20:18:38 +00001553{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001554 int us;
1555 int s;
1556 int d;
1557 long temp;
Tim Peters2a799bf2002-12-16 20:18:38 +00001558
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001559 PyObject *tuple = NULL;
1560 PyObject *num = NULL;
1561 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001562
Serhiy Storchaka5ef883b2017-10-23 19:57:04 +03001563 assert(PyInt_CheckExact(pyus) || PyLong_CheckExact(pyus));
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001564 tuple = PyNumber_Divmod(pyus, us_per_second);
1565 if (tuple == NULL)
1566 goto Done;
Tim Peters2a799bf2002-12-16 20:18:38 +00001567
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001568 num = PyTuple_GetItem(tuple, 1); /* us */
1569 if (num == NULL)
1570 goto Done;
1571 temp = PyLong_AsLong(num);
1572 num = NULL;
1573 if (temp == -1 && PyErr_Occurred())
1574 goto Done;
1575 assert(0 <= temp && temp < 1000000);
1576 us = (int)temp;
1577 if (us < 0) {
1578 /* The divisor was positive, so this must be an error. */
1579 assert(PyErr_Occurred());
1580 goto Done;
1581 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001582
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001583 num = PyTuple_GetItem(tuple, 0); /* leftover seconds */
1584 if (num == NULL)
1585 goto Done;
1586 Py_INCREF(num);
1587 Py_DECREF(tuple);
Tim Peters2a799bf2002-12-16 20:18:38 +00001588
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001589 tuple = PyNumber_Divmod(num, seconds_per_day);
1590 if (tuple == NULL)
1591 goto Done;
1592 Py_DECREF(num);
Tim Peters2a799bf2002-12-16 20:18:38 +00001593
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001594 num = PyTuple_GetItem(tuple, 1); /* seconds */
1595 if (num == NULL)
1596 goto Done;
1597 temp = PyLong_AsLong(num);
1598 num = NULL;
1599 if (temp == -1 && PyErr_Occurred())
1600 goto Done;
1601 assert(0 <= temp && temp < 24*3600);
1602 s = (int)temp;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001603
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001604 if (s < 0) {
1605 /* The divisor was positive, so this must be an error. */
1606 assert(PyErr_Occurred());
1607 goto Done;
1608 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001609
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001610 num = PyTuple_GetItem(tuple, 0); /* leftover days */
1611 if (num == NULL)
1612 goto Done;
1613 Py_INCREF(num);
1614 temp = PyLong_AsLong(num);
1615 if (temp == -1 && PyErr_Occurred())
1616 goto Done;
1617 d = (int)temp;
1618 if ((long)d != temp) {
1619 PyErr_SetString(PyExc_OverflowError, "normalized days too "
1620 "large to fit in a C int");
1621 goto Done;
1622 }
1623 result = new_delta_ex(d, s, us, 0, type);
Tim Peters2a799bf2002-12-16 20:18:38 +00001624
1625Done:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001626 Py_XDECREF(tuple);
1627 Py_XDECREF(num);
1628 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001629}
1630
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001631#define microseconds_to_delta(pymicros) \
1632 microseconds_to_delta_ex(pymicros, &PyDateTime_DeltaType)
Tim Petersb0c854d2003-05-17 15:57:00 +00001633
Tim Peters2a799bf2002-12-16 20:18:38 +00001634static PyObject *
1635multiply_int_timedelta(PyObject *intobj, PyDateTime_Delta *delta)
1636{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001637 PyObject *pyus_in;
1638 PyObject *pyus_out;
1639 PyObject *result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001640
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001641 pyus_in = delta_to_microseconds(delta);
1642 if (pyus_in == NULL)
1643 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001644
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001645 pyus_out = PyNumber_Multiply(pyus_in, intobj);
1646 Py_DECREF(pyus_in);
1647 if (pyus_out == NULL)
1648 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001649
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001650 result = microseconds_to_delta(pyus_out);
1651 Py_DECREF(pyus_out);
1652 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001653}
1654
1655static PyObject *
1656divide_timedelta_int(PyDateTime_Delta *delta, PyObject *intobj)
1657{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001658 PyObject *pyus_in;
1659 PyObject *pyus_out;
1660 PyObject *result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001661
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001662 pyus_in = delta_to_microseconds(delta);
1663 if (pyus_in == NULL)
1664 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001665
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001666 pyus_out = PyNumber_FloorDivide(pyus_in, intobj);
1667 Py_DECREF(pyus_in);
1668 if (pyus_out == NULL)
1669 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001670
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001671 result = microseconds_to_delta(pyus_out);
1672 Py_DECREF(pyus_out);
1673 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001674}
1675
1676static PyObject *
1677delta_add(PyObject *left, PyObject *right)
1678{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001679 PyObject *result = Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00001680
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001681 if (PyDelta_Check(left) && PyDelta_Check(right)) {
1682 /* delta + delta */
1683 /* The C-level additions can't overflow because of the
1684 * invariant bounds.
1685 */
1686 int days = GET_TD_DAYS(left) + GET_TD_DAYS(right);
1687 int seconds = GET_TD_SECONDS(left) + GET_TD_SECONDS(right);
1688 int microseconds = GET_TD_MICROSECONDS(left) +
1689 GET_TD_MICROSECONDS(right);
1690 result = new_delta(days, seconds, microseconds, 1);
1691 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001692
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001693 if (result == Py_NotImplemented)
1694 Py_INCREF(result);
1695 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001696}
1697
1698static PyObject *
1699delta_negative(PyDateTime_Delta *self)
1700{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001701 return new_delta(-GET_TD_DAYS(self),
1702 -GET_TD_SECONDS(self),
1703 -GET_TD_MICROSECONDS(self),
1704 1);
Tim Peters2a799bf2002-12-16 20:18:38 +00001705}
1706
1707static PyObject *
1708delta_positive(PyDateTime_Delta *self)
1709{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001710 /* Could optimize this (by returning self) if this isn't a
1711 * subclass -- but who uses unary + ? Approximately nobody.
1712 */
1713 return new_delta(GET_TD_DAYS(self),
1714 GET_TD_SECONDS(self),
1715 GET_TD_MICROSECONDS(self),
1716 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00001717}
1718
1719static PyObject *
1720delta_abs(PyDateTime_Delta *self)
1721{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001722 PyObject *result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001723
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001724 assert(GET_TD_MICROSECONDS(self) >= 0);
1725 assert(GET_TD_SECONDS(self) >= 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00001726
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001727 if (GET_TD_DAYS(self) < 0)
1728 result = delta_negative(self);
1729 else
1730 result = delta_positive(self);
Tim Peters2a799bf2002-12-16 20:18:38 +00001731
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001732 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001733}
1734
1735static PyObject *
1736delta_subtract(PyObject *left, PyObject *right)
1737{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001738 PyObject *result = Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00001739
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001740 if (PyDelta_Check(left) && PyDelta_Check(right)) {
1741 /* delta - delta */
Alexander Belopolsky07019bc2011-04-05 22:12:22 -04001742 /* The C-level additions can't overflow because of the
1743 * invariant bounds.
1744 */
1745 int days = GET_TD_DAYS(left) - GET_TD_DAYS(right);
1746 int seconds = GET_TD_SECONDS(left) - GET_TD_SECONDS(right);
1747 int microseconds = GET_TD_MICROSECONDS(left) -
1748 GET_TD_MICROSECONDS(right);
1749 result = new_delta(days, seconds, microseconds, 1);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001750 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001751
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001752 if (result == Py_NotImplemented)
1753 Py_INCREF(result);
1754 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001755}
1756
1757/* This is more natural as a tp_compare, but doesn't work then: for whatever
1758 * reason, Python's try_3way_compare ignores tp_compare unless
1759 * PyInstance_Check returns true, but these aren't old-style classes.
1760 */
1761static PyObject *
1762delta_richcompare(PyDateTime_Delta *self, PyObject *other, int op)
1763{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001764 int diff = 42; /* nonsense */
Tim Peters2a799bf2002-12-16 20:18:38 +00001765
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001766 if (PyDelta_Check(other)) {
1767 diff = GET_TD_DAYS(self) - GET_TD_DAYS(other);
1768 if (diff == 0) {
1769 diff = GET_TD_SECONDS(self) - GET_TD_SECONDS(other);
1770 if (diff == 0)
1771 diff = GET_TD_MICROSECONDS(self) -
1772 GET_TD_MICROSECONDS(other);
1773 }
1774 }
1775 else if (op == Py_EQ || op == Py_NE)
1776 diff = 1; /* any non-zero value will do */
Tim Peters07534a62003-02-07 22:50:28 +00001777
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001778 else /* stop this from falling back to address comparison */
1779 return cmperror((PyObject *)self, other);
Tim Peters07534a62003-02-07 22:50:28 +00001780
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001781 return diff_to_bool(diff, op);
Tim Peters2a799bf2002-12-16 20:18:38 +00001782}
1783
1784static PyObject *delta_getstate(PyDateTime_Delta *self);
1785
1786static long
1787delta_hash(PyDateTime_Delta *self)
1788{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001789 if (self->hashcode == -1) {
1790 PyObject *temp = delta_getstate(self);
1791 if (temp != NULL) {
1792 self->hashcode = PyObject_Hash(temp);
1793 Py_DECREF(temp);
1794 }
1795 }
1796 return self->hashcode;
Tim Peters2a799bf2002-12-16 20:18:38 +00001797}
1798
1799static PyObject *
1800delta_multiply(PyObject *left, PyObject *right)
1801{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001802 PyObject *result = Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00001803
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001804 if (PyDelta_Check(left)) {
1805 /* delta * ??? */
1806 if (PyInt_Check(right) || PyLong_Check(right))
1807 result = multiply_int_timedelta(right,
1808 (PyDateTime_Delta *) left);
1809 }
1810 else if (PyInt_Check(left) || PyLong_Check(left))
1811 result = multiply_int_timedelta(left,
1812 (PyDateTime_Delta *) right);
Tim Peters2a799bf2002-12-16 20:18:38 +00001813
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001814 if (result == Py_NotImplemented)
1815 Py_INCREF(result);
1816 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001817}
1818
1819static PyObject *
1820delta_divide(PyObject *left, PyObject *right)
1821{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001822 PyObject *result = Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00001823
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001824 if (PyDelta_Check(left)) {
1825 /* delta * ??? */
1826 if (PyInt_Check(right) || PyLong_Check(right))
1827 result = divide_timedelta_int(
1828 (PyDateTime_Delta *)left,
1829 right);
1830 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001831
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001832 if (result == Py_NotImplemented)
1833 Py_INCREF(result);
1834 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001835}
1836
1837/* Fold in the value of the tag ("seconds", "weeks", etc) component of a
1838 * timedelta constructor. sofar is the # of microseconds accounted for
1839 * so far, and there are factor microseconds per current unit, the number
1840 * of which is given by num. num * factor is added to sofar in a
1841 * numerically careful way, and that's the result. Any fractional
1842 * microseconds left over (this can happen if num is a float type) are
1843 * added into *leftover.
1844 * Note that there are many ways this can give an error (NULL) return.
1845 */
1846static PyObject *
1847accum(const char* tag, PyObject *sofar, PyObject *num, PyObject *factor,
1848 double *leftover)
1849{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001850 PyObject *prod;
1851 PyObject *sum;
Tim Peters2a799bf2002-12-16 20:18:38 +00001852
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001853 assert(num != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +00001854
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001855 if (PyInt_Check(num) || PyLong_Check(num)) {
Serhiy Storchaka5ef883b2017-10-23 19:57:04 +03001856 prod = PyNumber_Multiply(factor, num);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001857 if (prod == NULL)
1858 return NULL;
Serhiy Storchaka5ef883b2017-10-23 19:57:04 +03001859 assert(PyInt_CheckExact(prod) || PyLong_CheckExact(prod));
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001860 sum = PyNumber_Add(sofar, prod);
1861 Py_DECREF(prod);
Serhiy Storchaka5ef883b2017-10-23 19:57:04 +03001862 assert(sum == NULL || PyInt_CheckExact(sum) || PyLong_CheckExact(sum));
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001863 return sum;
1864 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001865
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001866 if (PyFloat_Check(num)) {
1867 double dnum;
1868 double fracpart;
1869 double intpart;
1870 PyObject *x;
1871 PyObject *y;
Tim Peters2a799bf2002-12-16 20:18:38 +00001872
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001873 /* The Plan: decompose num into an integer part and a
1874 * fractional part, num = intpart + fracpart.
1875 * Then num * factor ==
1876 * intpart * factor + fracpart * factor
1877 * and the LHS can be computed exactly in long arithmetic.
1878 * The RHS is again broken into an int part and frac part.
1879 * and the frac part is added into *leftover.
1880 */
1881 dnum = PyFloat_AsDouble(num);
1882 if (dnum == -1.0 && PyErr_Occurred())
1883 return NULL;
1884 fracpart = modf(dnum, &intpart);
1885 x = PyLong_FromDouble(intpart);
1886 if (x == NULL)
1887 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001888
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001889 prod = PyNumber_Multiply(x, factor);
1890 Py_DECREF(x);
1891 if (prod == NULL)
1892 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001893
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001894 sum = PyNumber_Add(sofar, prod);
1895 Py_DECREF(prod);
1896 if (sum == NULL)
1897 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001898
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001899 if (fracpart == 0.0)
1900 return sum;
1901 /* So far we've lost no information. Dealing with the
1902 * fractional part requires float arithmetic, and may
1903 * lose a little info.
1904 */
Serhiy Storchaka5ef883b2017-10-23 19:57:04 +03001905 assert(PyInt_CheckExact(factor) || PyLong_CheckExact(factor));
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001906 if (PyInt_Check(factor))
1907 dnum = (double)PyInt_AsLong(factor);
1908 else
1909 dnum = PyLong_AsDouble(factor);
Tim Peters2a799bf2002-12-16 20:18:38 +00001910
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001911 dnum *= fracpart;
1912 fracpart = modf(dnum, &intpart);
1913 x = PyLong_FromDouble(intpart);
1914 if (x == NULL) {
1915 Py_DECREF(sum);
1916 return NULL;
1917 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001918
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001919 y = PyNumber_Add(sum, x);
1920 Py_DECREF(sum);
1921 Py_DECREF(x);
1922 *leftover += fracpart;
Serhiy Storchaka5ef883b2017-10-23 19:57:04 +03001923 assert(y == NULL || PyInt_CheckExact(y) || PyLong_CheckExact(y));
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001924 return y;
1925 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001926
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001927 PyErr_Format(PyExc_TypeError,
1928 "unsupported type for timedelta %s component: %s",
1929 tag, Py_TYPE(num)->tp_name);
1930 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001931}
1932
1933static PyObject *
1934delta_new(PyTypeObject *type, PyObject *args, PyObject *kw)
1935{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001936 PyObject *self = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001937
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001938 /* Argument objects. */
1939 PyObject *day = NULL;
1940 PyObject *second = NULL;
1941 PyObject *us = NULL;
1942 PyObject *ms = NULL;
1943 PyObject *minute = NULL;
1944 PyObject *hour = NULL;
1945 PyObject *week = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001946
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001947 PyObject *x = NULL; /* running sum of microseconds */
1948 PyObject *y = NULL; /* temp sum of microseconds */
1949 double leftover_us = 0.0;
Tim Peters2a799bf2002-12-16 20:18:38 +00001950
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001951 static char *keywords[] = {
1952 "days", "seconds", "microseconds", "milliseconds",
1953 "minutes", "hours", "weeks", NULL
1954 };
Tim Peters2a799bf2002-12-16 20:18:38 +00001955
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001956 if (PyArg_ParseTupleAndKeywords(args, kw, "|OOOOOOO:__new__",
1957 keywords,
1958 &day, &second, &us,
1959 &ms, &minute, &hour, &week) == 0)
1960 goto Done;
Tim Peters2a799bf2002-12-16 20:18:38 +00001961
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001962 x = PyInt_FromLong(0);
1963 if (x == NULL)
1964 goto Done;
Tim Peters2a799bf2002-12-16 20:18:38 +00001965
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001966#define CLEANUP \
1967 Py_DECREF(x); \
1968 x = y; \
1969 if (x == NULL) \
1970 goto Done
Tim Peters2a799bf2002-12-16 20:18:38 +00001971
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001972 if (us) {
1973 y = accum("microseconds", x, us, us_per_us, &leftover_us);
1974 CLEANUP;
1975 }
1976 if (ms) {
1977 y = accum("milliseconds", x, ms, us_per_ms, &leftover_us);
1978 CLEANUP;
1979 }
1980 if (second) {
1981 y = accum("seconds", x, second, us_per_second, &leftover_us);
1982 CLEANUP;
1983 }
1984 if (minute) {
1985 y = accum("minutes", x, minute, us_per_minute, &leftover_us);
1986 CLEANUP;
1987 }
1988 if (hour) {
1989 y = accum("hours", x, hour, us_per_hour, &leftover_us);
1990 CLEANUP;
1991 }
1992 if (day) {
1993 y = accum("days", x, day, us_per_day, &leftover_us);
1994 CLEANUP;
1995 }
1996 if (week) {
1997 y = accum("weeks", x, week, us_per_week, &leftover_us);
1998 CLEANUP;
1999 }
2000 if (leftover_us) {
2001 /* Round to nearest whole # of us, and add into x. */
2002 PyObject *temp = PyLong_FromLong(round_to_long(leftover_us));
2003 if (temp == NULL) {
2004 Py_DECREF(x);
2005 goto Done;
2006 }
2007 y = PyNumber_Add(x, temp);
2008 Py_DECREF(temp);
2009 CLEANUP;
2010 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002011
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002012 self = microseconds_to_delta_ex(x, type);
2013 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00002014Done:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002015 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00002016
2017#undef CLEANUP
2018}
2019
2020static int
2021delta_nonzero(PyDateTime_Delta *self)
2022{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002023 return (GET_TD_DAYS(self) != 0
2024 || GET_TD_SECONDS(self) != 0
2025 || GET_TD_MICROSECONDS(self) != 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00002026}
2027
2028static PyObject *
2029delta_repr(PyDateTime_Delta *self)
2030{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002031 if (GET_TD_MICROSECONDS(self) != 0)
2032 return PyString_FromFormat("%s(%d, %d, %d)",
2033 Py_TYPE(self)->tp_name,
2034 GET_TD_DAYS(self),
2035 GET_TD_SECONDS(self),
2036 GET_TD_MICROSECONDS(self));
2037 if (GET_TD_SECONDS(self) != 0)
2038 return PyString_FromFormat("%s(%d, %d)",
2039 Py_TYPE(self)->tp_name,
2040 GET_TD_DAYS(self),
2041 GET_TD_SECONDS(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002042
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002043 return PyString_FromFormat("%s(%d)",
2044 Py_TYPE(self)->tp_name,
2045 GET_TD_DAYS(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002046}
2047
2048static PyObject *
2049delta_str(PyDateTime_Delta *self)
2050{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002051 int days = GET_TD_DAYS(self);
2052 int seconds = GET_TD_SECONDS(self);
2053 int us = GET_TD_MICROSECONDS(self);
2054 int hours;
2055 int minutes;
2056 char buf[100];
2057 char *pbuf = buf;
2058 size_t buflen = sizeof(buf);
2059 int n;
Tim Peters2a799bf2002-12-16 20:18:38 +00002060
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002061 minutes = divmod(seconds, 60, &seconds);
2062 hours = divmod(minutes, 60, &minutes);
Tim Peters2a799bf2002-12-16 20:18:38 +00002063
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002064 if (days) {
2065 n = PyOS_snprintf(pbuf, buflen, "%d day%s, ", days,
2066 (days == 1 || days == -1) ? "" : "s");
2067 if (n < 0 || (size_t)n >= buflen)
2068 goto Fail;
2069 pbuf += n;
2070 buflen -= (size_t)n;
2071 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002072
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002073 n = PyOS_snprintf(pbuf, buflen, "%d:%02d:%02d",
2074 hours, minutes, seconds);
2075 if (n < 0 || (size_t)n >= buflen)
2076 goto Fail;
2077 pbuf += n;
2078 buflen -= (size_t)n;
Tim Peters2a799bf2002-12-16 20:18:38 +00002079
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002080 if (us) {
2081 n = PyOS_snprintf(pbuf, buflen, ".%06d", us);
2082 if (n < 0 || (size_t)n >= buflen)
2083 goto Fail;
2084 pbuf += n;
2085 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002086
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002087 return PyString_FromStringAndSize(buf, pbuf - buf);
Tim Petersba873472002-12-18 20:19:21 +00002088
2089 Fail:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002090 PyErr_SetString(PyExc_SystemError, "goofy result from PyOS_snprintf");
2091 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002092}
2093
Tim Peters371935f2003-02-01 01:52:50 +00002094/* Pickle support, a simple use of __reduce__. */
2095
Tim Petersb57f8f02003-02-01 02:54:15 +00002096/* __getstate__ isn't exposed */
Tim Peters2a799bf2002-12-16 20:18:38 +00002097static PyObject *
2098delta_getstate(PyDateTime_Delta *self)
2099{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002100 return Py_BuildValue("iii", GET_TD_DAYS(self),
2101 GET_TD_SECONDS(self),
2102 GET_TD_MICROSECONDS(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002103}
2104
Tim Peters2a799bf2002-12-16 20:18:38 +00002105static PyObject *
Antoine Pitroubcfaf802009-11-25 22:59:36 +00002106delta_total_seconds(PyObject *self)
2107{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002108 PyObject *total_seconds;
2109 PyObject *total_microseconds;
2110 PyObject *one_million;
Mark Dickinson7000e9e2010-05-09 09:30:06 +00002111
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002112 total_microseconds = delta_to_microseconds((PyDateTime_Delta *)self);
2113 if (total_microseconds == NULL)
2114 return NULL;
Mark Dickinson7000e9e2010-05-09 09:30:06 +00002115
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002116 one_million = PyLong_FromLong(1000000L);
2117 if (one_million == NULL) {
2118 Py_DECREF(total_microseconds);
2119 return NULL;
2120 }
Mark Dickinson7000e9e2010-05-09 09:30:06 +00002121
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002122 total_seconds = PyNumber_TrueDivide(total_microseconds, one_million);
Mark Dickinson7000e9e2010-05-09 09:30:06 +00002123
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002124 Py_DECREF(total_microseconds);
2125 Py_DECREF(one_million);
2126 return total_seconds;
Antoine Pitroubcfaf802009-11-25 22:59:36 +00002127}
2128
2129static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002130delta_reduce(PyDateTime_Delta* self)
2131{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002132 return Py_BuildValue("ON", Py_TYPE(self), delta_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002133}
2134
2135#define OFFSET(field) offsetof(PyDateTime_Delta, field)
2136
2137static PyMemberDef delta_members[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002138
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002139 {"days", T_INT, OFFSET(days), READONLY,
2140 PyDoc_STR("Number of days.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002141
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002142 {"seconds", T_INT, OFFSET(seconds), READONLY,
2143 PyDoc_STR("Number of seconds (>= 0 and less than 1 day).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002144
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002145 {"microseconds", T_INT, OFFSET(microseconds), READONLY,
2146 PyDoc_STR("Number of microseconds (>= 0 and less than 1 second).")},
2147 {NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00002148};
2149
2150static PyMethodDef delta_methods[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002151 {"total_seconds", (PyCFunction)delta_total_seconds, METH_NOARGS,
2152 PyDoc_STR("Total seconds in the duration.")},
Antoine Pitroubcfaf802009-11-25 22:59:36 +00002153
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002154 {"__reduce__", (PyCFunction)delta_reduce, METH_NOARGS,
2155 PyDoc_STR("__reduce__() -> (cls, state)")},
Guido van Rossum177e41a2003-01-30 22:06:23 +00002156
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002157 {NULL, NULL},
Tim Peters2a799bf2002-12-16 20:18:38 +00002158};
2159
2160static char delta_doc[] =
2161PyDoc_STR("Difference between two datetime values.");
2162
2163static PyNumberMethods delta_as_number = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002164 delta_add, /* nb_add */
2165 delta_subtract, /* nb_subtract */
2166 delta_multiply, /* nb_multiply */
2167 delta_divide, /* nb_divide */
2168 0, /* nb_remainder */
2169 0, /* nb_divmod */
2170 0, /* nb_power */
2171 (unaryfunc)delta_negative, /* nb_negative */
2172 (unaryfunc)delta_positive, /* nb_positive */
2173 (unaryfunc)delta_abs, /* nb_absolute */
2174 (inquiry)delta_nonzero, /* nb_nonzero */
2175 0, /*nb_invert*/
2176 0, /*nb_lshift*/
2177 0, /*nb_rshift*/
2178 0, /*nb_and*/
2179 0, /*nb_xor*/
2180 0, /*nb_or*/
2181 0, /*nb_coerce*/
2182 0, /*nb_int*/
2183 0, /*nb_long*/
2184 0, /*nb_float*/
2185 0, /*nb_oct*/
2186 0, /*nb_hex*/
2187 0, /*nb_inplace_add*/
2188 0, /*nb_inplace_subtract*/
2189 0, /*nb_inplace_multiply*/
2190 0, /*nb_inplace_divide*/
2191 0, /*nb_inplace_remainder*/
2192 0, /*nb_inplace_power*/
2193 0, /*nb_inplace_lshift*/
2194 0, /*nb_inplace_rshift*/
2195 0, /*nb_inplace_and*/
2196 0, /*nb_inplace_xor*/
2197 0, /*nb_inplace_or*/
2198 delta_divide, /* nb_floor_divide */
2199 0, /* nb_true_divide */
2200 0, /* nb_inplace_floor_divide */
2201 0, /* nb_inplace_true_divide */
Tim Peters2a799bf2002-12-16 20:18:38 +00002202};
2203
2204static PyTypeObject PyDateTime_DeltaType = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002205 PyVarObject_HEAD_INIT(NULL, 0)
2206 "datetime.timedelta", /* tp_name */
2207 sizeof(PyDateTime_Delta), /* tp_basicsize */
2208 0, /* tp_itemsize */
2209 0, /* tp_dealloc */
2210 0, /* tp_print */
2211 0, /* tp_getattr */
2212 0, /* tp_setattr */
2213 0, /* tp_compare */
2214 (reprfunc)delta_repr, /* tp_repr */
2215 &delta_as_number, /* tp_as_number */
2216 0, /* tp_as_sequence */
2217 0, /* tp_as_mapping */
2218 (hashfunc)delta_hash, /* tp_hash */
2219 0, /* tp_call */
2220 (reprfunc)delta_str, /* tp_str */
2221 PyObject_GenericGetAttr, /* tp_getattro */
2222 0, /* tp_setattro */
2223 0, /* tp_as_buffer */
2224 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
2225 Py_TPFLAGS_BASETYPE, /* tp_flags */
2226 delta_doc, /* tp_doc */
2227 0, /* tp_traverse */
2228 0, /* tp_clear */
2229 (richcmpfunc)delta_richcompare, /* tp_richcompare */
2230 0, /* tp_weaklistoffset */
2231 0, /* tp_iter */
2232 0, /* tp_iternext */
2233 delta_methods, /* tp_methods */
2234 delta_members, /* tp_members */
2235 0, /* tp_getset */
2236 0, /* tp_base */
2237 0, /* tp_dict */
2238 0, /* tp_descr_get */
2239 0, /* tp_descr_set */
2240 0, /* tp_dictoffset */
2241 0, /* tp_init */
2242 0, /* tp_alloc */
2243 delta_new, /* tp_new */
2244 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00002245};
2246
2247/*
2248 * PyDateTime_Date implementation.
2249 */
2250
2251/* Accessor properties. */
2252
2253static PyObject *
2254date_year(PyDateTime_Date *self, void *unused)
2255{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002256 return PyInt_FromLong(GET_YEAR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002257}
2258
2259static PyObject *
2260date_month(PyDateTime_Date *self, void *unused)
2261{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002262 return PyInt_FromLong(GET_MONTH(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002263}
2264
2265static PyObject *
2266date_day(PyDateTime_Date *self, void *unused)
2267{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002268 return PyInt_FromLong(GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002269}
2270
2271static PyGetSetDef date_getset[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002272 {"year", (getter)date_year},
2273 {"month", (getter)date_month},
2274 {"day", (getter)date_day},
2275 {NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00002276};
2277
2278/* Constructors. */
2279
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00002280static char *date_kws[] = {"year", "month", "day", NULL};
Tim Peters12bf3392002-12-24 05:41:27 +00002281
Tim Peters2a799bf2002-12-16 20:18:38 +00002282static PyObject *
2283date_new(PyTypeObject *type, PyObject *args, PyObject *kw)
2284{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002285 PyObject *self = NULL;
2286 PyObject *state;
2287 int year;
2288 int month;
2289 int day;
Tim Peters2a799bf2002-12-16 20:18:38 +00002290
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002291 /* Check for invocation from pickle with __getstate__ state */
2292 if (PyTuple_GET_SIZE(args) == 1 &&
2293 PyString_Check(state = PyTuple_GET_ITEM(args, 0)) &&
2294 PyString_GET_SIZE(state) == _PyDateTime_DATE_DATASIZE &&
2295 MONTH_IS_SANE(PyString_AS_STRING(state)[2]))
2296 {
2297 PyDateTime_Date *me;
Tim Peters70533e22003-02-01 04:40:04 +00002298
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002299 me = (PyDateTime_Date *) (type->tp_alloc(type, 0));
2300 if (me != NULL) {
2301 char *pdata = PyString_AS_STRING(state);
2302 memcpy(me->data, pdata, _PyDateTime_DATE_DATASIZE);
2303 me->hashcode = -1;
2304 }
2305 return (PyObject *)me;
2306 }
Guido van Rossum177e41a2003-01-30 22:06:23 +00002307
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002308 if (PyArg_ParseTupleAndKeywords(args, kw, "iii", date_kws,
2309 &year, &month, &day)) {
2310 if (check_date_args(year, month, day) < 0)
2311 return NULL;
2312 self = new_date_ex(year, month, day, type);
2313 }
2314 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00002315}
2316
2317/* Return new date from localtime(t). */
2318static PyObject *
Tim Peters1b6f7a92004-06-20 02:50:16 +00002319date_local_from_time_t(PyObject *cls, double ts)
Tim Peters2a799bf2002-12-16 20:18:38 +00002320{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002321 struct tm *tm;
2322 time_t t;
2323 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002324
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002325 t = _PyTime_DoubleToTimet(ts);
2326 if (t == (time_t)-1 && PyErr_Occurred())
2327 return NULL;
2328 tm = localtime(&t);
2329 if (tm)
2330 result = PyObject_CallFunction(cls, "iii",
2331 tm->tm_year + 1900,
2332 tm->tm_mon + 1,
2333 tm->tm_mday);
2334 else
2335 PyErr_SetString(PyExc_ValueError,
2336 "timestamp out of range for "
2337 "platform localtime() function");
2338 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002339}
2340
2341/* Return new date from current time.
2342 * We say this is equivalent to fromtimestamp(time.time()), and the
2343 * only way to be sure of that is to *call* time.time(). That's not
2344 * generally the same as calling C's time.
2345 */
2346static PyObject *
2347date_today(PyObject *cls, PyObject *dummy)
2348{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002349 PyObject *time;
2350 PyObject *result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002351
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002352 time = time_time();
2353 if (time == NULL)
2354 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002355
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002356 /* Note well: today() is a class method, so this may not call
2357 * date.fromtimestamp. For example, it may call
2358 * datetime.fromtimestamp. That's why we need all the accuracy
2359 * time.time() delivers; if someone were gonzo about optimization,
2360 * date.today() could get away with plain C time().
2361 */
2362 result = PyObject_CallMethod(cls, "fromtimestamp", "O", time);
2363 Py_DECREF(time);
2364 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002365}
2366
2367/* Return new date from given timestamp (Python timestamp -- a double). */
2368static PyObject *
2369date_fromtimestamp(PyObject *cls, PyObject *args)
2370{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002371 double timestamp;
2372 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002373
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002374 if (PyArg_ParseTuple(args, "d:fromtimestamp", &timestamp))
2375 result = date_local_from_time_t(cls, timestamp);
2376 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002377}
2378
2379/* Return new date from proleptic Gregorian ordinal. Raises ValueError if
2380 * the ordinal is out of range.
2381 */
2382static PyObject *
2383date_fromordinal(PyObject *cls, PyObject *args)
2384{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002385 PyObject *result = NULL;
2386 int ordinal;
Tim Peters2a799bf2002-12-16 20:18:38 +00002387
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002388 if (PyArg_ParseTuple(args, "i:fromordinal", &ordinal)) {
2389 int year;
2390 int month;
2391 int day;
Tim Peters2a799bf2002-12-16 20:18:38 +00002392
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002393 if (ordinal < 1)
2394 PyErr_SetString(PyExc_ValueError, "ordinal must be "
2395 ">= 1");
2396 else {
2397 ord_to_ymd(ordinal, &year, &month, &day);
2398 result = PyObject_CallFunction(cls, "iii",
2399 year, month, day);
2400 }
2401 }
2402 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002403}
2404
2405/*
2406 * Date arithmetic.
2407 */
2408
2409/* date + timedelta -> date. If arg negate is true, subtract the timedelta
2410 * instead.
2411 */
2412static PyObject *
2413add_date_timedelta(PyDateTime_Date *date, PyDateTime_Delta *delta, int negate)
2414{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002415 PyObject *result = NULL;
2416 int year = GET_YEAR(date);
2417 int month = GET_MONTH(date);
2418 int deltadays = GET_TD_DAYS(delta);
2419 /* C-level overflow is impossible because |deltadays| < 1e9. */
2420 int day = GET_DAY(date) + (negate ? -deltadays : deltadays);
Tim Peters2a799bf2002-12-16 20:18:38 +00002421
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002422 if (normalize_date(&year, &month, &day) >= 0)
2423 result = new_date(year, month, day);
2424 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002425}
2426
2427static PyObject *
2428date_add(PyObject *left, PyObject *right)
2429{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002430 if (PyDateTime_Check(left) || PyDateTime_Check(right)) {
2431 Py_INCREF(Py_NotImplemented);
2432 return Py_NotImplemented;
2433 }
2434 if (PyDate_Check(left)) {
2435 /* date + ??? */
2436 if (PyDelta_Check(right))
2437 /* date + delta */
2438 return add_date_timedelta((PyDateTime_Date *) left,
2439 (PyDateTime_Delta *) right,
2440 0);
2441 }
2442 else {
2443 /* ??? + date
2444 * 'right' must be one of us, or we wouldn't have been called
2445 */
2446 if (PyDelta_Check(left))
2447 /* delta + date */
2448 return add_date_timedelta((PyDateTime_Date *) right,
2449 (PyDateTime_Delta *) left,
2450 0);
2451 }
2452 Py_INCREF(Py_NotImplemented);
2453 return Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00002454}
2455
2456static PyObject *
2457date_subtract(PyObject *left, PyObject *right)
2458{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002459 if (PyDateTime_Check(left) || PyDateTime_Check(right)) {
2460 Py_INCREF(Py_NotImplemented);
2461 return Py_NotImplemented;
2462 }
2463 if (PyDate_Check(left)) {
2464 if (PyDate_Check(right)) {
2465 /* date - date */
2466 int left_ord = ymd_to_ord(GET_YEAR(left),
2467 GET_MONTH(left),
2468 GET_DAY(left));
2469 int right_ord = ymd_to_ord(GET_YEAR(right),
2470 GET_MONTH(right),
2471 GET_DAY(right));
2472 return new_delta(left_ord - right_ord, 0, 0, 0);
2473 }
2474 if (PyDelta_Check(right)) {
2475 /* date - delta */
2476 return add_date_timedelta((PyDateTime_Date *) left,
2477 (PyDateTime_Delta *) right,
2478 1);
2479 }
2480 }
2481 Py_INCREF(Py_NotImplemented);
2482 return Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00002483}
2484
2485
2486/* Various ways to turn a date into a string. */
2487
2488static PyObject *
2489date_repr(PyDateTime_Date *self)
2490{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002491 char buffer[1028];
2492 const char *type_name;
Tim Peters2a799bf2002-12-16 20:18:38 +00002493
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002494 type_name = Py_TYPE(self)->tp_name;
2495 PyOS_snprintf(buffer, sizeof(buffer), "%s(%d, %d, %d)",
2496 type_name,
2497 GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002498
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002499 return PyString_FromString(buffer);
Tim Peters2a799bf2002-12-16 20:18:38 +00002500}
2501
2502static PyObject *
2503date_isoformat(PyDateTime_Date *self)
2504{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002505 char buffer[128];
Tim Peters2a799bf2002-12-16 20:18:38 +00002506
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002507 isoformat_date(self, buffer, sizeof(buffer));
2508 return PyString_FromString(buffer);
Tim Peters2a799bf2002-12-16 20:18:38 +00002509}
2510
Tim Peterse2df5ff2003-05-02 18:39:55 +00002511/* str() calls the appropriate isoformat() method. */
Tim Peters2a799bf2002-12-16 20:18:38 +00002512static PyObject *
2513date_str(PyDateTime_Date *self)
2514{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002515 return PyObject_CallMethod((PyObject *)self, "isoformat", "()");
Tim Peters2a799bf2002-12-16 20:18:38 +00002516}
2517
2518
2519static PyObject *
2520date_ctime(PyDateTime_Date *self)
2521{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002522 return format_ctime(self, 0, 0, 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00002523}
2524
2525static PyObject *
2526date_strftime(PyDateTime_Date *self, PyObject *args, PyObject *kw)
2527{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002528 /* This method can be inherited, and needs to call the
2529 * timetuple() method appropriate to self's class.
2530 */
2531 PyObject *result;
2532 PyObject *tuple;
2533 const char *format;
2534 Py_ssize_t format_len;
2535 static char *keywords[] = {"format", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00002536
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002537 if (! PyArg_ParseTupleAndKeywords(args, kw, "s#:strftime", keywords,
2538 &format, &format_len))
2539 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002540
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002541 tuple = PyObject_CallMethod((PyObject *)self, "timetuple", "()");
2542 if (tuple == NULL)
2543 return NULL;
2544 result = wrap_strftime((PyObject *)self, format, format_len, tuple,
2545 (PyObject *)self);
2546 Py_DECREF(tuple);
2547 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002548}
2549
Eric Smitha9f7d622008-02-17 19:46:49 +00002550static PyObject *
2551date_format(PyDateTime_Date *self, PyObject *args)
2552{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002553 PyObject *format;
Eric Smitha9f7d622008-02-17 19:46:49 +00002554
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002555 if (!PyArg_ParseTuple(args, "O:__format__", &format))
2556 return NULL;
Eric Smitha9f7d622008-02-17 19:46:49 +00002557
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002558 /* Check for str or unicode */
2559 if (PyString_Check(format)) {
2560 /* If format is zero length, return str(self) */
2561 if (PyString_GET_SIZE(format) == 0)
2562 return PyObject_Str((PyObject *)self);
2563 } else if (PyUnicode_Check(format)) {
2564 /* If format is zero length, return str(self) */
2565 if (PyUnicode_GET_SIZE(format) == 0)
2566 return PyObject_Unicode((PyObject *)self);
2567 } else {
2568 PyErr_Format(PyExc_ValueError,
2569 "__format__ expects str or unicode, not %.200s",
2570 Py_TYPE(format)->tp_name);
2571 return NULL;
2572 }
2573 return PyObject_CallMethod((PyObject *)self, "strftime", "O", format);
Eric Smitha9f7d622008-02-17 19:46:49 +00002574}
2575
Tim Peters2a799bf2002-12-16 20:18:38 +00002576/* ISO methods. */
2577
2578static PyObject *
2579date_isoweekday(PyDateTime_Date *self)
2580{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002581 int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002582
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002583 return PyInt_FromLong(dow + 1);
Tim Peters2a799bf2002-12-16 20:18:38 +00002584}
2585
2586static PyObject *
2587date_isocalendar(PyDateTime_Date *self)
2588{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002589 int year = GET_YEAR(self);
2590 int week1_monday = iso_week1_monday(year);
2591 int today = ymd_to_ord(year, GET_MONTH(self), GET_DAY(self));
2592 int week;
2593 int day;
Tim Peters2a799bf2002-12-16 20:18:38 +00002594
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002595 week = divmod(today - week1_monday, 7, &day);
2596 if (week < 0) {
2597 --year;
2598 week1_monday = iso_week1_monday(year);
2599 week = divmod(today - week1_monday, 7, &day);
2600 }
2601 else if (week >= 52 && today >= iso_week1_monday(year + 1)) {
2602 ++year;
2603 week = 0;
2604 }
2605 return Py_BuildValue("iii", year, week + 1, day + 1);
Tim Peters2a799bf2002-12-16 20:18:38 +00002606}
2607
2608/* Miscellaneous methods. */
2609
2610/* This is more natural as a tp_compare, but doesn't work then: for whatever
2611 * reason, Python's try_3way_compare ignores tp_compare unless
2612 * PyInstance_Check returns true, but these aren't old-style classes.
2613 */
2614static PyObject *
2615date_richcompare(PyDateTime_Date *self, PyObject *other, int op)
2616{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002617 int diff = 42; /* nonsense */
Tim Peters2a799bf2002-12-16 20:18:38 +00002618
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002619 if (PyDate_Check(other))
2620 diff = memcmp(self->data, ((PyDateTime_Date *)other)->data,
2621 _PyDateTime_DATE_DATASIZE);
Tim Peters07534a62003-02-07 22:50:28 +00002622
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002623 else if (PyObject_HasAttrString(other, "timetuple")) {
2624 /* A hook for other kinds of date objects. */
2625 Py_INCREF(Py_NotImplemented);
2626 return Py_NotImplemented;
2627 }
2628 else if (op == Py_EQ || op == Py_NE)
2629 diff = 1; /* any non-zero value will do */
Tim Peters07534a62003-02-07 22:50:28 +00002630
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002631 else /* stop this from falling back to address comparison */
2632 return cmperror((PyObject *)self, other);
Tim Peters07534a62003-02-07 22:50:28 +00002633
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002634 return diff_to_bool(diff, op);
Tim Peters2a799bf2002-12-16 20:18:38 +00002635}
2636
2637static PyObject *
2638date_timetuple(PyDateTime_Date *self)
2639{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002640 return build_struct_time(GET_YEAR(self),
2641 GET_MONTH(self),
2642 GET_DAY(self),
2643 0, 0, 0, -1);
Tim Peters2a799bf2002-12-16 20:18:38 +00002644}
2645
Tim Peters12bf3392002-12-24 05:41:27 +00002646static PyObject *
2647date_replace(PyDateTime_Date *self, PyObject *args, PyObject *kw)
2648{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002649 PyObject *clone;
2650 PyObject *tuple;
2651 int year = GET_YEAR(self);
2652 int month = GET_MONTH(self);
2653 int day = GET_DAY(self);
Tim Peters12bf3392002-12-24 05:41:27 +00002654
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002655 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iii:replace", date_kws,
2656 &year, &month, &day))
2657 return NULL;
2658 tuple = Py_BuildValue("iii", year, month, day);
2659 if (tuple == NULL)
2660 return NULL;
2661 clone = date_new(Py_TYPE(self), tuple, NULL);
2662 Py_DECREF(tuple);
2663 return clone;
Tim Peters12bf3392002-12-24 05:41:27 +00002664}
2665
Tim Peters2a799bf2002-12-16 20:18:38 +00002666static PyObject *date_getstate(PyDateTime_Date *self);
2667
2668static long
2669date_hash(PyDateTime_Date *self)
2670{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002671 if (self->hashcode == -1) {
2672 PyObject *temp = date_getstate(self);
2673 if (temp != NULL) {
2674 self->hashcode = PyObject_Hash(temp);
2675 Py_DECREF(temp);
2676 }
2677 }
2678 return self->hashcode;
Tim Peters2a799bf2002-12-16 20:18:38 +00002679}
2680
2681static PyObject *
2682date_toordinal(PyDateTime_Date *self)
2683{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002684 return PyInt_FromLong(ymd_to_ord(GET_YEAR(self), GET_MONTH(self),
2685 GET_DAY(self)));
Tim Peters2a799bf2002-12-16 20:18:38 +00002686}
2687
2688static PyObject *
2689date_weekday(PyDateTime_Date *self)
2690{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002691 int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002692
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002693 return PyInt_FromLong(dow);
Tim Peters2a799bf2002-12-16 20:18:38 +00002694}
2695
Tim Peters371935f2003-02-01 01:52:50 +00002696/* Pickle support, a simple use of __reduce__. */
Tim Peters2a799bf2002-12-16 20:18:38 +00002697
Tim Petersb57f8f02003-02-01 02:54:15 +00002698/* __getstate__ isn't exposed */
Tim Peters2a799bf2002-12-16 20:18:38 +00002699static PyObject *
2700date_getstate(PyDateTime_Date *self)
2701{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002702 return Py_BuildValue(
2703 "(N)",
2704 PyString_FromStringAndSize((char *)self->data,
2705 _PyDateTime_DATE_DATASIZE));
Tim Peters2a799bf2002-12-16 20:18:38 +00002706}
2707
2708static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00002709date_reduce(PyDateTime_Date *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00002710{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002711 return Py_BuildValue("(ON)", Py_TYPE(self), date_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002712}
2713
2714static PyMethodDef date_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002715
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002716 /* Class methods: */
Guido van Rossum177e41a2003-01-30 22:06:23 +00002717
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002718 {"fromtimestamp", (PyCFunction)date_fromtimestamp, METH_VARARGS |
2719 METH_CLASS,
2720 PyDoc_STR("timestamp -> local date from a POSIX timestamp (like "
2721 "time.time()).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002722
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002723 {"fromordinal", (PyCFunction)date_fromordinal, METH_VARARGS |
2724 METH_CLASS,
2725 PyDoc_STR("int -> date corresponding to a proleptic Gregorian "
2726 "ordinal.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002727
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002728 {"today", (PyCFunction)date_today, METH_NOARGS | METH_CLASS,
2729 PyDoc_STR("Current date or datetime: same as "
2730 "self.__class__.fromtimestamp(time.time()).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002731
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002732 /* Instance methods: */
Tim Peters2a799bf2002-12-16 20:18:38 +00002733
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002734 {"ctime", (PyCFunction)date_ctime, METH_NOARGS,
2735 PyDoc_STR("Return ctime() style string.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002736
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002737 {"strftime", (PyCFunction)date_strftime, METH_VARARGS | METH_KEYWORDS,
2738 PyDoc_STR("format -> strftime() style string.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002739
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002740 {"__format__", (PyCFunction)date_format, METH_VARARGS,
2741 PyDoc_STR("Formats self with strftime.")},
Eric Smitha9f7d622008-02-17 19:46:49 +00002742
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002743 {"timetuple", (PyCFunction)date_timetuple, METH_NOARGS,
2744 PyDoc_STR("Return time tuple, compatible with time.localtime().")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002745
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002746 {"isocalendar", (PyCFunction)date_isocalendar, METH_NOARGS,
2747 PyDoc_STR("Return a 3-tuple containing ISO year, week number, and "
2748 "weekday.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002749
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002750 {"isoformat", (PyCFunction)date_isoformat, METH_NOARGS,
2751 PyDoc_STR("Return string in ISO 8601 format, YYYY-MM-DD.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002752
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002753 {"isoweekday", (PyCFunction)date_isoweekday, METH_NOARGS,
2754 PyDoc_STR("Return the day of the week represented by the date.\n"
2755 "Monday == 1 ... Sunday == 7")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002756
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002757 {"toordinal", (PyCFunction)date_toordinal, METH_NOARGS,
2758 PyDoc_STR("Return proleptic Gregorian ordinal. January 1 of year "
2759 "1 is day 1.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002760
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002761 {"weekday", (PyCFunction)date_weekday, METH_NOARGS,
2762 PyDoc_STR("Return the day of the week represented by the date.\n"
2763 "Monday == 0 ... Sunday == 6")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002764
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002765 {"replace", (PyCFunction)date_replace, METH_VARARGS | METH_KEYWORDS,
2766 PyDoc_STR("Return date with new specified fields.")},
Tim Peters12bf3392002-12-24 05:41:27 +00002767
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002768 {"__reduce__", (PyCFunction)date_reduce, METH_NOARGS,
2769 PyDoc_STR("__reduce__() -> (cls, state)")},
Guido van Rossum177e41a2003-01-30 22:06:23 +00002770
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002771 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00002772};
2773
2774static char date_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00002775PyDoc_STR("date(year, month, day) --> date object");
Tim Peters2a799bf2002-12-16 20:18:38 +00002776
2777static PyNumberMethods date_as_number = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002778 date_add, /* nb_add */
2779 date_subtract, /* nb_subtract */
2780 0, /* nb_multiply */
2781 0, /* nb_divide */
2782 0, /* nb_remainder */
2783 0, /* nb_divmod */
2784 0, /* nb_power */
2785 0, /* nb_negative */
2786 0, /* nb_positive */
2787 0, /* nb_absolute */
2788 0, /* nb_nonzero */
Tim Peters2a799bf2002-12-16 20:18:38 +00002789};
2790
2791static PyTypeObject PyDateTime_DateType = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002792 PyVarObject_HEAD_INIT(NULL, 0)
2793 "datetime.date", /* tp_name */
2794 sizeof(PyDateTime_Date), /* tp_basicsize */
2795 0, /* tp_itemsize */
2796 0, /* tp_dealloc */
2797 0, /* tp_print */
2798 0, /* tp_getattr */
2799 0, /* tp_setattr */
2800 0, /* tp_compare */
2801 (reprfunc)date_repr, /* tp_repr */
2802 &date_as_number, /* tp_as_number */
2803 0, /* tp_as_sequence */
2804 0, /* tp_as_mapping */
2805 (hashfunc)date_hash, /* tp_hash */
2806 0, /* tp_call */
2807 (reprfunc)date_str, /* tp_str */
2808 PyObject_GenericGetAttr, /* tp_getattro */
2809 0, /* tp_setattro */
2810 0, /* tp_as_buffer */
2811 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
2812 Py_TPFLAGS_BASETYPE, /* tp_flags */
2813 date_doc, /* tp_doc */
2814 0, /* tp_traverse */
2815 0, /* tp_clear */
2816 (richcmpfunc)date_richcompare, /* tp_richcompare */
2817 0, /* tp_weaklistoffset */
2818 0, /* tp_iter */
2819 0, /* tp_iternext */
2820 date_methods, /* tp_methods */
2821 0, /* tp_members */
2822 date_getset, /* tp_getset */
2823 0, /* tp_base */
2824 0, /* tp_dict */
2825 0, /* tp_descr_get */
2826 0, /* tp_descr_set */
2827 0, /* tp_dictoffset */
2828 0, /* tp_init */
2829 0, /* tp_alloc */
2830 date_new, /* tp_new */
2831 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00002832};
2833
2834/*
Tim Peters2a799bf2002-12-16 20:18:38 +00002835 * PyDateTime_TZInfo implementation.
2836 */
2837
2838/* This is a pure abstract base class, so doesn't do anything beyond
2839 * raising NotImplemented exceptions. Real tzinfo classes need
2840 * to derive from this. This is mostly for clarity, and for efficiency in
Tim Petersa9bc1682003-01-11 03:39:11 +00002841 * datetime and time constructors (their tzinfo arguments need to
Tim Peters2a799bf2002-12-16 20:18:38 +00002842 * be subclasses of this tzinfo class, which is easy and quick to check).
2843 *
2844 * Note: For reasons having to do with pickling of subclasses, we have
2845 * to allow tzinfo objects to be instantiated. This wasn't an issue
2846 * in the Python implementation (__init__() could raise NotImplementedError
2847 * there without ill effect), but doing so in the C implementation hit a
2848 * brick wall.
2849 */
2850
2851static PyObject *
2852tzinfo_nogo(const char* methodname)
2853{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002854 PyErr_Format(PyExc_NotImplementedError,
2855 "a tzinfo subclass must implement %s()",
2856 methodname);
2857 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002858}
2859
2860/* Methods. A subclass must implement these. */
2861
Tim Peters52dcce22003-01-23 16:36:11 +00002862static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002863tzinfo_tzname(PyDateTime_TZInfo *self, PyObject *dt)
2864{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002865 return tzinfo_nogo("tzname");
Tim Peters2a799bf2002-12-16 20:18:38 +00002866}
2867
Tim Peters52dcce22003-01-23 16:36:11 +00002868static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002869tzinfo_utcoffset(PyDateTime_TZInfo *self, PyObject *dt)
2870{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002871 return tzinfo_nogo("utcoffset");
Tim Peters2a799bf2002-12-16 20:18:38 +00002872}
2873
Tim Peters52dcce22003-01-23 16:36:11 +00002874static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002875tzinfo_dst(PyDateTime_TZInfo *self, PyObject *dt)
2876{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002877 return tzinfo_nogo("dst");
Tim Peters2a799bf2002-12-16 20:18:38 +00002878}
2879
Tim Peters52dcce22003-01-23 16:36:11 +00002880static PyObject *
2881tzinfo_fromutc(PyDateTime_TZInfo *self, PyDateTime_DateTime *dt)
2882{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002883 int y, m, d, hh, mm, ss, us;
Tim Peters52dcce22003-01-23 16:36:11 +00002884
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002885 PyObject *result;
2886 int off, dst;
2887 int none;
2888 int delta;
Tim Peters52dcce22003-01-23 16:36:11 +00002889
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002890 if (! PyDateTime_Check(dt)) {
2891 PyErr_SetString(PyExc_TypeError,
2892 "fromutc: argument must be a datetime");
2893 return NULL;
2894 }
2895 if (! HASTZINFO(dt) || dt->tzinfo != (PyObject *)self) {
2896 PyErr_SetString(PyExc_ValueError, "fromutc: dt.tzinfo "
2897 "is not self");
2898 return NULL;
2899 }
Tim Peters52dcce22003-01-23 16:36:11 +00002900
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002901 off = call_utcoffset(dt->tzinfo, (PyObject *)dt, &none);
2902 if (off == -1 && PyErr_Occurred())
2903 return NULL;
2904 if (none) {
2905 PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
2906 "utcoffset() result required");
2907 return NULL;
2908 }
Tim Peters52dcce22003-01-23 16:36:11 +00002909
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002910 dst = call_dst(dt->tzinfo, (PyObject *)dt, &none);
2911 if (dst == -1 && PyErr_Occurred())
2912 return NULL;
2913 if (none) {
2914 PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
2915 "dst() result required");
2916 return NULL;
2917 }
Tim Peters52dcce22003-01-23 16:36:11 +00002918
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002919 y = GET_YEAR(dt);
2920 m = GET_MONTH(dt);
2921 d = GET_DAY(dt);
2922 hh = DATE_GET_HOUR(dt);
2923 mm = DATE_GET_MINUTE(dt);
2924 ss = DATE_GET_SECOND(dt);
2925 us = DATE_GET_MICROSECOND(dt);
Tim Peters52dcce22003-01-23 16:36:11 +00002926
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002927 delta = off - dst;
2928 mm += delta;
2929 if ((mm < 0 || mm >= 60) &&
2930 normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
2931 return NULL;
2932 result = new_datetime(y, m, d, hh, mm, ss, us, dt->tzinfo);
2933 if (result == NULL)
2934 return result;
Tim Peters52dcce22003-01-23 16:36:11 +00002935
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002936 dst = call_dst(dt->tzinfo, result, &none);
2937 if (dst == -1 && PyErr_Occurred())
2938 goto Fail;
2939 if (none)
2940 goto Inconsistent;
2941 if (dst == 0)
2942 return result;
Tim Peters52dcce22003-01-23 16:36:11 +00002943
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002944 mm += dst;
2945 if ((mm < 0 || mm >= 60) &&
2946 normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
2947 goto Fail;
2948 Py_DECREF(result);
2949 result = new_datetime(y, m, d, hh, mm, ss, us, dt->tzinfo);
2950 return result;
Tim Peters52dcce22003-01-23 16:36:11 +00002951
2952Inconsistent:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002953 PyErr_SetString(PyExc_ValueError, "fromutc: tz.dst() gave"
2954 "inconsistent results; cannot convert");
Tim Peters52dcce22003-01-23 16:36:11 +00002955
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002956 /* fall thru to failure */
Tim Peters52dcce22003-01-23 16:36:11 +00002957Fail:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002958 Py_DECREF(result);
2959 return NULL;
Tim Peters52dcce22003-01-23 16:36:11 +00002960}
2961
Tim Peters2a799bf2002-12-16 20:18:38 +00002962/*
2963 * Pickle support. This is solely so that tzinfo subclasses can use
Guido van Rossum177e41a2003-01-30 22:06:23 +00002964 * pickling -- tzinfo itself is supposed to be uninstantiable.
Tim Peters2a799bf2002-12-16 20:18:38 +00002965 */
2966
Guido van Rossum177e41a2003-01-30 22:06:23 +00002967static PyObject *
2968tzinfo_reduce(PyObject *self)
2969{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002970 PyObject *args, *state, *tmp;
2971 PyObject *getinitargs, *getstate;
Tim Peters2a799bf2002-12-16 20:18:38 +00002972
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002973 tmp = PyTuple_New(0);
2974 if (tmp == NULL)
2975 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002976
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002977 getinitargs = PyObject_GetAttrString(self, "__getinitargs__");
2978 if (getinitargs != NULL) {
2979 args = PyObject_CallObject(getinitargs, tmp);
2980 Py_DECREF(getinitargs);
2981 if (args == NULL) {
2982 Py_DECREF(tmp);
2983 return NULL;
2984 }
2985 }
2986 else {
2987 PyErr_Clear();
2988 args = tmp;
2989 Py_INCREF(args);
2990 }
Guido van Rossum177e41a2003-01-30 22:06:23 +00002991
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002992 getstate = PyObject_GetAttrString(self, "__getstate__");
2993 if (getstate != NULL) {
2994 state = PyObject_CallObject(getstate, tmp);
2995 Py_DECREF(getstate);
2996 if (state == NULL) {
2997 Py_DECREF(args);
2998 Py_DECREF(tmp);
2999 return NULL;
3000 }
3001 }
3002 else {
3003 PyObject **dictptr;
3004 PyErr_Clear();
3005 state = Py_None;
3006 dictptr = _PyObject_GetDictPtr(self);
3007 if (dictptr && *dictptr && PyDict_Size(*dictptr))
3008 state = *dictptr;
3009 Py_INCREF(state);
3010 }
Guido van Rossum177e41a2003-01-30 22:06:23 +00003011
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003012 Py_DECREF(tmp);
Guido van Rossum177e41a2003-01-30 22:06:23 +00003013
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003014 if (state == Py_None) {
3015 Py_DECREF(state);
3016 return Py_BuildValue("(ON)", Py_TYPE(self), args);
3017 }
3018 else
3019 return Py_BuildValue("(ONN)", Py_TYPE(self), args, state);
Guido van Rossum177e41a2003-01-30 22:06:23 +00003020}
Tim Peters2a799bf2002-12-16 20:18:38 +00003021
3022static PyMethodDef tzinfo_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00003023
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003024 {"tzname", (PyCFunction)tzinfo_tzname, METH_O,
3025 PyDoc_STR("datetime -> string name of time zone.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003026
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003027 {"utcoffset", (PyCFunction)tzinfo_utcoffset, METH_O,
3028 PyDoc_STR("datetime -> minutes east of UTC (negative for "
3029 "west of UTC).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003030
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003031 {"dst", (PyCFunction)tzinfo_dst, METH_O,
3032 PyDoc_STR("datetime -> DST offset in minutes east of UTC.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003033
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003034 {"fromutc", (PyCFunction)tzinfo_fromutc, METH_O,
Alexander Belopolsky1f6e2252010-07-03 03:27:12 +00003035 PyDoc_STR("datetime in UTC -> datetime in local time.")},
Tim Peters52dcce22003-01-23 16:36:11 +00003036
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003037 {"__reduce__", (PyCFunction)tzinfo_reduce, METH_NOARGS,
3038 PyDoc_STR("-> (cls, state)")},
Guido van Rossum177e41a2003-01-30 22:06:23 +00003039
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003040 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00003041};
3042
3043static char tzinfo_doc[] =
3044PyDoc_STR("Abstract base class for time zone info objects.");
3045
Neal Norwitzce3d34d2003-02-04 20:45:17 +00003046statichere PyTypeObject PyDateTime_TZInfoType = {
Benjamin Petersona72d15c2017-09-13 21:20:29 -07003047 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003048 "datetime.tzinfo", /* tp_name */
3049 sizeof(PyDateTime_TZInfo), /* tp_basicsize */
3050 0, /* tp_itemsize */
3051 0, /* tp_dealloc */
3052 0, /* tp_print */
3053 0, /* tp_getattr */
3054 0, /* tp_setattr */
3055 0, /* tp_compare */
3056 0, /* tp_repr */
3057 0, /* tp_as_number */
3058 0, /* tp_as_sequence */
3059 0, /* tp_as_mapping */
3060 0, /* tp_hash */
3061 0, /* tp_call */
3062 0, /* tp_str */
3063 PyObject_GenericGetAttr, /* tp_getattro */
3064 0, /* tp_setattro */
3065 0, /* tp_as_buffer */
3066 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
3067 Py_TPFLAGS_BASETYPE, /* tp_flags */
3068 tzinfo_doc, /* tp_doc */
3069 0, /* tp_traverse */
3070 0, /* tp_clear */
3071 0, /* tp_richcompare */
3072 0, /* tp_weaklistoffset */
3073 0, /* tp_iter */
3074 0, /* tp_iternext */
3075 tzinfo_methods, /* tp_methods */
3076 0, /* tp_members */
3077 0, /* tp_getset */
3078 0, /* tp_base */
3079 0, /* tp_dict */
3080 0, /* tp_descr_get */
3081 0, /* tp_descr_set */
3082 0, /* tp_dictoffset */
3083 0, /* tp_init */
3084 0, /* tp_alloc */
3085 PyType_GenericNew, /* tp_new */
3086 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00003087};
3088
3089/*
Tim Peters37f39822003-01-10 03:49:02 +00003090 * PyDateTime_Time implementation.
Tim Peters2a799bf2002-12-16 20:18:38 +00003091 */
3092
Tim Peters37f39822003-01-10 03:49:02 +00003093/* Accessor properties.
Tim Peters2a799bf2002-12-16 20:18:38 +00003094 */
3095
3096static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003097time_hour(PyDateTime_Time *self, void *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00003098{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003099 return PyInt_FromLong(TIME_GET_HOUR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00003100}
3101
Tim Peters37f39822003-01-10 03:49:02 +00003102static PyObject *
3103time_minute(PyDateTime_Time *self, void *unused)
3104{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003105 return PyInt_FromLong(TIME_GET_MINUTE(self));
Tim Peters37f39822003-01-10 03:49:02 +00003106}
3107
3108/* The name time_second conflicted with some platform header file. */
3109static PyObject *
3110py_time_second(PyDateTime_Time *self, void *unused)
3111{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003112 return PyInt_FromLong(TIME_GET_SECOND(self));
Tim Peters37f39822003-01-10 03:49:02 +00003113}
3114
3115static PyObject *
3116time_microsecond(PyDateTime_Time *self, void *unused)
3117{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003118 return PyInt_FromLong(TIME_GET_MICROSECOND(self));
Tim Peters37f39822003-01-10 03:49:02 +00003119}
3120
3121static PyObject *
3122time_tzinfo(PyDateTime_Time *self, void *unused)
3123{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003124 PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
3125 Py_INCREF(result);
3126 return result;
Tim Peters37f39822003-01-10 03:49:02 +00003127}
3128
3129static PyGetSetDef time_getset[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003130 {"hour", (getter)time_hour},
3131 {"minute", (getter)time_minute},
3132 {"second", (getter)py_time_second},
3133 {"microsecond", (getter)time_microsecond},
3134 {"tzinfo", (getter)time_tzinfo},
3135 {NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00003136};
3137
3138/*
3139 * Constructors.
3140 */
3141
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003142static char *time_kws[] = {"hour", "minute", "second", "microsecond",
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003143 "tzinfo", NULL};
Tim Peters12bf3392002-12-24 05:41:27 +00003144
Tim Peters2a799bf2002-12-16 20:18:38 +00003145static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003146time_new(PyTypeObject *type, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003147{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003148 PyObject *self = NULL;
3149 PyObject *state;
3150 int hour = 0;
3151 int minute = 0;
3152 int second = 0;
3153 int usecond = 0;
3154 PyObject *tzinfo = Py_None;
Tim Peters2a799bf2002-12-16 20:18:38 +00003155
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003156 /* Check for invocation from pickle with __getstate__ state */
3157 if (PyTuple_GET_SIZE(args) >= 1 &&
3158 PyTuple_GET_SIZE(args) <= 2 &&
3159 PyString_Check(state = PyTuple_GET_ITEM(args, 0)) &&
3160 PyString_GET_SIZE(state) == _PyDateTime_TIME_DATASIZE &&
3161 ((unsigned char) (PyString_AS_STRING(state)[0])) < 24)
3162 {
3163 PyDateTime_Time *me;
3164 char aware;
Tim Peters70533e22003-02-01 04:40:04 +00003165
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003166 if (PyTuple_GET_SIZE(args) == 2) {
3167 tzinfo = PyTuple_GET_ITEM(args, 1);
3168 if (check_tzinfo_subclass(tzinfo) < 0) {
3169 PyErr_SetString(PyExc_TypeError, "bad "
3170 "tzinfo state arg");
3171 return NULL;
3172 }
3173 }
3174 aware = (char)(tzinfo != Py_None);
3175 me = (PyDateTime_Time *) (type->tp_alloc(type, aware));
3176 if (me != NULL) {
3177 char *pdata = PyString_AS_STRING(state);
Tim Peters70533e22003-02-01 04:40:04 +00003178
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003179 memcpy(me->data, pdata, _PyDateTime_TIME_DATASIZE);
3180 me->hashcode = -1;
3181 me->hastzinfo = aware;
3182 if (aware) {
3183 Py_INCREF(tzinfo);
3184 me->tzinfo = tzinfo;
3185 }
3186 }
3187 return (PyObject *)me;
3188 }
Guido van Rossum177e41a2003-01-30 22:06:23 +00003189
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003190 if (PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO", time_kws,
3191 &hour, &minute, &second, &usecond,
3192 &tzinfo)) {
3193 if (check_time_args(hour, minute, second, usecond) < 0)
3194 return NULL;
3195 if (check_tzinfo_subclass(tzinfo) < 0)
3196 return NULL;
3197 self = new_time_ex(hour, minute, second, usecond, tzinfo,
3198 type);
3199 }
3200 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00003201}
3202
3203/*
3204 * Destructor.
3205 */
3206
3207static void
Tim Peters37f39822003-01-10 03:49:02 +00003208time_dealloc(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003209{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003210 if (HASTZINFO(self)) {
3211 Py_XDECREF(self->tzinfo);
3212 }
3213 Py_TYPE(self)->tp_free((PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00003214}
3215
3216/*
Tim Peters855fe882002-12-22 03:43:39 +00003217 * Indirect access to tzinfo methods.
Tim Peters2a799bf2002-12-16 20:18:38 +00003218 */
3219
Tim Peters2a799bf2002-12-16 20:18:38 +00003220/* These are all METH_NOARGS, so don't need to check the arglist. */
3221static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003222time_utcoffset(PyDateTime_Time *self, PyObject *unused) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003223 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
3224 "utcoffset", Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00003225}
3226
3227static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003228time_dst(PyDateTime_Time *self, PyObject *unused) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003229 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
3230 "dst", Py_None);
Tim Peters855fe882002-12-22 03:43:39 +00003231}
3232
3233static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003234time_tzname(PyDateTime_Time *self, PyObject *unused) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003235 return call_tzname(HASTZINFO(self) ? self->tzinfo : Py_None,
3236 Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00003237}
3238
3239/*
Tim Peters37f39822003-01-10 03:49:02 +00003240 * Various ways to turn a time into a string.
Tim Peters2a799bf2002-12-16 20:18:38 +00003241 */
3242
3243static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003244time_repr(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003245{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003246 char buffer[100];
3247 const char *type_name = Py_TYPE(self)->tp_name;
3248 int h = TIME_GET_HOUR(self);
3249 int m = TIME_GET_MINUTE(self);
3250 int s = TIME_GET_SECOND(self);
3251 int us = TIME_GET_MICROSECOND(self);
3252 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00003253
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003254 if (us)
3255 PyOS_snprintf(buffer, sizeof(buffer),
3256 "%s(%d, %d, %d, %d)", type_name, h, m, s, us);
3257 else if (s)
3258 PyOS_snprintf(buffer, sizeof(buffer),
3259 "%s(%d, %d, %d)", type_name, h, m, s);
3260 else
3261 PyOS_snprintf(buffer, sizeof(buffer),
3262 "%s(%d, %d)", type_name, h, m);
3263 result = PyString_FromString(buffer);
3264 if (result != NULL && HASTZINFO(self))
3265 result = append_keyword_tzinfo(result, self->tzinfo);
3266 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00003267}
3268
Tim Peters37f39822003-01-10 03:49:02 +00003269static PyObject *
3270time_str(PyDateTime_Time *self)
3271{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003272 return PyObject_CallMethod((PyObject *)self, "isoformat", "()");
Tim Peters37f39822003-01-10 03:49:02 +00003273}
Tim Peters2a799bf2002-12-16 20:18:38 +00003274
3275static PyObject *
Martin v. Löwis4c11a922007-02-08 09:13:36 +00003276time_isoformat(PyDateTime_Time *self, PyObject *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00003277{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003278 char buf[100];
3279 PyObject *result;
3280 /* Reuse the time format code from the datetime type. */
3281 PyDateTime_DateTime datetime;
3282 PyDateTime_DateTime *pdatetime = &datetime;
Tim Peters2a799bf2002-12-16 20:18:38 +00003283
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003284 /* Copy over just the time bytes. */
3285 memcpy(pdatetime->data + _PyDateTime_DATE_DATASIZE,
3286 self->data,
3287 _PyDateTime_TIME_DATASIZE);
Tim Peters37f39822003-01-10 03:49:02 +00003288
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003289 isoformat_time(pdatetime, buf, sizeof(buf));
3290 result = PyString_FromString(buf);
3291 if (result == NULL || ! HASTZINFO(self) || self->tzinfo == Py_None)
3292 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00003293
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003294 /* We need to append the UTC offset. */
3295 if (format_utcoffset(buf, sizeof(buf), ":", self->tzinfo,
3296 Py_None) < 0) {
3297 Py_DECREF(result);
3298 return NULL;
3299 }
3300 PyString_ConcatAndDel(&result, PyString_FromString(buf));
3301 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00003302}
3303
Tim Peters37f39822003-01-10 03:49:02 +00003304static PyObject *
3305time_strftime(PyDateTime_Time *self, PyObject *args, PyObject *kw)
3306{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003307 PyObject *result;
3308 PyObject *tuple;
3309 const char *format;
3310 Py_ssize_t format_len;
3311 static char *keywords[] = {"format", NULL};
Tim Peters37f39822003-01-10 03:49:02 +00003312
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003313 if (! PyArg_ParseTupleAndKeywords(args, kw, "s#:strftime", keywords,
3314 &format, &format_len))
3315 return NULL;
Tim Peters37f39822003-01-10 03:49:02 +00003316
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003317 /* Python's strftime does insane things with the year part of the
3318 * timetuple. The year is forced to (the otherwise nonsensical)
3319 * 1900 to worm around that.
3320 */
3321 tuple = Py_BuildValue("iiiiiiiii",
3322 1900, 1, 1, /* year, month, day */
3323 TIME_GET_HOUR(self),
3324 TIME_GET_MINUTE(self),
3325 TIME_GET_SECOND(self),
3326 0, 1, -1); /* weekday, daynum, dst */
3327 if (tuple == NULL)
3328 return NULL;
3329 assert(PyTuple_Size(tuple) == 9);
3330 result = wrap_strftime((PyObject *)self, format, format_len, tuple,
3331 Py_None);
3332 Py_DECREF(tuple);
3333 return result;
Tim Peters37f39822003-01-10 03:49:02 +00003334}
Tim Peters2a799bf2002-12-16 20:18:38 +00003335
3336/*
3337 * Miscellaneous methods.
3338 */
3339
Tim Peters37f39822003-01-10 03:49:02 +00003340/* This is more natural as a tp_compare, but doesn't work then: for whatever
3341 * reason, Python's try_3way_compare ignores tp_compare unless
3342 * PyInstance_Check returns true, but these aren't old-style classes.
3343 */
3344static PyObject *
3345time_richcompare(PyDateTime_Time *self, PyObject *other, int op)
3346{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003347 int diff;
3348 naivety n1, n2;
3349 int offset1, offset2;
Tim Peters37f39822003-01-10 03:49:02 +00003350
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003351 if (! PyTime_Check(other)) {
3352 if (op == Py_EQ || op == Py_NE) {
3353 PyObject *result = op == Py_EQ ? Py_False : Py_True;
3354 Py_INCREF(result);
3355 return result;
3356 }
3357 /* Stop this from falling back to address comparison. */
3358 return cmperror((PyObject *)self, other);
3359 }
3360 if (classify_two_utcoffsets((PyObject *)self, &offset1, &n1, Py_None,
3361 other, &offset2, &n2, Py_None) < 0)
3362 return NULL;
3363 assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
3364 /* If they're both naive, or both aware and have the same offsets,
3365 * we get off cheap. Note that if they're both naive, offset1 ==
3366 * offset2 == 0 at this point.
3367 */
3368 if (n1 == n2 && offset1 == offset2) {
3369 diff = memcmp(self->data, ((PyDateTime_Time *)other)->data,
3370 _PyDateTime_TIME_DATASIZE);
3371 return diff_to_bool(diff, op);
3372 }
Tim Peters37f39822003-01-10 03:49:02 +00003373
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003374 if (n1 == OFFSET_AWARE && n2 == OFFSET_AWARE) {
3375 assert(offset1 != offset2); /* else last "if" handled it */
3376 /* Convert everything except microseconds to seconds. These
3377 * can't overflow (no more than the # of seconds in 2 days).
3378 */
3379 offset1 = TIME_GET_HOUR(self) * 3600 +
3380 (TIME_GET_MINUTE(self) - offset1) * 60 +
3381 TIME_GET_SECOND(self);
3382 offset2 = TIME_GET_HOUR(other) * 3600 +
3383 (TIME_GET_MINUTE(other) - offset2) * 60 +
3384 TIME_GET_SECOND(other);
3385 diff = offset1 - offset2;
3386 if (diff == 0)
3387 diff = TIME_GET_MICROSECOND(self) -
3388 TIME_GET_MICROSECOND(other);
3389 return diff_to_bool(diff, op);
3390 }
Tim Peters37f39822003-01-10 03:49:02 +00003391
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003392 assert(n1 != n2);
3393 PyErr_SetString(PyExc_TypeError,
3394 "can't compare offset-naive and "
3395 "offset-aware times");
3396 return NULL;
Tim Peters37f39822003-01-10 03:49:02 +00003397}
3398
3399static long
3400time_hash(PyDateTime_Time *self)
3401{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003402 if (self->hashcode == -1) {
3403 naivety n;
3404 int offset;
3405 PyObject *temp;
Tim Peters37f39822003-01-10 03:49:02 +00003406
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003407 n = classify_utcoffset((PyObject *)self, Py_None, &offset);
3408 assert(n != OFFSET_UNKNOWN);
3409 if (n == OFFSET_ERROR)
3410 return -1;
Tim Peters37f39822003-01-10 03:49:02 +00003411
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003412 /* Reduce this to a hash of another object. */
3413 if (offset == 0)
3414 temp = PyString_FromStringAndSize((char *)self->data,
3415 _PyDateTime_TIME_DATASIZE);
3416 else {
3417 int hour;
3418 int minute;
Tim Peters37f39822003-01-10 03:49:02 +00003419
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003420 assert(n == OFFSET_AWARE);
3421 assert(HASTZINFO(self));
3422 hour = divmod(TIME_GET_HOUR(self) * 60 +
3423 TIME_GET_MINUTE(self) - offset,
3424 60,
3425 &minute);
3426 if (0 <= hour && hour < 24)
3427 temp = new_time(hour, minute,
3428 TIME_GET_SECOND(self),
3429 TIME_GET_MICROSECOND(self),
3430 Py_None);
3431 else
3432 temp = Py_BuildValue("iiii",
3433 hour, minute,
3434 TIME_GET_SECOND(self),
3435 TIME_GET_MICROSECOND(self));
3436 }
3437 if (temp != NULL) {
3438 self->hashcode = PyObject_Hash(temp);
3439 Py_DECREF(temp);
3440 }
3441 }
3442 return self->hashcode;
Tim Peters37f39822003-01-10 03:49:02 +00003443}
Tim Peters2a799bf2002-12-16 20:18:38 +00003444
Tim Peters12bf3392002-12-24 05:41:27 +00003445static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003446time_replace(PyDateTime_Time *self, PyObject *args, PyObject *kw)
Tim Peters12bf3392002-12-24 05:41:27 +00003447{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003448 PyObject *clone;
3449 PyObject *tuple;
3450 int hh = TIME_GET_HOUR(self);
3451 int mm = TIME_GET_MINUTE(self);
3452 int ss = TIME_GET_SECOND(self);
3453 int us = TIME_GET_MICROSECOND(self);
3454 PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
Tim Peters12bf3392002-12-24 05:41:27 +00003455
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003456 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO:replace",
3457 time_kws,
3458 &hh, &mm, &ss, &us, &tzinfo))
3459 return NULL;
3460 tuple = Py_BuildValue("iiiiO", hh, mm, ss, us, tzinfo);
3461 if (tuple == NULL)
3462 return NULL;
3463 clone = time_new(Py_TYPE(self), tuple, NULL);
3464 Py_DECREF(tuple);
3465 return clone;
Tim Peters12bf3392002-12-24 05:41:27 +00003466}
3467
Tim Peters2a799bf2002-12-16 20:18:38 +00003468static int
Tim Peters37f39822003-01-10 03:49:02 +00003469time_nonzero(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003470{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003471 int offset;
3472 int none;
Tim Peters2a799bf2002-12-16 20:18:38 +00003473
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003474 if (TIME_GET_SECOND(self) || TIME_GET_MICROSECOND(self)) {
3475 /* Since utcoffset is in whole minutes, nothing can
3476 * alter the conclusion that this is nonzero.
3477 */
3478 return 1;
3479 }
3480 offset = 0;
3481 if (HASTZINFO(self) && self->tzinfo != Py_None) {
3482 offset = call_utcoffset(self->tzinfo, Py_None, &none);
3483 if (offset == -1 && PyErr_Occurred())
3484 return -1;
3485 }
3486 return (TIME_GET_MINUTE(self) - offset + TIME_GET_HOUR(self)*60) != 0;
Tim Peters2a799bf2002-12-16 20:18:38 +00003487}
3488
Tim Peters371935f2003-02-01 01:52:50 +00003489/* Pickle support, a simple use of __reduce__. */
Tim Peters2a799bf2002-12-16 20:18:38 +00003490
Tim Peters33e0f382003-01-10 02:05:14 +00003491/* Let basestate be the non-tzinfo data string.
Tim Peters2a799bf2002-12-16 20:18:38 +00003492 * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
3493 * So it's a tuple in any (non-error) case.
Tim Petersb57f8f02003-02-01 02:54:15 +00003494 * __getstate__ isn't exposed.
Tim Peters2a799bf2002-12-16 20:18:38 +00003495 */
3496static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003497time_getstate(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003498{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003499 PyObject *basestate;
3500 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00003501
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003502 basestate = PyString_FromStringAndSize((char *)self->data,
3503 _PyDateTime_TIME_DATASIZE);
3504 if (basestate != NULL) {
3505 if (! HASTZINFO(self) || self->tzinfo == Py_None)
3506 result = PyTuple_Pack(1, basestate);
3507 else
3508 result = PyTuple_Pack(2, basestate, self->tzinfo);
3509 Py_DECREF(basestate);
3510 }
3511 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00003512}
3513
3514static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00003515time_reduce(PyDateTime_Time *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00003516{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003517 return Py_BuildValue("(ON)", Py_TYPE(self), time_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00003518}
3519
Tim Peters37f39822003-01-10 03:49:02 +00003520static PyMethodDef time_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00003521
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003522 {"isoformat", (PyCFunction)time_isoformat, METH_NOARGS,
3523 PyDoc_STR("Return string in ISO 8601 format, HH:MM:SS[.mmmmmm]"
3524 "[+HH:MM].")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003525
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003526 {"strftime", (PyCFunction)time_strftime, METH_VARARGS | METH_KEYWORDS,
3527 PyDoc_STR("format -> strftime() style string.")},
Tim Peters37f39822003-01-10 03:49:02 +00003528
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003529 {"__format__", (PyCFunction)date_format, METH_VARARGS,
3530 PyDoc_STR("Formats self with strftime.")},
Eric Smitha9f7d622008-02-17 19:46:49 +00003531
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003532 {"utcoffset", (PyCFunction)time_utcoffset, METH_NOARGS,
3533 PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003534
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003535 {"tzname", (PyCFunction)time_tzname, METH_NOARGS,
3536 PyDoc_STR("Return self.tzinfo.tzname(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003537
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003538 {"dst", (PyCFunction)time_dst, METH_NOARGS,
3539 PyDoc_STR("Return self.tzinfo.dst(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003540
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003541 {"replace", (PyCFunction)time_replace, METH_VARARGS | METH_KEYWORDS,
3542 PyDoc_STR("Return time with new specified fields.")},
Tim Peters12bf3392002-12-24 05:41:27 +00003543
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003544 {"__reduce__", (PyCFunction)time_reduce, METH_NOARGS,
3545 PyDoc_STR("__reduce__() -> (cls, state)")},
Guido van Rossum177e41a2003-01-30 22:06:23 +00003546
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003547 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00003548};
3549
Tim Peters37f39822003-01-10 03:49:02 +00003550static char time_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00003551PyDoc_STR("time([hour[, minute[, second[, microsecond[, tzinfo]]]]]) --> a time object\n\
3552\n\
3553All arguments are optional. tzinfo may be None, or an instance of\n\
3554a tzinfo subclass. The remaining arguments may be ints or longs.\n");
Tim Peters2a799bf2002-12-16 20:18:38 +00003555
Tim Peters37f39822003-01-10 03:49:02 +00003556static PyNumberMethods time_as_number = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003557 0, /* nb_add */
3558 0, /* nb_subtract */
3559 0, /* nb_multiply */
3560 0, /* nb_divide */
3561 0, /* nb_remainder */
3562 0, /* nb_divmod */
3563 0, /* nb_power */
3564 0, /* nb_negative */
3565 0, /* nb_positive */
3566 0, /* nb_absolute */
3567 (inquiry)time_nonzero, /* nb_nonzero */
Tim Peters2a799bf2002-12-16 20:18:38 +00003568};
3569
Tim Peters37f39822003-01-10 03:49:02 +00003570statichere PyTypeObject PyDateTime_TimeType = {
Benjamin Petersona72d15c2017-09-13 21:20:29 -07003571 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003572 "datetime.time", /* tp_name */
3573 sizeof(PyDateTime_Time), /* tp_basicsize */
3574 0, /* tp_itemsize */
3575 (destructor)time_dealloc, /* tp_dealloc */
3576 0, /* tp_print */
3577 0, /* tp_getattr */
3578 0, /* tp_setattr */
3579 0, /* tp_compare */
3580 (reprfunc)time_repr, /* tp_repr */
3581 &time_as_number, /* tp_as_number */
3582 0, /* tp_as_sequence */
3583 0, /* tp_as_mapping */
3584 (hashfunc)time_hash, /* tp_hash */
3585 0, /* tp_call */
3586 (reprfunc)time_str, /* tp_str */
3587 PyObject_GenericGetAttr, /* tp_getattro */
3588 0, /* tp_setattro */
3589 0, /* tp_as_buffer */
3590 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
3591 Py_TPFLAGS_BASETYPE, /* tp_flags */
3592 time_doc, /* tp_doc */
3593 0, /* tp_traverse */
3594 0, /* tp_clear */
3595 (richcmpfunc)time_richcompare, /* tp_richcompare */
3596 0, /* tp_weaklistoffset */
3597 0, /* tp_iter */
3598 0, /* tp_iternext */
3599 time_methods, /* tp_methods */
3600 0, /* tp_members */
3601 time_getset, /* tp_getset */
3602 0, /* tp_base */
3603 0, /* tp_dict */
3604 0, /* tp_descr_get */
3605 0, /* tp_descr_set */
3606 0, /* tp_dictoffset */
3607 0, /* tp_init */
3608 time_alloc, /* tp_alloc */
3609 time_new, /* tp_new */
3610 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00003611};
3612
3613/*
Tim Petersa9bc1682003-01-11 03:39:11 +00003614 * PyDateTime_DateTime implementation.
Tim Peters2a799bf2002-12-16 20:18:38 +00003615 */
3616
Tim Petersa9bc1682003-01-11 03:39:11 +00003617/* Accessor properties. Properties for day, month, and year are inherited
3618 * from date.
Tim Peters2a799bf2002-12-16 20:18:38 +00003619 */
3620
3621static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003622datetime_hour(PyDateTime_DateTime *self, void *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00003623{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003624 return PyInt_FromLong(DATE_GET_HOUR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00003625}
3626
Tim Petersa9bc1682003-01-11 03:39:11 +00003627static PyObject *
3628datetime_minute(PyDateTime_DateTime *self, void *unused)
3629{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003630 return PyInt_FromLong(DATE_GET_MINUTE(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00003631}
3632
3633static PyObject *
3634datetime_second(PyDateTime_DateTime *self, void *unused)
3635{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003636 return PyInt_FromLong(DATE_GET_SECOND(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00003637}
3638
3639static PyObject *
3640datetime_microsecond(PyDateTime_DateTime *self, void *unused)
3641{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003642 return PyInt_FromLong(DATE_GET_MICROSECOND(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00003643}
3644
3645static PyObject *
3646datetime_tzinfo(PyDateTime_DateTime *self, void *unused)
3647{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003648 PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
3649 Py_INCREF(result);
3650 return result;
Tim Petersa9bc1682003-01-11 03:39:11 +00003651}
3652
3653static PyGetSetDef datetime_getset[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003654 {"hour", (getter)datetime_hour},
3655 {"minute", (getter)datetime_minute},
3656 {"second", (getter)datetime_second},
3657 {"microsecond", (getter)datetime_microsecond},
3658 {"tzinfo", (getter)datetime_tzinfo},
3659 {NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00003660};
3661
3662/*
3663 * Constructors.
Tim Peters2a799bf2002-12-16 20:18:38 +00003664 */
3665
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003666static char *datetime_kws[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003667 "year", "month", "day", "hour", "minute", "second",
3668 "microsecond", "tzinfo", NULL
Tim Peters12bf3392002-12-24 05:41:27 +00003669};
3670
Tim Peters2a799bf2002-12-16 20:18:38 +00003671static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003672datetime_new(PyTypeObject *type, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003673{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003674 PyObject *self = NULL;
3675 PyObject *state;
3676 int year;
3677 int month;
3678 int day;
3679 int hour = 0;
3680 int minute = 0;
3681 int second = 0;
3682 int usecond = 0;
3683 PyObject *tzinfo = Py_None;
Tim Peters2a799bf2002-12-16 20:18:38 +00003684
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003685 /* Check for invocation from pickle with __getstate__ state */
3686 if (PyTuple_GET_SIZE(args) >= 1 &&
3687 PyTuple_GET_SIZE(args) <= 2 &&
3688 PyString_Check(state = PyTuple_GET_ITEM(args, 0)) &&
3689 PyString_GET_SIZE(state) == _PyDateTime_DATETIME_DATASIZE &&
3690 MONTH_IS_SANE(PyString_AS_STRING(state)[2]))
3691 {
3692 PyDateTime_DateTime *me;
3693 char aware;
Tim Peters70533e22003-02-01 04:40:04 +00003694
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003695 if (PyTuple_GET_SIZE(args) == 2) {
3696 tzinfo = PyTuple_GET_ITEM(args, 1);
3697 if (check_tzinfo_subclass(tzinfo) < 0) {
3698 PyErr_SetString(PyExc_TypeError, "bad "
3699 "tzinfo state arg");
3700 return NULL;
3701 }
3702 }
3703 aware = (char)(tzinfo != Py_None);
3704 me = (PyDateTime_DateTime *) (type->tp_alloc(type , aware));
3705 if (me != NULL) {
3706 char *pdata = PyString_AS_STRING(state);
Tim Peters70533e22003-02-01 04:40:04 +00003707
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003708 memcpy(me->data, pdata, _PyDateTime_DATETIME_DATASIZE);
3709 me->hashcode = -1;
3710 me->hastzinfo = aware;
3711 if (aware) {
3712 Py_INCREF(tzinfo);
3713 me->tzinfo = tzinfo;
3714 }
3715 }
3716 return (PyObject *)me;
3717 }
Guido van Rossum177e41a2003-01-30 22:06:23 +00003718
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003719 if (PyArg_ParseTupleAndKeywords(args, kw, "iii|iiiiO", datetime_kws,
3720 &year, &month, &day, &hour, &minute,
3721 &second, &usecond, &tzinfo)) {
3722 if (check_date_args(year, month, day) < 0)
3723 return NULL;
3724 if (check_time_args(hour, minute, second, usecond) < 0)
3725 return NULL;
3726 if (check_tzinfo_subclass(tzinfo) < 0)
3727 return NULL;
3728 self = new_datetime_ex(year, month, day,
3729 hour, minute, second, usecond,
3730 tzinfo, type);
3731 }
3732 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00003733}
3734
Tim Petersa9bc1682003-01-11 03:39:11 +00003735/* TM_FUNC is the shared type of localtime() and gmtime(). */
3736typedef struct tm *(*TM_FUNC)(const time_t *timer);
3737
3738/* Internal helper.
3739 * Build datetime from a time_t and a distinct count of microseconds.
3740 * Pass localtime or gmtime for f, to control the interpretation of timet.
3741 */
3742static PyObject *
3743datetime_from_timet_and_us(PyObject *cls, TM_FUNC f, time_t timet, int us,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003744 PyObject *tzinfo)
Tim Petersa9bc1682003-01-11 03:39:11 +00003745{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003746 struct tm *tm;
3747 PyObject *result = NULL;
Tim Petersa9bc1682003-01-11 03:39:11 +00003748
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003749 tm = f(&timet);
3750 if (tm) {
3751 /* The platform localtime/gmtime may insert leap seconds,
3752 * indicated by tm->tm_sec > 59. We don't care about them,
3753 * except to the extent that passing them on to the datetime
3754 * constructor would raise ValueError for a reason that
3755 * made no sense to the user.
3756 */
3757 if (tm->tm_sec > 59)
3758 tm->tm_sec = 59;
3759 result = PyObject_CallFunction(cls, "iiiiiiiO",
3760 tm->tm_year + 1900,
3761 tm->tm_mon + 1,
3762 tm->tm_mday,
3763 tm->tm_hour,
3764 tm->tm_min,
3765 tm->tm_sec,
3766 us,
3767 tzinfo);
3768 }
3769 else
3770 PyErr_SetString(PyExc_ValueError,
3771 "timestamp out of range for "
3772 "platform localtime()/gmtime() function");
3773 return result;
Tim Petersa9bc1682003-01-11 03:39:11 +00003774}
3775
3776/* Internal helper.
3777 * Build datetime from a Python timestamp. Pass localtime or gmtime for f,
3778 * to control the interpretation of the timestamp. Since a double doesn't
3779 * have enough bits to cover a datetime's full range of precision, it's
3780 * better to call datetime_from_timet_and_us provided you have a way
3781 * to get that much precision (e.g., C time() isn't good enough).
3782 */
3783static PyObject *
3784datetime_from_timestamp(PyObject *cls, TM_FUNC f, double timestamp,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003785 PyObject *tzinfo)
Tim Petersa9bc1682003-01-11 03:39:11 +00003786{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003787 time_t timet;
3788 double fraction;
3789 int us;
Tim Petersa9bc1682003-01-11 03:39:11 +00003790
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003791 timet = _PyTime_DoubleToTimet(timestamp);
3792 if (timet == (time_t)-1 && PyErr_Occurred())
3793 return NULL;
3794 fraction = timestamp - (double)timet;
3795 us = (int)round_to_long(fraction * 1e6);
3796 if (us < 0) {
3797 /* Truncation towards zero is not what we wanted
3798 for negative numbers (Python's mod semantics) */
3799 timet -= 1;
3800 us += 1000000;
3801 }
3802 /* If timestamp is less than one microsecond smaller than a
3803 * full second, round up. Otherwise, ValueErrors are raised
3804 * for some floats. */
3805 if (us == 1000000) {
3806 timet += 1;
3807 us = 0;
3808 }
3809 return datetime_from_timet_and_us(cls, f, timet, us, tzinfo);
Tim Petersa9bc1682003-01-11 03:39:11 +00003810}
3811
3812/* Internal helper.
3813 * Build most accurate possible datetime for current time. Pass localtime or
3814 * gmtime for f as appropriate.
3815 */
3816static PyObject *
3817datetime_best_possible(PyObject *cls, TM_FUNC f, PyObject *tzinfo)
3818{
3819#ifdef HAVE_GETTIMEOFDAY
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003820 struct timeval t;
Tim Petersa9bc1682003-01-11 03:39:11 +00003821
3822#ifdef GETTIMEOFDAY_NO_TZ
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003823 gettimeofday(&t);
Tim Petersa9bc1682003-01-11 03:39:11 +00003824#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003825 gettimeofday(&t, (struct timezone *)NULL);
Tim Petersa9bc1682003-01-11 03:39:11 +00003826#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003827 return datetime_from_timet_and_us(cls, f, t.tv_sec, (int)t.tv_usec,
3828 tzinfo);
Tim Petersa9bc1682003-01-11 03:39:11 +00003829
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003830#else /* ! HAVE_GETTIMEOFDAY */
3831 /* No flavor of gettimeofday exists on this platform. Python's
3832 * time.time() does a lot of other platform tricks to get the
3833 * best time it can on the platform, and we're not going to do
3834 * better than that (if we could, the better code would belong
3835 * in time.time()!) We're limited by the precision of a double,
3836 * though.
3837 */
3838 PyObject *time;
3839 double dtime;
Tim Petersa9bc1682003-01-11 03:39:11 +00003840
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003841 time = time_time();
3842 if (time == NULL)
3843 return NULL;
3844 dtime = PyFloat_AsDouble(time);
3845 Py_DECREF(time);
3846 if (dtime == -1.0 && PyErr_Occurred())
3847 return NULL;
3848 return datetime_from_timestamp(cls, f, dtime, tzinfo);
3849#endif /* ! HAVE_GETTIMEOFDAY */
Tim Petersa9bc1682003-01-11 03:39:11 +00003850}
3851
Tim Peters2a799bf2002-12-16 20:18:38 +00003852/* Return best possible local time -- this isn't constrained by the
3853 * precision of a timestamp.
3854 */
3855static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003856datetime_now(PyObject *cls, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003857{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003858 PyObject *self;
3859 PyObject *tzinfo = Py_None;
3860 static char *keywords[] = {"tz", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00003861
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003862 if (! PyArg_ParseTupleAndKeywords(args, kw, "|O:now", keywords,
3863 &tzinfo))
3864 return NULL;
3865 if (check_tzinfo_subclass(tzinfo) < 0)
3866 return NULL;
Tim Peters10cadce2003-01-23 19:58:02 +00003867
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003868 self = datetime_best_possible(cls,
3869 tzinfo == Py_None ? localtime : gmtime,
3870 tzinfo);
3871 if (self != NULL && tzinfo != Py_None) {
3872 /* Convert UTC to tzinfo's zone. */
3873 PyObject *temp = self;
3874 self = PyObject_CallMethod(tzinfo, "fromutc", "O", self);
3875 Py_DECREF(temp);
3876 }
3877 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00003878}
3879
Tim Petersa9bc1682003-01-11 03:39:11 +00003880/* Return best possible UTC time -- this isn't constrained by the
3881 * precision of a timestamp.
3882 */
3883static PyObject *
3884datetime_utcnow(PyObject *cls, PyObject *dummy)
3885{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003886 return datetime_best_possible(cls, gmtime, Py_None);
Tim Petersa9bc1682003-01-11 03:39:11 +00003887}
3888
Tim Peters2a799bf2002-12-16 20:18:38 +00003889/* Return new local datetime from timestamp (Python timestamp -- a double). */
3890static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003891datetime_fromtimestamp(PyObject *cls, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003892{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003893 PyObject *self;
3894 double timestamp;
3895 PyObject *tzinfo = Py_None;
3896 static char *keywords[] = {"timestamp", "tz", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00003897
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003898 if (! PyArg_ParseTupleAndKeywords(args, kw, "d|O:fromtimestamp",
3899 keywords, &timestamp, &tzinfo))
3900 return NULL;
3901 if (check_tzinfo_subclass(tzinfo) < 0)
3902 return NULL;
Tim Peters2a44a8d2003-01-23 20:53:10 +00003903
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003904 self = datetime_from_timestamp(cls,
3905 tzinfo == Py_None ? localtime : gmtime,
3906 timestamp,
3907 tzinfo);
3908 if (self != NULL && tzinfo != Py_None) {
3909 /* Convert UTC to tzinfo's zone. */
3910 PyObject *temp = self;
3911 self = PyObject_CallMethod(tzinfo, "fromutc", "O", self);
3912 Py_DECREF(temp);
3913 }
3914 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00003915}
3916
Tim Petersa9bc1682003-01-11 03:39:11 +00003917/* Return new UTC datetime from timestamp (Python timestamp -- a double). */
3918static PyObject *
3919datetime_utcfromtimestamp(PyObject *cls, PyObject *args)
3920{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003921 double timestamp;
3922 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00003923
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003924 if (PyArg_ParseTuple(args, "d:utcfromtimestamp", &timestamp))
3925 result = datetime_from_timestamp(cls, gmtime, timestamp,
3926 Py_None);
3927 return result;
Tim Petersa9bc1682003-01-11 03:39:11 +00003928}
3929
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003930/* Return new datetime from time.strptime(). */
3931static PyObject *
3932datetime_strptime(PyObject *cls, PyObject *args)
3933{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003934 static PyObject *module = NULL;
3935 PyObject *result = NULL, *obj, *st = NULL, *frac = NULL;
3936 const char *string, *format;
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003937
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003938 if (!PyArg_ParseTuple(args, "ss:strptime", &string, &format))
3939 return NULL;
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003940
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003941 if (module == NULL &&
3942 (module = PyImport_ImportModuleNoBlock("_strptime")) == NULL)
3943 return NULL;
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003944
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003945 /* _strptime._strptime returns a two-element tuple. The first
3946 element is a time.struct_time object. The second is the
3947 microseconds (which are not defined for time.struct_time). */
3948 obj = PyObject_CallMethod(module, "_strptime", "ss", string, format);
3949 if (obj != NULL) {
3950 int i, good_timetuple = 1;
3951 long int ia[7];
3952 if (PySequence_Check(obj) && PySequence_Size(obj) == 2) {
3953 st = PySequence_GetItem(obj, 0);
3954 frac = PySequence_GetItem(obj, 1);
3955 if (st == NULL || frac == NULL)
3956 good_timetuple = 0;
3957 /* copy y/m/d/h/m/s values out of the
3958 time.struct_time */
3959 if (good_timetuple &&
3960 PySequence_Check(st) &&
3961 PySequence_Size(st) >= 6) {
3962 for (i=0; i < 6; i++) {
3963 PyObject *p = PySequence_GetItem(st, i);
3964 if (p == NULL) {
3965 good_timetuple = 0;
3966 break;
3967 }
3968 if (PyInt_Check(p))
3969 ia[i] = PyInt_AsLong(p);
3970 else
3971 good_timetuple = 0;
3972 Py_DECREF(p);
3973 }
3974 }
3975 else
3976 good_timetuple = 0;
3977 /* follow that up with a little dose of microseconds */
3978 if (good_timetuple && PyInt_Check(frac))
3979 ia[6] = PyInt_AsLong(frac);
3980 else
3981 good_timetuple = 0;
3982 }
3983 else
3984 good_timetuple = 0;
3985 if (good_timetuple)
3986 result = PyObject_CallFunction(cls, "iiiiiii",
3987 ia[0], ia[1], ia[2],
3988 ia[3], ia[4], ia[5],
3989 ia[6]);
3990 else
3991 PyErr_SetString(PyExc_ValueError,
3992 "unexpected value from _strptime._strptime");
3993 }
3994 Py_XDECREF(obj);
3995 Py_XDECREF(st);
3996 Py_XDECREF(frac);
3997 return result;
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003998}
3999
Tim Petersa9bc1682003-01-11 03:39:11 +00004000/* Return new datetime from date/datetime and time arguments. */
4001static PyObject *
4002datetime_combine(PyObject *cls, PyObject *args, PyObject *kw)
4003{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004004 static char *keywords[] = {"date", "time", NULL};
4005 PyObject *date;
4006 PyObject *time;
4007 PyObject *result = NULL;
Tim Petersa9bc1682003-01-11 03:39:11 +00004008
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004009 if (PyArg_ParseTupleAndKeywords(args, kw, "O!O!:combine", keywords,
4010 &PyDateTime_DateType, &date,
4011 &PyDateTime_TimeType, &time)) {
4012 PyObject *tzinfo = Py_None;
Tim Petersa9bc1682003-01-11 03:39:11 +00004013
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004014 if (HASTZINFO(time))
4015 tzinfo = ((PyDateTime_Time *)time)->tzinfo;
4016 result = PyObject_CallFunction(cls, "iiiiiiiO",
4017 GET_YEAR(date),
4018 GET_MONTH(date),
4019 GET_DAY(date),
4020 TIME_GET_HOUR(time),
4021 TIME_GET_MINUTE(time),
4022 TIME_GET_SECOND(time),
4023 TIME_GET_MICROSECOND(time),
4024 tzinfo);
4025 }
4026 return result;
Tim Petersa9bc1682003-01-11 03:39:11 +00004027}
Tim Peters2a799bf2002-12-16 20:18:38 +00004028
4029/*
4030 * Destructor.
4031 */
4032
4033static void
Tim Petersa9bc1682003-01-11 03:39:11 +00004034datetime_dealloc(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004035{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004036 if (HASTZINFO(self)) {
4037 Py_XDECREF(self->tzinfo);
4038 }
4039 Py_TYPE(self)->tp_free((PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00004040}
4041
4042/*
4043 * Indirect access to tzinfo methods.
4044 */
4045
Tim Peters2a799bf2002-12-16 20:18:38 +00004046/* These are all METH_NOARGS, so don't need to check the arglist. */
4047static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004048datetime_utcoffset(PyDateTime_DateTime *self, PyObject *unused) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004049 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
4050 "utcoffset", (PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00004051}
4052
4053static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004054datetime_dst(PyDateTime_DateTime *self, PyObject *unused) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004055 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
4056 "dst", (PyObject *)self);
Tim Peters855fe882002-12-22 03:43:39 +00004057}
4058
4059static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004060datetime_tzname(PyDateTime_DateTime *self, PyObject *unused) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004061 return call_tzname(HASTZINFO(self) ? self->tzinfo : Py_None,
4062 (PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00004063}
4064
4065/*
Tim Petersa9bc1682003-01-11 03:39:11 +00004066 * datetime arithmetic.
Tim Peters2a799bf2002-12-16 20:18:38 +00004067 */
4068
Tim Petersa9bc1682003-01-11 03:39:11 +00004069/* factor must be 1 (to add) or -1 (to subtract). The result inherits
4070 * the tzinfo state of date.
Tim Peters2a799bf2002-12-16 20:18:38 +00004071 */
4072static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004073add_datetime_timedelta(PyDateTime_DateTime *date, PyDateTime_Delta *delta,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004074 int factor)
Tim Peters2a799bf2002-12-16 20:18:38 +00004075{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004076 /* Note that the C-level additions can't overflow, because of
4077 * invariant bounds on the member values.
4078 */
4079 int year = GET_YEAR(date);
4080 int month = GET_MONTH(date);
4081 int day = GET_DAY(date) + GET_TD_DAYS(delta) * factor;
4082 int hour = DATE_GET_HOUR(date);
4083 int minute = DATE_GET_MINUTE(date);
4084 int second = DATE_GET_SECOND(date) + GET_TD_SECONDS(delta) * factor;
4085 int microsecond = DATE_GET_MICROSECOND(date) +
4086 GET_TD_MICROSECONDS(delta) * factor;
Tim Peters2a799bf2002-12-16 20:18:38 +00004087
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004088 assert(factor == 1 || factor == -1);
4089 if (normalize_datetime(&year, &month, &day,
4090 &hour, &minute, &second, &microsecond) < 0)
4091 return NULL;
4092 else
4093 return new_datetime(year, month, day,
4094 hour, minute, second, microsecond,
4095 HASTZINFO(date) ? date->tzinfo : Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004096}
4097
4098static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004099datetime_add(PyObject *left, PyObject *right)
Tim Peters2a799bf2002-12-16 20:18:38 +00004100{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004101 if (PyDateTime_Check(left)) {
4102 /* datetime + ??? */
4103 if (PyDelta_Check(right))
4104 /* datetime + delta */
4105 return add_datetime_timedelta(
4106 (PyDateTime_DateTime *)left,
4107 (PyDateTime_Delta *)right,
4108 1);
4109 }
4110 else if (PyDelta_Check(left)) {
4111 /* delta + datetime */
4112 return add_datetime_timedelta((PyDateTime_DateTime *) right,
4113 (PyDateTime_Delta *) left,
4114 1);
4115 }
4116 Py_INCREF(Py_NotImplemented);
4117 return Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00004118}
4119
4120static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004121datetime_subtract(PyObject *left, PyObject *right)
Tim Peters2a799bf2002-12-16 20:18:38 +00004122{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004123 PyObject *result = Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00004124
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004125 if (PyDateTime_Check(left)) {
4126 /* datetime - ??? */
4127 if (PyDateTime_Check(right)) {
4128 /* datetime - datetime */
4129 naivety n1, n2;
4130 int offset1, offset2;
4131 int delta_d, delta_s, delta_us;
Tim Peters2a799bf2002-12-16 20:18:38 +00004132
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004133 if (classify_two_utcoffsets(left, &offset1, &n1, left,
4134 right, &offset2, &n2,
4135 right) < 0)
4136 return NULL;
4137 assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
4138 if (n1 != n2) {
4139 PyErr_SetString(PyExc_TypeError,
4140 "can't subtract offset-naive and "
4141 "offset-aware datetimes");
4142 return NULL;
4143 }
4144 delta_d = ymd_to_ord(GET_YEAR(left),
4145 GET_MONTH(left),
4146 GET_DAY(left)) -
4147 ymd_to_ord(GET_YEAR(right),
4148 GET_MONTH(right),
4149 GET_DAY(right));
4150 /* These can't overflow, since the values are
4151 * normalized. At most this gives the number of
4152 * seconds in one day.
4153 */
4154 delta_s = (DATE_GET_HOUR(left) -
4155 DATE_GET_HOUR(right)) * 3600 +
4156 (DATE_GET_MINUTE(left) -
4157 DATE_GET_MINUTE(right)) * 60 +
4158 (DATE_GET_SECOND(left) -
4159 DATE_GET_SECOND(right));
4160 delta_us = DATE_GET_MICROSECOND(left) -
4161 DATE_GET_MICROSECOND(right);
4162 /* (left - offset1) - (right - offset2) =
4163 * (left - right) + (offset2 - offset1)
4164 */
4165 delta_s += (offset2 - offset1) * 60;
4166 result = new_delta(delta_d, delta_s, delta_us, 1);
4167 }
4168 else if (PyDelta_Check(right)) {
4169 /* datetime - delta */
4170 result = add_datetime_timedelta(
4171 (PyDateTime_DateTime *)left,
4172 (PyDateTime_Delta *)right,
4173 -1);
4174 }
4175 }
Tim Peters2a799bf2002-12-16 20:18:38 +00004176
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004177 if (result == Py_NotImplemented)
4178 Py_INCREF(result);
4179 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00004180}
4181
4182/* Various ways to turn a datetime into a string. */
4183
4184static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004185datetime_repr(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004186{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004187 char buffer[1000];
4188 const char *type_name = Py_TYPE(self)->tp_name;
4189 PyObject *baserepr;
Tim Peters2a799bf2002-12-16 20:18:38 +00004190
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004191 if (DATE_GET_MICROSECOND(self)) {
4192 PyOS_snprintf(buffer, sizeof(buffer),
4193 "%s(%d, %d, %d, %d, %d, %d, %d)",
4194 type_name,
4195 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4196 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4197 DATE_GET_SECOND(self),
4198 DATE_GET_MICROSECOND(self));
4199 }
4200 else if (DATE_GET_SECOND(self)) {
4201 PyOS_snprintf(buffer, sizeof(buffer),
4202 "%s(%d, %d, %d, %d, %d, %d)",
4203 type_name,
4204 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4205 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4206 DATE_GET_SECOND(self));
4207 }
4208 else {
4209 PyOS_snprintf(buffer, sizeof(buffer),
4210 "%s(%d, %d, %d, %d, %d)",
4211 type_name,
4212 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4213 DATE_GET_HOUR(self), DATE_GET_MINUTE(self));
4214 }
4215 baserepr = PyString_FromString(buffer);
4216 if (baserepr == NULL || ! HASTZINFO(self))
4217 return baserepr;
4218 return append_keyword_tzinfo(baserepr, self->tzinfo);
Tim Peters2a799bf2002-12-16 20:18:38 +00004219}
4220
Tim Petersa9bc1682003-01-11 03:39:11 +00004221static PyObject *
4222datetime_str(PyDateTime_DateTime *self)
4223{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004224 return PyObject_CallMethod((PyObject *)self, "isoformat", "(s)", " ");
Tim Petersa9bc1682003-01-11 03:39:11 +00004225}
Tim Peters2a799bf2002-12-16 20:18:38 +00004226
4227static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004228datetime_isoformat(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00004229{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004230 char sep = 'T';
4231 static char *keywords[] = {"sep", NULL};
4232 char buffer[100];
4233 char *cp;
4234 PyObject *result;
Tim Peters2a799bf2002-12-16 20:18:38 +00004235
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004236 if (!PyArg_ParseTupleAndKeywords(args, kw, "|c:isoformat", keywords,
4237 &sep))
4238 return NULL;
4239 cp = isoformat_date((PyDateTime_Date *)self, buffer, sizeof(buffer));
4240 assert(cp != NULL);
4241 *cp++ = sep;
4242 cp = isoformat_time(self, cp, sizeof(buffer) - (cp - buffer));
4243 result = PyString_FromStringAndSize(buffer, cp - buffer);
4244 if (result == NULL || ! HASTZINFO(self))
4245 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00004246
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004247 /* We need to append the UTC offset. */
4248 if (format_utcoffset(buffer, sizeof(buffer), ":", self->tzinfo,
4249 (PyObject *)self) < 0) {
4250 Py_DECREF(result);
4251 return NULL;
4252 }
4253 PyString_ConcatAndDel(&result, PyString_FromString(buffer));
4254 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00004255}
4256
Tim Petersa9bc1682003-01-11 03:39:11 +00004257static PyObject *
4258datetime_ctime(PyDateTime_DateTime *self)
4259{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004260 return format_ctime((PyDateTime_Date *)self,
4261 DATE_GET_HOUR(self),
4262 DATE_GET_MINUTE(self),
4263 DATE_GET_SECOND(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00004264}
4265
Tim Peters2a799bf2002-12-16 20:18:38 +00004266/* Miscellaneous methods. */
4267
Tim Petersa9bc1682003-01-11 03:39:11 +00004268/* This is more natural as a tp_compare, but doesn't work then: for whatever
4269 * reason, Python's try_3way_compare ignores tp_compare unless
4270 * PyInstance_Check returns true, but these aren't old-style classes.
4271 */
4272static PyObject *
4273datetime_richcompare(PyDateTime_DateTime *self, PyObject *other, int op)
4274{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004275 int diff;
4276 naivety n1, n2;
4277 int offset1, offset2;
Tim Petersa9bc1682003-01-11 03:39:11 +00004278
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004279 if (! PyDateTime_Check(other)) {
4280 /* If other has a "timetuple" attr, that's an advertised
4281 * hook for other classes to ask to get comparison control.
4282 * However, date instances have a timetuple attr, and we
4283 * don't want to allow that comparison. Because datetime
4284 * is a subclass of date, when mixing date and datetime
4285 * in a comparison, Python gives datetime the first shot
4286 * (it's the more specific subtype). So we can stop that
4287 * combination here reliably.
4288 */
4289 if (PyObject_HasAttrString(other, "timetuple") &&
4290 ! PyDate_Check(other)) {
4291 /* A hook for other kinds of datetime objects. */
4292 Py_INCREF(Py_NotImplemented);
4293 return Py_NotImplemented;
4294 }
4295 if (op == Py_EQ || op == Py_NE) {
4296 PyObject *result = op == Py_EQ ? Py_False : Py_True;
4297 Py_INCREF(result);
4298 return result;
4299 }
4300 /* Stop this from falling back to address comparison. */
4301 return cmperror((PyObject *)self, other);
4302 }
Tim Petersa9bc1682003-01-11 03:39:11 +00004303
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004304 if (classify_two_utcoffsets((PyObject *)self, &offset1, &n1,
4305 (PyObject *)self,
4306 other, &offset2, &n2,
4307 other) < 0)
4308 return NULL;
4309 assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
4310 /* If they're both naive, or both aware and have the same offsets,
4311 * we get off cheap. Note that if they're both naive, offset1 ==
4312 * offset2 == 0 at this point.
4313 */
4314 if (n1 == n2 && offset1 == offset2) {
4315 diff = memcmp(self->data, ((PyDateTime_DateTime *)other)->data,
4316 _PyDateTime_DATETIME_DATASIZE);
4317 return diff_to_bool(diff, op);
4318 }
Tim Petersa9bc1682003-01-11 03:39:11 +00004319
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004320 if (n1 == OFFSET_AWARE && n2 == OFFSET_AWARE) {
4321 PyDateTime_Delta *delta;
Tim Petersa9bc1682003-01-11 03:39:11 +00004322
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004323 assert(offset1 != offset2); /* else last "if" handled it */
4324 delta = (PyDateTime_Delta *)datetime_subtract((PyObject *)self,
4325 other);
4326 if (delta == NULL)
4327 return NULL;
4328 diff = GET_TD_DAYS(delta);
4329 if (diff == 0)
4330 diff = GET_TD_SECONDS(delta) |
4331 GET_TD_MICROSECONDS(delta);
4332 Py_DECREF(delta);
4333 return diff_to_bool(diff, op);
4334 }
Tim Petersa9bc1682003-01-11 03:39:11 +00004335
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004336 assert(n1 != n2);
4337 PyErr_SetString(PyExc_TypeError,
4338 "can't compare offset-naive and "
4339 "offset-aware datetimes");
4340 return NULL;
Tim Petersa9bc1682003-01-11 03:39:11 +00004341}
4342
4343static long
4344datetime_hash(PyDateTime_DateTime *self)
4345{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004346 if (self->hashcode == -1) {
4347 naivety n;
4348 int offset;
4349 PyObject *temp;
Tim Petersa9bc1682003-01-11 03:39:11 +00004350
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004351 n = classify_utcoffset((PyObject *)self, (PyObject *)self,
4352 &offset);
4353 assert(n != OFFSET_UNKNOWN);
4354 if (n == OFFSET_ERROR)
4355 return -1;
Tim Petersa9bc1682003-01-11 03:39:11 +00004356
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004357 /* Reduce this to a hash of another object. */
4358 if (n == OFFSET_NAIVE)
4359 temp = PyString_FromStringAndSize(
4360 (char *)self->data,
4361 _PyDateTime_DATETIME_DATASIZE);
4362 else {
4363 int days;
4364 int seconds;
Tim Petersa9bc1682003-01-11 03:39:11 +00004365
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004366 assert(n == OFFSET_AWARE);
4367 assert(HASTZINFO(self));
4368 days = ymd_to_ord(GET_YEAR(self),
4369 GET_MONTH(self),
4370 GET_DAY(self));
4371 seconds = DATE_GET_HOUR(self) * 3600 +
4372 (DATE_GET_MINUTE(self) - offset) * 60 +
4373 DATE_GET_SECOND(self);
4374 temp = new_delta(days,
4375 seconds,
4376 DATE_GET_MICROSECOND(self),
4377 1);
4378 }
4379 if (temp != NULL) {
4380 self->hashcode = PyObject_Hash(temp);
4381 Py_DECREF(temp);
4382 }
4383 }
4384 return self->hashcode;
Tim Petersa9bc1682003-01-11 03:39:11 +00004385}
Tim Peters2a799bf2002-12-16 20:18:38 +00004386
4387static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004388datetime_replace(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters12bf3392002-12-24 05:41:27 +00004389{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004390 PyObject *clone;
4391 PyObject *tuple;
4392 int y = GET_YEAR(self);
4393 int m = GET_MONTH(self);
4394 int d = GET_DAY(self);
4395 int hh = DATE_GET_HOUR(self);
4396 int mm = DATE_GET_MINUTE(self);
4397 int ss = DATE_GET_SECOND(self);
4398 int us = DATE_GET_MICROSECOND(self);
4399 PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
Tim Peters12bf3392002-12-24 05:41:27 +00004400
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004401 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiiiiO:replace",
4402 datetime_kws,
4403 &y, &m, &d, &hh, &mm, &ss, &us,
4404 &tzinfo))
4405 return NULL;
4406 tuple = Py_BuildValue("iiiiiiiO", y, m, d, hh, mm, ss, us, tzinfo);
4407 if (tuple == NULL)
4408 return NULL;
4409 clone = datetime_new(Py_TYPE(self), tuple, NULL);
4410 Py_DECREF(tuple);
4411 return clone;
Tim Peters12bf3392002-12-24 05:41:27 +00004412}
4413
4414static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004415datetime_astimezone(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters80475bb2002-12-25 07:40:55 +00004416{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004417 int y, m, d, hh, mm, ss, us;
4418 PyObject *result;
4419 int offset, none;
Tim Peters521fc152002-12-31 17:36:56 +00004420
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004421 PyObject *tzinfo;
4422 static char *keywords[] = {"tz", NULL};
Tim Peters80475bb2002-12-25 07:40:55 +00004423
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004424 if (! PyArg_ParseTupleAndKeywords(args, kw, "O!:astimezone", keywords,
4425 &PyDateTime_TZInfoType, &tzinfo))
4426 return NULL;
Tim Peters80475bb2002-12-25 07:40:55 +00004427
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004428 if (!HASTZINFO(self) || self->tzinfo == Py_None)
4429 goto NeedAware;
Tim Peters521fc152002-12-31 17:36:56 +00004430
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004431 /* Conversion to self's own time zone is a NOP. */
4432 if (self->tzinfo == tzinfo) {
4433 Py_INCREF(self);
4434 return (PyObject *)self;
4435 }
Tim Peters521fc152002-12-31 17:36:56 +00004436
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004437 /* Convert self to UTC. */
4438 offset = call_utcoffset(self->tzinfo, (PyObject *)self, &none);
4439 if (offset == -1 && PyErr_Occurred())
4440 return NULL;
4441 if (none)
4442 goto NeedAware;
Tim Petersf3615152003-01-01 21:51:37 +00004443
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004444 y = GET_YEAR(self);
4445 m = GET_MONTH(self);
4446 d = GET_DAY(self);
4447 hh = DATE_GET_HOUR(self);
4448 mm = DATE_GET_MINUTE(self);
4449 ss = DATE_GET_SECOND(self);
4450 us = DATE_GET_MICROSECOND(self);
Tim Peters52dcce22003-01-23 16:36:11 +00004451
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004452 mm -= offset;
4453 if ((mm < 0 || mm >= 60) &&
4454 normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
4455 return NULL;
Tim Peters52dcce22003-01-23 16:36:11 +00004456
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004457 /* Attach new tzinfo and let fromutc() do the rest. */
4458 result = new_datetime(y, m, d, hh, mm, ss, us, tzinfo);
4459 if (result != NULL) {
4460 PyObject *temp = result;
Tim Peters52dcce22003-01-23 16:36:11 +00004461
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004462 result = PyObject_CallMethod(tzinfo, "fromutc", "O", temp);
4463 Py_DECREF(temp);
4464 }
4465 return result;
Tim Peters521fc152002-12-31 17:36:56 +00004466
Tim Peters52dcce22003-01-23 16:36:11 +00004467NeedAware:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004468 PyErr_SetString(PyExc_ValueError, "astimezone() cannot be applied to "
4469 "a naive datetime");
4470 return NULL;
Tim Peters80475bb2002-12-25 07:40:55 +00004471}
4472
4473static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004474datetime_timetuple(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004475{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004476 int dstflag = -1;
Tim Peters2a799bf2002-12-16 20:18:38 +00004477
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004478 if (HASTZINFO(self) && self->tzinfo != Py_None) {
4479 int none;
Tim Peters2a799bf2002-12-16 20:18:38 +00004480
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004481 dstflag = call_dst(self->tzinfo, (PyObject *)self, &none);
4482 if (dstflag == -1 && PyErr_Occurred())
4483 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004484
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004485 if (none)
4486 dstflag = -1;
4487 else if (dstflag != 0)
4488 dstflag = 1;
Tim Peters2a799bf2002-12-16 20:18:38 +00004489
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004490 }
4491 return build_struct_time(GET_YEAR(self),
4492 GET_MONTH(self),
4493 GET_DAY(self),
4494 DATE_GET_HOUR(self),
4495 DATE_GET_MINUTE(self),
4496 DATE_GET_SECOND(self),
4497 dstflag);
Tim Peters2a799bf2002-12-16 20:18:38 +00004498}
4499
4500static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004501datetime_getdate(PyDateTime_DateTime *self)
4502{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004503 return new_date(GET_YEAR(self),
4504 GET_MONTH(self),
4505 GET_DAY(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00004506}
4507
4508static PyObject *
4509datetime_gettime(PyDateTime_DateTime *self)
4510{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004511 return new_time(DATE_GET_HOUR(self),
4512 DATE_GET_MINUTE(self),
4513 DATE_GET_SECOND(self),
4514 DATE_GET_MICROSECOND(self),
4515 Py_None);
Tim Petersa9bc1682003-01-11 03:39:11 +00004516}
4517
4518static PyObject *
4519datetime_gettimetz(PyDateTime_DateTime *self)
4520{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004521 return new_time(DATE_GET_HOUR(self),
4522 DATE_GET_MINUTE(self),
4523 DATE_GET_SECOND(self),
4524 DATE_GET_MICROSECOND(self),
4525 HASTZINFO(self) ? self->tzinfo : Py_None);
Tim Petersa9bc1682003-01-11 03:39:11 +00004526}
4527
4528static PyObject *
4529datetime_utctimetuple(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004530{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004531 int y = GET_YEAR(self);
4532 int m = GET_MONTH(self);
4533 int d = GET_DAY(self);
4534 int hh = DATE_GET_HOUR(self);
4535 int mm = DATE_GET_MINUTE(self);
4536 int ss = DATE_GET_SECOND(self);
4537 int us = 0; /* microseconds are ignored in a timetuple */
4538 int offset = 0;
Tim Peters2a799bf2002-12-16 20:18:38 +00004539
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004540 if (HASTZINFO(self) && self->tzinfo != Py_None) {
4541 int none;
Tim Peters2a799bf2002-12-16 20:18:38 +00004542
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004543 offset = call_utcoffset(self->tzinfo, (PyObject *)self, &none);
4544 if (offset == -1 && PyErr_Occurred())
4545 return NULL;
4546 }
4547 /* Even if offset is 0, don't call timetuple() -- tm_isdst should be
4548 * 0 in a UTC timetuple regardless of what dst() says.
4549 */
4550 if (offset) {
4551 /* Subtract offset minutes & normalize. */
4552 int stat;
Tim Peters2a799bf2002-12-16 20:18:38 +00004553
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004554 mm -= offset;
4555 stat = normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us);
4556 if (stat < 0) {
4557 /* At the edges, it's possible we overflowed
4558 * beyond MINYEAR or MAXYEAR.
4559 */
4560 if (PyErr_ExceptionMatches(PyExc_OverflowError))
4561 PyErr_Clear();
4562 else
4563 return NULL;
4564 }
4565 }
4566 return build_struct_time(y, m, d, hh, mm, ss, 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00004567}
4568
Tim Peters371935f2003-02-01 01:52:50 +00004569/* Pickle support, a simple use of __reduce__. */
Tim Peters33e0f382003-01-10 02:05:14 +00004570
Tim Petersa9bc1682003-01-11 03:39:11 +00004571/* Let basestate be the non-tzinfo data string.
Tim Peters2a799bf2002-12-16 20:18:38 +00004572 * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
4573 * So it's a tuple in any (non-error) case.
Tim Petersb57f8f02003-02-01 02:54:15 +00004574 * __getstate__ isn't exposed.
Tim Peters2a799bf2002-12-16 20:18:38 +00004575 */
4576static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004577datetime_getstate(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004578{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004579 PyObject *basestate;
4580 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004581
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004582 basestate = PyString_FromStringAndSize((char *)self->data,
4583 _PyDateTime_DATETIME_DATASIZE);
4584 if (basestate != NULL) {
4585 if (! HASTZINFO(self) || self->tzinfo == Py_None)
4586 result = PyTuple_Pack(1, basestate);
4587 else
4588 result = PyTuple_Pack(2, basestate, self->tzinfo);
4589 Py_DECREF(basestate);
4590 }
4591 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00004592}
4593
4594static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00004595datetime_reduce(PyDateTime_DateTime *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00004596{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004597 return Py_BuildValue("(ON)", Py_TYPE(self), datetime_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00004598}
4599
Tim Petersa9bc1682003-01-11 03:39:11 +00004600static PyMethodDef datetime_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00004601
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004602 /* Class methods: */
Tim Peters2a799bf2002-12-16 20:18:38 +00004603
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004604 {"now", (PyCFunction)datetime_now,
4605 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
4606 PyDoc_STR("[tz] -> new datetime with tz's local day and time.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004607
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004608 {"utcnow", (PyCFunction)datetime_utcnow,
4609 METH_NOARGS | METH_CLASS,
4610 PyDoc_STR("Return a new datetime representing UTC day and time.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00004611
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004612 {"fromtimestamp", (PyCFunction)datetime_fromtimestamp,
4613 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
4614 PyDoc_STR("timestamp[, tz] -> tz's local time from POSIX timestamp.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004615
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004616 {"utcfromtimestamp", (PyCFunction)datetime_utcfromtimestamp,
4617 METH_VARARGS | METH_CLASS,
4618 PyDoc_STR("timestamp -> UTC datetime from a POSIX timestamp "
4619 "(like time.time()).")},
Tim Petersa9bc1682003-01-11 03:39:11 +00004620
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004621 {"strptime", (PyCFunction)datetime_strptime,
4622 METH_VARARGS | METH_CLASS,
4623 PyDoc_STR("string, format -> new datetime parsed from a string "
4624 "(like time.strptime()).")},
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004625
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004626 {"combine", (PyCFunction)datetime_combine,
4627 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
4628 PyDoc_STR("date, time -> datetime with same date and time fields")},
Tim Petersa9bc1682003-01-11 03:39:11 +00004629
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004630 /* Instance methods: */
Guido van Rossum177e41a2003-01-30 22:06:23 +00004631
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004632 {"date", (PyCFunction)datetime_getdate, METH_NOARGS,
4633 PyDoc_STR("Return date object with same year, month and day.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00004634
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004635 {"time", (PyCFunction)datetime_gettime, METH_NOARGS,
4636 PyDoc_STR("Return time object with same time but with tzinfo=None.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00004637
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004638 {"timetz", (PyCFunction)datetime_gettimetz, METH_NOARGS,
4639 PyDoc_STR("Return time object with same time and tzinfo.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00004640
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004641 {"ctime", (PyCFunction)datetime_ctime, METH_NOARGS,
4642 PyDoc_STR("Return ctime() style string.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00004643
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004644 {"timetuple", (PyCFunction)datetime_timetuple, METH_NOARGS,
4645 PyDoc_STR("Return time tuple, compatible with time.localtime().")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004646
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004647 {"utctimetuple", (PyCFunction)datetime_utctimetuple, METH_NOARGS,
4648 PyDoc_STR("Return UTC time tuple, compatible with time.localtime().")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004649
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004650 {"isoformat", (PyCFunction)datetime_isoformat, METH_VARARGS | METH_KEYWORDS,
4651 PyDoc_STR("[sep] -> string in ISO 8601 format, "
4652 "YYYY-MM-DDTHH:MM:SS[.mmmmmm][+HH:MM].\n\n"
4653 "sep is used to separate the year from the time, and "
4654 "defaults to 'T'.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004655
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004656 {"utcoffset", (PyCFunction)datetime_utcoffset, METH_NOARGS,
4657 PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004658
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004659 {"tzname", (PyCFunction)datetime_tzname, METH_NOARGS,
4660 PyDoc_STR("Return self.tzinfo.tzname(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004661
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004662 {"dst", (PyCFunction)datetime_dst, METH_NOARGS,
4663 PyDoc_STR("Return self.tzinfo.dst(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004664
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004665 {"replace", (PyCFunction)datetime_replace, METH_VARARGS | METH_KEYWORDS,
4666 PyDoc_STR("Return datetime with new specified fields.")},
Tim Peters12bf3392002-12-24 05:41:27 +00004667
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004668 {"astimezone", (PyCFunction)datetime_astimezone, METH_VARARGS | METH_KEYWORDS,
4669 PyDoc_STR("tz -> convert to local time in new timezone tz\n")},
Tim Peters80475bb2002-12-25 07:40:55 +00004670
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004671 {"__reduce__", (PyCFunction)datetime_reduce, METH_NOARGS,
4672 PyDoc_STR("__reduce__() -> (cls, state)")},
Guido van Rossum177e41a2003-01-30 22:06:23 +00004673
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004674 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00004675};
4676
Tim Petersa9bc1682003-01-11 03:39:11 +00004677static char datetime_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00004678PyDoc_STR("datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]])\n\
4679\n\
4680The year, month and day arguments are required. tzinfo may be None, or an\n\
4681instance of a tzinfo subclass. The remaining arguments may be ints or longs.\n");
Tim Peters2a799bf2002-12-16 20:18:38 +00004682
Tim Petersa9bc1682003-01-11 03:39:11 +00004683static PyNumberMethods datetime_as_number = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004684 datetime_add, /* nb_add */
4685 datetime_subtract, /* nb_subtract */
4686 0, /* nb_multiply */
4687 0, /* nb_divide */
4688 0, /* nb_remainder */
4689 0, /* nb_divmod */
4690 0, /* nb_power */
4691 0, /* nb_negative */
4692 0, /* nb_positive */
4693 0, /* nb_absolute */
4694 0, /* nb_nonzero */
Tim Peters2a799bf2002-12-16 20:18:38 +00004695};
4696
Tim Petersa9bc1682003-01-11 03:39:11 +00004697statichere PyTypeObject PyDateTime_DateTimeType = {
Benjamin Petersona72d15c2017-09-13 21:20:29 -07004698 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004699 "datetime.datetime", /* tp_name */
4700 sizeof(PyDateTime_DateTime), /* tp_basicsize */
4701 0, /* tp_itemsize */
4702 (destructor)datetime_dealloc, /* tp_dealloc */
4703 0, /* tp_print */
4704 0, /* tp_getattr */
4705 0, /* tp_setattr */
4706 0, /* tp_compare */
4707 (reprfunc)datetime_repr, /* tp_repr */
4708 &datetime_as_number, /* tp_as_number */
4709 0, /* tp_as_sequence */
4710 0, /* tp_as_mapping */
4711 (hashfunc)datetime_hash, /* tp_hash */
4712 0, /* tp_call */
4713 (reprfunc)datetime_str, /* tp_str */
4714 PyObject_GenericGetAttr, /* tp_getattro */
4715 0, /* tp_setattro */
4716 0, /* tp_as_buffer */
4717 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
4718 Py_TPFLAGS_BASETYPE, /* tp_flags */
4719 datetime_doc, /* tp_doc */
4720 0, /* tp_traverse */
4721 0, /* tp_clear */
4722 (richcmpfunc)datetime_richcompare, /* tp_richcompare */
4723 0, /* tp_weaklistoffset */
4724 0, /* tp_iter */
4725 0, /* tp_iternext */
4726 datetime_methods, /* tp_methods */
4727 0, /* tp_members */
4728 datetime_getset, /* tp_getset */
4729 &PyDateTime_DateType, /* tp_base */
4730 0, /* tp_dict */
4731 0, /* tp_descr_get */
4732 0, /* tp_descr_set */
4733 0, /* tp_dictoffset */
4734 0, /* tp_init */
4735 datetime_alloc, /* tp_alloc */
4736 datetime_new, /* tp_new */
4737 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00004738};
4739
4740/* ---------------------------------------------------------------------------
4741 * Module methods and initialization.
4742 */
4743
4744static PyMethodDef module_methods[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004745 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00004746};
4747
Tim Peters9ddf40b2004-06-20 22:41:32 +00004748/* C API. Clients get at this via PyDateTime_IMPORT, defined in
4749 * datetime.h.
4750 */
4751static PyDateTime_CAPI CAPI = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004752 &PyDateTime_DateType,
4753 &PyDateTime_DateTimeType,
4754 &PyDateTime_TimeType,
4755 &PyDateTime_DeltaType,
4756 &PyDateTime_TZInfoType,
4757 new_date_ex,
4758 new_datetime_ex,
4759 new_time_ex,
4760 new_delta_ex,
4761 datetime_fromtimestamp,
4762 date_fromtimestamp
Tim Peters9ddf40b2004-06-20 22:41:32 +00004763};
4764
4765
Tim Peters2a799bf2002-12-16 20:18:38 +00004766PyMODINIT_FUNC
4767initdatetime(void)
4768{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004769 PyObject *m; /* a module object */
4770 PyObject *d; /* its dict */
4771 PyObject *x;
Tim Peters2a799bf2002-12-16 20:18:38 +00004772
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004773 m = Py_InitModule3("datetime", module_methods,
4774 "Fast implementation of the datetime type.");
4775 if (m == NULL)
4776 return;
Tim Peters2a799bf2002-12-16 20:18:38 +00004777
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004778 if (PyType_Ready(&PyDateTime_DateType) < 0)
4779 return;
4780 if (PyType_Ready(&PyDateTime_DateTimeType) < 0)
4781 return;
4782 if (PyType_Ready(&PyDateTime_DeltaType) < 0)
4783 return;
4784 if (PyType_Ready(&PyDateTime_TimeType) < 0)
4785 return;
4786 if (PyType_Ready(&PyDateTime_TZInfoType) < 0)
4787 return;
Tim Peters2a799bf2002-12-16 20:18:38 +00004788
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004789 /* timedelta values */
4790 d = PyDateTime_DeltaType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00004791
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004792 x = new_delta(0, 0, 1, 0);
4793 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4794 return;
4795 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00004796
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004797 x = new_delta(-MAX_DELTA_DAYS, 0, 0, 0);
4798 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4799 return;
4800 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00004801
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004802 x = new_delta(MAX_DELTA_DAYS, 24*3600-1, 1000000-1, 0);
4803 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4804 return;
4805 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00004806
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004807 /* date values */
4808 d = PyDateTime_DateType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00004809
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004810 x = new_date(1, 1, 1);
4811 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4812 return;
4813 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00004814
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004815 x = new_date(MAXYEAR, 12, 31);
4816 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4817 return;
4818 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00004819
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004820 x = new_delta(1, 0, 0, 0);
4821 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4822 return;
4823 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00004824
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004825 /* time values */
4826 d = PyDateTime_TimeType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00004827
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004828 x = new_time(0, 0, 0, 0, Py_None);
4829 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4830 return;
4831 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00004832
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004833 x = new_time(23, 59, 59, 999999, Py_None);
4834 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4835 return;
4836 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00004837
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004838 x = new_delta(0, 0, 1, 0);
4839 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4840 return;
4841 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00004842
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004843 /* datetime values */
4844 d = PyDateTime_DateTimeType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00004845
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004846 x = new_datetime(1, 1, 1, 0, 0, 0, 0, Py_None);
4847 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4848 return;
4849 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00004850
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004851 x = new_datetime(MAXYEAR, 12, 31, 23, 59, 59, 999999, Py_None);
4852 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4853 return;
4854 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00004855
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004856 x = new_delta(0, 0, 1, 0);
4857 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4858 return;
4859 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00004860
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004861 /* module initialization */
4862 PyModule_AddIntConstant(m, "MINYEAR", MINYEAR);
4863 PyModule_AddIntConstant(m, "MAXYEAR", MAXYEAR);
Tim Peters2a799bf2002-12-16 20:18:38 +00004864
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004865 Py_INCREF(&PyDateTime_DateType);
4866 PyModule_AddObject(m, "date", (PyObject *) &PyDateTime_DateType);
Tim Peters2a799bf2002-12-16 20:18:38 +00004867
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004868 Py_INCREF(&PyDateTime_DateTimeType);
4869 PyModule_AddObject(m, "datetime",
4870 (PyObject *)&PyDateTime_DateTimeType);
Tim Petersa9bc1682003-01-11 03:39:11 +00004871
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004872 Py_INCREF(&PyDateTime_TimeType);
4873 PyModule_AddObject(m, "time", (PyObject *) &PyDateTime_TimeType);
Tim Petersa9bc1682003-01-11 03:39:11 +00004874
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004875 Py_INCREF(&PyDateTime_DeltaType);
4876 PyModule_AddObject(m, "timedelta", (PyObject *) &PyDateTime_DeltaType);
Tim Peters2a799bf2002-12-16 20:18:38 +00004877
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004878 Py_INCREF(&PyDateTime_TZInfoType);
4879 PyModule_AddObject(m, "tzinfo", (PyObject *) &PyDateTime_TZInfoType);
Tim Peters2a799bf2002-12-16 20:18:38 +00004880
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004881 x = PyCapsule_New(&CAPI, PyDateTime_CAPSULE_NAME, NULL);
4882 if (x == NULL)
4883 return;
4884 PyModule_AddObject(m, "datetime_CAPI", x);
Tim Peters9ddf40b2004-06-20 22:41:32 +00004885
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004886 /* A 4-year cycle has an extra leap day over what we'd get from
4887 * pasting together 4 single years.
4888 */
4889 assert(DI4Y == 4 * 365 + 1);
4890 assert(DI4Y == days_before_year(4+1));
Tim Peters2a799bf2002-12-16 20:18:38 +00004891
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004892 /* Similarly, a 400-year cycle has an extra leap day over what we'd
4893 * get from pasting together 4 100-year cycles.
4894 */
4895 assert(DI400Y == 4 * DI100Y + 1);
4896 assert(DI400Y == days_before_year(400+1));
Tim Peters2a799bf2002-12-16 20:18:38 +00004897
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004898 /* OTOH, a 100-year cycle has one fewer leap day than we'd get from
4899 * pasting together 25 4-year cycles.
4900 */
4901 assert(DI100Y == 25 * DI4Y - 1);
4902 assert(DI100Y == days_before_year(100+1));
Tim Peters2a799bf2002-12-16 20:18:38 +00004903
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004904 us_per_us = PyInt_FromLong(1);
4905 us_per_ms = PyInt_FromLong(1000);
4906 us_per_second = PyInt_FromLong(1000000);
4907 us_per_minute = PyInt_FromLong(60000000);
4908 seconds_per_day = PyInt_FromLong(24 * 3600);
4909 if (us_per_us == NULL || us_per_ms == NULL || us_per_second == NULL ||
4910 us_per_minute == NULL || seconds_per_day == NULL)
4911 return;
Tim Peters2a799bf2002-12-16 20:18:38 +00004912
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004913 /* The rest are too big for 32-bit ints, but even
4914 * us_per_week fits in 40 bits, so doubles should be exact.
4915 */
4916 us_per_hour = PyLong_FromDouble(3600000000.0);
4917 us_per_day = PyLong_FromDouble(86400000000.0);
4918 us_per_week = PyLong_FromDouble(604800000000.0);
4919 if (us_per_hour == NULL || us_per_day == NULL || us_per_week == NULL)
4920 return;
Tim Peters2a799bf2002-12-16 20:18:38 +00004921}
Tim Petersf3615152003-01-01 21:51:37 +00004922
4923/* ---------------------------------------------------------------------------
Tim Petersa9bc1682003-01-11 03:39:11 +00004924Some time zone algebra. For a datetime x, let
Tim Petersf3615152003-01-01 21:51:37 +00004925 x.n = x stripped of its timezone -- its naive time.
4926 x.o = x.utcoffset(), and assuming that doesn't raise an exception or
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004927 return None
Tim Petersf3615152003-01-01 21:51:37 +00004928 x.d = x.dst(), and assuming that doesn't raise an exception or
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004929 return None
Tim Petersf3615152003-01-01 21:51:37 +00004930 x.s = x's standard offset, x.o - x.d
4931
4932Now some derived rules, where k is a duration (timedelta).
4933
49341. x.o = x.s + x.d
4935 This follows from the definition of x.s.
4936
Tim Petersc5dc4da2003-01-02 17:55:03 +000049372. If x and y have the same tzinfo member, x.s = y.s.
Tim Petersf3615152003-01-01 21:51:37 +00004938 This is actually a requirement, an assumption we need to make about
4939 sane tzinfo classes.
4940
49413. The naive UTC time corresponding to x is x.n - x.o.
4942 This is again a requirement for a sane tzinfo class.
4943
49444. (x+k).s = x.s
Tim Peters8bb5ad22003-01-24 02:44:45 +00004945 This follows from #2, and that datimetimetz+timedelta preserves tzinfo.
Tim Petersf3615152003-01-01 21:51:37 +00004946
Tim Petersc5dc4da2003-01-02 17:55:03 +000049475. (x+k).n = x.n + k
Tim Petersf3615152003-01-01 21:51:37 +00004948 Again follows from how arithmetic is defined.
4949
Tim Peters8bb5ad22003-01-24 02:44:45 +00004950Now we can explain tz.fromutc(x). Let's assume it's an interesting case
Tim Petersf3615152003-01-01 21:51:37 +00004951(meaning that the various tzinfo methods exist, and don't blow up or return
4952None when called).
4953
Tim Petersa9bc1682003-01-11 03:39:11 +00004954The function wants to return a datetime y with timezone tz, equivalent to x.
Tim Peters8bb5ad22003-01-24 02:44:45 +00004955x is already in UTC.
Tim Petersf3615152003-01-01 21:51:37 +00004956
4957By #3, we want
4958
Tim Peters8bb5ad22003-01-24 02:44:45 +00004959 y.n - y.o = x.n [1]
Tim Petersf3615152003-01-01 21:51:37 +00004960
4961The algorithm starts by attaching tz to x.n, and calling that y. So
4962x.n = y.n at the start. Then it wants to add a duration k to y, so that [1]
4963becomes true; in effect, we want to solve [2] for k:
4964
Tim Peters8bb5ad22003-01-24 02:44:45 +00004965 (y+k).n - (y+k).o = x.n [2]
Tim Petersf3615152003-01-01 21:51:37 +00004966
4967By #1, this is the same as
4968
Tim Peters8bb5ad22003-01-24 02:44:45 +00004969 (y+k).n - ((y+k).s + (y+k).d) = x.n [3]
Tim Petersf3615152003-01-01 21:51:37 +00004970
4971By #5, (y+k).n = y.n + k, which equals x.n + k because x.n=y.n at the start.
4972Substituting that into [3],
4973
Tim Peters8bb5ad22003-01-24 02:44:45 +00004974 x.n + k - (y+k).s - (y+k).d = x.n; the x.n terms cancel, leaving
4975 k - (y+k).s - (y+k).d = 0; rearranging,
4976 k = (y+k).s - (y+k).d; by #4, (y+k).s == y.s, so
4977 k = y.s - (y+k).d
Tim Petersf3615152003-01-01 21:51:37 +00004978
Tim Peters8bb5ad22003-01-24 02:44:45 +00004979On the RHS, (y+k).d can't be computed directly, but y.s can be, and we
4980approximate k by ignoring the (y+k).d term at first. Note that k can't be
4981very large, since all offset-returning methods return a duration of magnitude
4982less than 24 hours. For that reason, if y is firmly in std time, (y+k).d must
4983be 0, so ignoring it has no consequence then.
Tim Petersf3615152003-01-01 21:51:37 +00004984
4985In any case, the new value is
4986
Tim Peters8bb5ad22003-01-24 02:44:45 +00004987 z = y + y.s [4]
Tim Petersf3615152003-01-01 21:51:37 +00004988
Tim Peters8bb5ad22003-01-24 02:44:45 +00004989It's helpful to step back at look at [4] from a higher level: it's simply
4990mapping from UTC to tz's standard time.
Tim Petersc5dc4da2003-01-02 17:55:03 +00004991
4992At this point, if
4993
Tim Peters8bb5ad22003-01-24 02:44:45 +00004994 z.n - z.o = x.n [5]
Tim Petersc5dc4da2003-01-02 17:55:03 +00004995
4996we have an equivalent time, and are almost done. The insecurity here is
Tim Petersf3615152003-01-01 21:51:37 +00004997at the start of daylight time. Picture US Eastern for concreteness. The wall
4998time 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 +00004999sense then. The docs ask that an Eastern tzinfo class consider such a time to
5000be EDT (because it's "after 2"), which is a redundant spelling of 1:MM EST
5001on the day DST starts. We want to return the 1:MM EST spelling because that's
Tim Petersf3615152003-01-01 21:51:37 +00005002the only spelling that makes sense on the local wall clock.
5003
Tim Petersc5dc4da2003-01-02 17:55:03 +00005004In fact, if [5] holds at this point, we do have the standard-time spelling,
5005but that takes a bit of proof. We first prove a stronger result. What's the
5006difference between the LHS and RHS of [5]? Let
Tim Petersf3615152003-01-01 21:51:37 +00005007
Tim Peters8bb5ad22003-01-24 02:44:45 +00005008 diff = x.n - (z.n - z.o) [6]
Tim Petersf3615152003-01-01 21:51:37 +00005009
Tim Petersc5dc4da2003-01-02 17:55:03 +00005010Now
5011 z.n = by [4]
Tim Peters8bb5ad22003-01-24 02:44:45 +00005012 (y + y.s).n = by #5
5013 y.n + y.s = since y.n = x.n
5014 x.n + y.s = since z and y are have the same tzinfo member,
5015 y.s = z.s by #2
5016 x.n + z.s
Tim Petersf3615152003-01-01 21:51:37 +00005017
Tim Petersc5dc4da2003-01-02 17:55:03 +00005018Plugging that back into [6] gives
Tim Petersf3615152003-01-01 21:51:37 +00005019
Tim Petersc5dc4da2003-01-02 17:55:03 +00005020 diff =
Tim Peters8bb5ad22003-01-24 02:44:45 +00005021 x.n - ((x.n + z.s) - z.o) = expanding
5022 x.n - x.n - z.s + z.o = cancelling
5023 - z.s + z.o = by #2
Tim Petersc5dc4da2003-01-02 17:55:03 +00005024 z.d
Tim Petersf3615152003-01-01 21:51:37 +00005025
Tim Petersc5dc4da2003-01-02 17:55:03 +00005026So diff = z.d.
Tim Petersf3615152003-01-01 21:51:37 +00005027
Tim Petersc5dc4da2003-01-02 17:55:03 +00005028If [5] is true now, diff = 0, so z.d = 0 too, and we have the standard-time
Tim Peters8bb5ad22003-01-24 02:44:45 +00005029spelling we wanted in the endcase described above. We're done. Contrarily,
5030if z.d = 0, then we have a UTC equivalent, and are also done.
Tim Petersf3615152003-01-01 21:51:37 +00005031
Tim Petersc5dc4da2003-01-02 17:55:03 +00005032If [5] is not true now, diff = z.d != 0, and z.d is the offset we need to
5033add to z (in effect, z is in tz's standard time, and we need to shift the
Tim Peters8bb5ad22003-01-24 02:44:45 +00005034local clock into tz's daylight time).
Tim Petersf3615152003-01-01 21:51:37 +00005035
Tim Petersc5dc4da2003-01-02 17:55:03 +00005036Let
Tim Petersf3615152003-01-01 21:51:37 +00005037
Tim Peters4fede1a2003-01-04 00:26:59 +00005038 z' = z + z.d = z + diff [7]
Tim Petersc3bb26a2003-01-02 03:14:59 +00005039
Tim Peters4fede1a2003-01-04 00:26:59 +00005040and we can again ask whether
Tim Petersc3bb26a2003-01-02 03:14:59 +00005041
Tim Peters8bb5ad22003-01-24 02:44:45 +00005042 z'.n - z'.o = x.n [8]
Tim Petersc3bb26a2003-01-02 03:14:59 +00005043
Tim Peters8bb5ad22003-01-24 02:44:45 +00005044If so, we're done. If not, the tzinfo class is insane, according to the
5045assumptions we've made. This also requires a bit of proof. As before, let's
5046compute the difference between the LHS and RHS of [8] (and skipping some of
5047the justifications for the kinds of substitutions we've done several times
5048already):
Tim Peters4fede1a2003-01-04 00:26:59 +00005049
Tim Peters8bb5ad22003-01-24 02:44:45 +00005050 diff' = x.n - (z'.n - z'.o) = replacing z'.n via [7]
Antoine Pitrouc83ea132010-05-09 14:46:46 +00005051 x.n - (z.n + diff - z'.o) = replacing diff via [6]
5052 x.n - (z.n + x.n - (z.n - z.o) - z'.o) =
5053 x.n - z.n - x.n + z.n - z.o + z'.o = cancel x.n
5054 - z.n + z.n - z.o + z'.o = cancel z.n
5055 - z.o + z'.o = #1 twice
5056 -z.s - z.d + z'.s + z'.d = z and z' have same tzinfo
5057 z'.d - z.d
Tim Peters4fede1a2003-01-04 00:26:59 +00005058
5059So 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 +00005060we've found the UTC-equivalent so are done. In fact, we stop with [7] and
5061return z', not bothering to compute z'.d.
Tim Peters4fede1a2003-01-04 00:26:59 +00005062
Tim Peters8bb5ad22003-01-24 02:44:45 +00005063How could z.d and z'd differ? z' = z + z.d [7], so merely moving z' by
5064a dst() offset, and starting *from* a time already in DST (we know z.d != 0),
5065would have to change the result dst() returns: we start in DST, and moving
5066a little further into it takes us out of DST.
Tim Peters4fede1a2003-01-04 00:26:59 +00005067
Tim Peters8bb5ad22003-01-24 02:44:45 +00005068There isn't a sane case where this can happen. The closest it gets is at
5069the end of DST, where there's an hour in UTC with no spelling in a hybrid
5070tzinfo class. In US Eastern, that's 5:MM UTC = 0:MM EST = 1:MM EDT. During
5071that hour, on an Eastern clock 1:MM is taken as being in standard time (6:MM
5072UTC) because the docs insist on that, but 0:MM is taken as being in daylight
5073time (4:MM UTC). There is no local time mapping to 5:MM UTC. The local
5074clock jumps from 1:59 back to 1:00 again, and repeats the 1:MM hour in
5075standard time. Since that's what the local clock *does*, we want to map both
5076UTC hours 5:MM and 6:MM to 1:MM Eastern. The result is ambiguous
Tim Peters4fede1a2003-01-04 00:26:59 +00005077in local time, but so it goes -- it's the way the local clock works.
5078
Tim Peters8bb5ad22003-01-24 02:44:45 +00005079When x = 5:MM UTC is the input to this algorithm, x.o=0, y.o=-5 and y.d=0,
5080so z=0:MM. z.d=60 (minutes) then, so [5] doesn't hold and we keep going.
5081z' = 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 +00005082(correctly) concludes that z' is not UTC-equivalent to x.
5083
5084Because we know z.d said z was in daylight time (else [5] would have held and
5085we would have stopped then), and we know z.d != z'.d (else [8] would have held
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +00005086and we would have stopped then), and there are only 2 possible values dst() can
Tim Peters4fede1a2003-01-04 00:26:59 +00005087return in Eastern, it follows that z'.d must be 0 (which it is in the example,
5088but the reasoning doesn't depend on the example -- it depends on there being
5089two possible dst() outcomes, one zero and the other non-zero). Therefore
Tim Peters8bb5ad22003-01-24 02:44:45 +00005090z' must be in standard time, and is the spelling we want in this case.
5091
5092Note again that z' is not UTC-equivalent as far as the hybrid tzinfo class is
5093concerned (because it takes z' as being in standard time rather than the
5094daylight time we intend here), but returning it gives the real-life "local
5095clock repeats an hour" behavior when mapping the "unspellable" UTC hour into
5096tz.
5097
5098When the input is 6:MM, z=1:MM and z.d=0, and we stop at once, again with
5099the 1:MM standard time spelling we want.
5100
5101So how can this break? One of the assumptions must be violated. Two
5102possibilities:
5103
51041) [2] effectively says that y.s is invariant across all y belong to a given
5105 time zone. This isn't true if, for political reasons or continental drift,
5106 a region decides to change its base offset from UTC.
5107
51082) There may be versions of "double daylight" time where the tail end of
5109 the analysis gives up a step too early. I haven't thought about that
5110 enough to say.
5111
5112In any case, it's clear that the default fromutc() is strong enough to handle
5113"almost all" time zones: so long as the standard offset is invariant, it
5114doesn't matter if daylight time transition points change from year to year, or
5115if daylight time is skipped in some years; it doesn't matter how large or
5116small dst() may get within its bounds; and it doesn't even matter if some
5117perverse time zone returns a negative dst()). So a breaking case must be
5118pretty bizarre, and a tzinfo subclass can override fromutc() if it is.
Tim Petersf3615152003-01-01 21:51:37 +00005119--------------------------------------------------------------------------- */