blob: 6084ffa2013dd6bd19cc08053af786155b462b34 [file] [log] [blame]
Tim Peters2a799bf2002-12-16 20:18:38 +00001/* C implementation for the date/time type documented at
2 * http://www.zope.org/Members/fdrake/DateTimeWiki/FrontPage
3 */
4
5#include "Python.h"
Tim Peters2a799bf2002-12-16 20:18:38 +00006#include "structmember.h"
7
8#include <time.h>
9
Tim Peters9ddf40b2004-06-20 22:41:32 +000010/* Differentiate between building the core module and building extension
11 * modules.
12 */
Guido van Rossum360e4b82007-05-14 22:51:27 +000013#ifndef Py_BUILD_CORE
Tim Peters9ddf40b2004-06-20 22:41:32 +000014#define Py_BUILD_CORE
Guido van Rossum360e4b82007-05-14 22:51:27 +000015#endif
Tim Peters2a799bf2002-12-16 20:18:38 +000016#include "datetime.h"
Tim Peters9ddf40b2004-06-20 22:41:32 +000017#undef Py_BUILD_CORE
Tim Peters2a799bf2002-12-16 20:18:38 +000018
Larry Hastings61272b72014-01-07 12:41:53 -080019/*[clinic input]
Larry Hastings44e2eaa2013-11-23 15:37:55 -080020module datetime
Larry Hastingsc2047262014-01-25 20:43:29 -080021class datetime.datetime "PyDateTime_DateTime *" "&PyDateTime_DateTimeType"
Larry Hastings61272b72014-01-07 12:41:53 -080022[clinic start generated code]*/
Larry Hastings581ee362014-01-28 05:00:08 -080023/*[clinic end generated code: output=da39a3ee5e6b4b0d input=78142cb64b9e98bc]*/
Larry Hastings44e2eaa2013-11-23 15:37:55 -080024
Tim Peters2a799bf2002-12-16 20:18:38 +000025/* We require that C int be at least 32 bits, and use int virtually
26 * everywhere. In just a few cases we use a temp long, where a Python
27 * API returns a C long. In such cases, we have to ensure that the
28 * final result fits in a C int (this can be an issue on 64-bit boxes).
29 */
30#if SIZEOF_INT < 4
Alexander Belopolskycf86e362010-07-23 19:25:47 +000031# error "_datetime.c requires that C int have at least 32 bits"
Tim Peters2a799bf2002-12-16 20:18:38 +000032#endif
33
34#define MINYEAR 1
35#define MAXYEAR 9999
Alexander Belopolskyf03a6162010-05-27 21:42:58 +000036#define MAXORDINAL 3652059 /* date(9999,12,31).toordinal() */
Tim Peters2a799bf2002-12-16 20:18:38 +000037
38/* Nine decimal digits is easy to communicate, and leaves enough room
39 * so that two delta days can be added w/o fear of overflowing a signed
40 * 32-bit int, and with plenty of room left over to absorb any possible
41 * carries from adding seconds.
42 */
43#define MAX_DELTA_DAYS 999999999
44
45/* Rename the long macros in datetime.h to more reasonable short names. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000046#define GET_YEAR PyDateTime_GET_YEAR
47#define GET_MONTH PyDateTime_GET_MONTH
48#define GET_DAY PyDateTime_GET_DAY
49#define DATE_GET_HOUR PyDateTime_DATE_GET_HOUR
50#define DATE_GET_MINUTE PyDateTime_DATE_GET_MINUTE
51#define DATE_GET_SECOND PyDateTime_DATE_GET_SECOND
52#define DATE_GET_MICROSECOND PyDateTime_DATE_GET_MICROSECOND
Tim Peters2a799bf2002-12-16 20:18:38 +000053
54/* Date accessors for date and datetime. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000055#define SET_YEAR(o, v) (((o)->data[0] = ((v) & 0xff00) >> 8), \
56 ((o)->data[1] = ((v) & 0x00ff)))
57#define SET_MONTH(o, v) (PyDateTime_GET_MONTH(o) = (v))
58#define SET_DAY(o, v) (PyDateTime_GET_DAY(o) = (v))
Tim Peters2a799bf2002-12-16 20:18:38 +000059
60/* Date/Time accessors for datetime. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000061#define DATE_SET_HOUR(o, v) (PyDateTime_DATE_GET_HOUR(o) = (v))
62#define DATE_SET_MINUTE(o, v) (PyDateTime_DATE_GET_MINUTE(o) = (v))
63#define DATE_SET_SECOND(o, v) (PyDateTime_DATE_GET_SECOND(o) = (v))
64#define DATE_SET_MICROSECOND(o, v) \
65 (((o)->data[7] = ((v) & 0xff0000) >> 16), \
66 ((o)->data[8] = ((v) & 0x00ff00) >> 8), \
67 ((o)->data[9] = ((v) & 0x0000ff)))
Tim Peters2a799bf2002-12-16 20:18:38 +000068
69/* Time accessors for time. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000070#define TIME_GET_HOUR PyDateTime_TIME_GET_HOUR
71#define TIME_GET_MINUTE PyDateTime_TIME_GET_MINUTE
72#define TIME_GET_SECOND PyDateTime_TIME_GET_SECOND
73#define TIME_GET_MICROSECOND PyDateTime_TIME_GET_MICROSECOND
74#define TIME_SET_HOUR(o, v) (PyDateTime_TIME_GET_HOUR(o) = (v))
75#define TIME_SET_MINUTE(o, v) (PyDateTime_TIME_GET_MINUTE(o) = (v))
76#define TIME_SET_SECOND(o, v) (PyDateTime_TIME_GET_SECOND(o) = (v))
77#define TIME_SET_MICROSECOND(o, v) \
78 (((o)->data[3] = ((v) & 0xff0000) >> 16), \
79 ((o)->data[4] = ((v) & 0x00ff00) >> 8), \
80 ((o)->data[5] = ((v) & 0x0000ff)))
Tim Peters2a799bf2002-12-16 20:18:38 +000081
82/* Delta accessors for timedelta. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000083#define GET_TD_DAYS(o) (((PyDateTime_Delta *)(o))->days)
84#define GET_TD_SECONDS(o) (((PyDateTime_Delta *)(o))->seconds)
85#define GET_TD_MICROSECONDS(o) (((PyDateTime_Delta *)(o))->microseconds)
Tim Peters2a799bf2002-12-16 20:18:38 +000086
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000087#define SET_TD_DAYS(o, v) ((o)->days = (v))
88#define SET_TD_SECONDS(o, v) ((o)->seconds = (v))
Tim Peters2a799bf2002-12-16 20:18:38 +000089#define SET_TD_MICROSECONDS(o, v) ((o)->microseconds = (v))
90
Tim Petersa032d2e2003-01-11 00:15:54 +000091/* p is a pointer to a time or a datetime object; HASTZINFO(p) returns
92 * p->hastzinfo.
93 */
Alexander Belopolsky73ca4402010-07-07 23:56:38 +000094#define HASTZINFO(p) (((_PyDateTime_BaseTZInfo *)(p))->hastzinfo)
95#define GET_TIME_TZINFO(p) (HASTZINFO(p) ? \
96 ((PyDateTime_Time *)(p))->tzinfo : Py_None)
97#define GET_DT_TZINFO(p) (HASTZINFO(p) ? \
98 ((PyDateTime_DateTime *)(p))->tzinfo : Py_None)
Tim Peters3f606292004-03-21 23:38:41 +000099/* M is a char or int claiming to be a valid month. The macro is equivalent
100 * to the two-sided Python test
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000101 * 1 <= M <= 12
Tim Peters3f606292004-03-21 23:38:41 +0000102 */
103#define MONTH_IS_SANE(M) ((unsigned int)(M) - 1 < 12)
104
Tim Peters2a799bf2002-12-16 20:18:38 +0000105/* Forward declarations. */
106static PyTypeObject PyDateTime_DateType;
107static PyTypeObject PyDateTime_DateTimeType;
Tim Peters2a799bf2002-12-16 20:18:38 +0000108static PyTypeObject PyDateTime_DeltaType;
109static PyTypeObject PyDateTime_TimeType;
110static PyTypeObject PyDateTime_TZInfoType;
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000111static PyTypeObject PyDateTime_TimeZoneType;
Tim Peters2a799bf2002-12-16 20:18:38 +0000112
Martin v. Löwise75fc142013-11-07 18:46:53 +0100113_Py_IDENTIFIER(as_integer_ratio);
114_Py_IDENTIFIER(fromutc);
115_Py_IDENTIFIER(isoformat);
116_Py_IDENTIFIER(strftime);
117
Tim Peters2a799bf2002-12-16 20:18:38 +0000118/* ---------------------------------------------------------------------------
119 * Math utilities.
120 */
121
122/* k = i+j overflows iff k differs in sign from both inputs,
123 * iff k^i has sign bit set and k^j has sign bit set,
124 * iff (k^i)&(k^j) has sign bit set.
125 */
126#define SIGNED_ADD_OVERFLOWED(RESULT, I, J) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000127 ((((RESULT) ^ (I)) & ((RESULT) ^ (J))) < 0)
Tim Peters2a799bf2002-12-16 20:18:38 +0000128
129/* Compute Python divmod(x, y), returning the quotient and storing the
130 * remainder into *r. The quotient is the floor of x/y, and that's
131 * the real point of this. C will probably truncate instead (C99
132 * requires truncation; C89 left it implementation-defined).
133 * Simplification: we *require* that y > 0 here. That's appropriate
134 * for all the uses made of it. This simplifies the code and makes
135 * the overflow case impossible (divmod(LONG_MIN, -1) is the only
136 * overflow case).
137 */
138static int
139divmod(int x, int y, int *r)
140{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000141 int quo;
Tim Peters2a799bf2002-12-16 20:18:38 +0000142
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000143 assert(y > 0);
144 quo = x / y;
145 *r = x - quo * y;
146 if (*r < 0) {
147 --quo;
148 *r += y;
149 }
150 assert(0 <= *r && *r < y);
151 return quo;
Tim Peters2a799bf2002-12-16 20:18:38 +0000152}
153
Alexander Belopolsky1790bc42010-05-31 17:33:47 +0000154/* Nearest integer to m / n for integers m and n. Half-integer results
155 * are rounded to even.
156 */
157static PyObject *
158divide_nearest(PyObject *m, PyObject *n)
159{
160 PyObject *result;
161 PyObject *temp;
162
Mark Dickinsonfa68a612010-06-07 18:47:09 +0000163 temp = _PyLong_DivmodNear(m, n);
Alexander Belopolsky1790bc42010-05-31 17:33:47 +0000164 if (temp == NULL)
165 return NULL;
166 result = PyTuple_GET_ITEM(temp, 0);
167 Py_INCREF(result);
168 Py_DECREF(temp);
169
170 return result;
171}
172
Tim Peters2a799bf2002-12-16 20:18:38 +0000173/* ---------------------------------------------------------------------------
174 * General calendrical helper functions
175 */
176
177/* For each month ordinal in 1..12, the number of days in that month,
178 * and the number of days before that month in the same year. These
179 * are correct for non-leap years only.
180 */
181static int _days_in_month[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000182 0, /* unused; this vector uses 1-based indexing */
183 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
Tim Peters2a799bf2002-12-16 20:18:38 +0000184};
185
186static int _days_before_month[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000187 0, /* unused; this vector uses 1-based indexing */
188 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
Tim Peters2a799bf2002-12-16 20:18:38 +0000189};
190
191/* year -> 1 if leap year, else 0. */
192static int
193is_leap(int year)
194{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000195 /* Cast year to unsigned. The result is the same either way, but
196 * C can generate faster code for unsigned mod than for signed
197 * mod (especially for % 4 -- a good compiler should just grab
198 * the last 2 bits when the LHS is unsigned).
199 */
200 const unsigned int ayear = (unsigned int)year;
201 return ayear % 4 == 0 && (ayear % 100 != 0 || ayear % 400 == 0);
Tim Peters2a799bf2002-12-16 20:18:38 +0000202}
203
204/* year, month -> number of days in that month in that year */
205static int
206days_in_month(int year, int month)
207{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000208 assert(month >= 1);
209 assert(month <= 12);
210 if (month == 2 && is_leap(year))
211 return 29;
212 else
213 return _days_in_month[month];
Tim Peters2a799bf2002-12-16 20:18:38 +0000214}
215
216/* year, month -> number of days in year preceeding first day of month */
217static int
218days_before_month(int year, int month)
219{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000220 int days;
Tim Peters2a799bf2002-12-16 20:18:38 +0000221
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000222 assert(month >= 1);
223 assert(month <= 12);
224 days = _days_before_month[month];
225 if (month > 2 && is_leap(year))
226 ++days;
227 return days;
Tim Peters2a799bf2002-12-16 20:18:38 +0000228}
229
230/* year -> number of days before January 1st of year. Remember that we
231 * start with year 1, so days_before_year(1) == 0.
232 */
233static int
234days_before_year(int year)
235{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000236 int y = year - 1;
237 /* This is incorrect if year <= 0; we really want the floor
238 * here. But so long as MINYEAR is 1, the smallest year this
Alexander Belopolsky59a289d2010-10-13 22:54:34 +0000239 * can see is 1.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000240 */
Alexander Belopolsky59a289d2010-10-13 22:54:34 +0000241 assert (year >= 1);
242 return y*365 + y/4 - y/100 + y/400;
Tim Peters2a799bf2002-12-16 20:18:38 +0000243}
244
245/* Number of days in 4, 100, and 400 year cycles. That these have
246 * the correct values is asserted in the module init function.
247 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000248#define DI4Y 1461 /* days_before_year(5); days in 4 years */
249#define DI100Y 36524 /* days_before_year(101); days in 100 years */
250#define DI400Y 146097 /* days_before_year(401); days in 400 years */
Tim Peters2a799bf2002-12-16 20:18:38 +0000251
252/* ordinal -> year, month, day, considering 01-Jan-0001 as day 1. */
253static void
254ord_to_ymd(int ordinal, int *year, int *month, int *day)
255{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000256 int n, n1, n4, n100, n400, leapyear, preceding;
Tim Peters2a799bf2002-12-16 20:18:38 +0000257
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000258 /* ordinal is a 1-based index, starting at 1-Jan-1. The pattern of
259 * leap years repeats exactly every 400 years. The basic strategy is
260 * to find the closest 400-year boundary at or before ordinal, then
261 * work with the offset from that boundary to ordinal. Life is much
262 * clearer if we subtract 1 from ordinal first -- then the values
263 * of ordinal at 400-year boundaries are exactly those divisible
264 * by DI400Y:
265 *
266 * D M Y n n-1
267 * -- --- ---- ---------- ----------------
268 * 31 Dec -400 -DI400Y -DI400Y -1
269 * 1 Jan -399 -DI400Y +1 -DI400Y 400-year boundary
270 * ...
271 * 30 Dec 000 -1 -2
272 * 31 Dec 000 0 -1
273 * 1 Jan 001 1 0 400-year boundary
274 * 2 Jan 001 2 1
275 * 3 Jan 001 3 2
276 * ...
277 * 31 Dec 400 DI400Y DI400Y -1
278 * 1 Jan 401 DI400Y +1 DI400Y 400-year boundary
279 */
280 assert(ordinal >= 1);
281 --ordinal;
282 n400 = ordinal / DI400Y;
283 n = ordinal % DI400Y;
284 *year = n400 * 400 + 1;
Tim Peters2a799bf2002-12-16 20:18:38 +0000285
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000286 /* Now n is the (non-negative) offset, in days, from January 1 of
287 * year, to the desired date. Now compute how many 100-year cycles
288 * precede n.
289 * Note that it's possible for n100 to equal 4! In that case 4 full
290 * 100-year cycles precede the desired day, which implies the
291 * desired day is December 31 at the end of a 400-year cycle.
292 */
293 n100 = n / DI100Y;
294 n = n % DI100Y;
Tim Peters2a799bf2002-12-16 20:18:38 +0000295
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000296 /* Now compute how many 4-year cycles precede it. */
297 n4 = n / DI4Y;
298 n = n % DI4Y;
Tim Peters2a799bf2002-12-16 20:18:38 +0000299
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000300 /* And now how many single years. Again n1 can be 4, and again
301 * meaning that the desired day is December 31 at the end of the
302 * 4-year cycle.
303 */
304 n1 = n / 365;
305 n = n % 365;
Tim Peters2a799bf2002-12-16 20:18:38 +0000306
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000307 *year += n100 * 100 + n4 * 4 + n1;
308 if (n1 == 4 || n100 == 4) {
309 assert(n == 0);
310 *year -= 1;
311 *month = 12;
312 *day = 31;
313 return;
314 }
Tim Peters2a799bf2002-12-16 20:18:38 +0000315
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000316 /* Now the year is correct, and n is the offset from January 1. We
317 * find the month via an estimate that's either exact or one too
318 * large.
319 */
320 leapyear = n1 == 3 && (n4 != 24 || n100 == 3);
321 assert(leapyear == is_leap(*year));
322 *month = (n + 50) >> 5;
323 preceding = (_days_before_month[*month] + (*month > 2 && leapyear));
324 if (preceding > n) {
325 /* estimate is too large */
326 *month -= 1;
327 preceding -= days_in_month(*year, *month);
328 }
329 n -= preceding;
330 assert(0 <= n);
331 assert(n < days_in_month(*year, *month));
Tim Peters2a799bf2002-12-16 20:18:38 +0000332
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000333 *day = n + 1;
Tim Peters2a799bf2002-12-16 20:18:38 +0000334}
335
336/* year, month, day -> ordinal, considering 01-Jan-0001 as day 1. */
337static int
338ymd_to_ord(int year, int month, int day)
339{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000340 return days_before_year(year) + days_before_month(year, month) + day;
Tim Peters2a799bf2002-12-16 20:18:38 +0000341}
342
343/* Day of week, where Monday==0, ..., Sunday==6. 1/1/1 was a Monday. */
344static int
345weekday(int year, int month, int day)
346{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000347 return (ymd_to_ord(year, month, day) + 6) % 7;
Tim Peters2a799bf2002-12-16 20:18:38 +0000348}
349
350/* Ordinal of the Monday starting week 1 of the ISO year. Week 1 is the
351 * first calendar week containing a Thursday.
352 */
353static int
354iso_week1_monday(int year)
355{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000356 int first_day = ymd_to_ord(year, 1, 1); /* ord of 1/1 */
357 /* 0 if 1/1 is a Monday, 1 if a Tue, etc. */
358 int first_weekday = (first_day + 6) % 7;
359 /* ordinal of closest Monday at or before 1/1 */
360 int week1_monday = first_day - first_weekday;
Tim Peters2a799bf2002-12-16 20:18:38 +0000361
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000362 if (first_weekday > 3) /* if 1/1 was Fri, Sat, Sun */
363 week1_monday += 7;
364 return week1_monday;
Tim Peters2a799bf2002-12-16 20:18:38 +0000365}
366
367/* ---------------------------------------------------------------------------
368 * Range checkers.
369 */
370
371/* Check that -MAX_DELTA_DAYS <= days <= MAX_DELTA_DAYS. If so, return 0.
372 * If not, raise OverflowError and return -1.
373 */
374static int
375check_delta_day_range(int days)
376{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000377 if (-MAX_DELTA_DAYS <= days && days <= MAX_DELTA_DAYS)
378 return 0;
379 PyErr_Format(PyExc_OverflowError,
380 "days=%d; must have magnitude <= %d",
381 days, MAX_DELTA_DAYS);
382 return -1;
Tim Peters2a799bf2002-12-16 20:18:38 +0000383}
384
385/* Check that date arguments are in range. Return 0 if they are. If they
386 * aren't, raise ValueError and return -1.
387 */
388static int
389check_date_args(int year, int month, int day)
390{
391
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000392 if (year < MINYEAR || year > MAXYEAR) {
393 PyErr_SetString(PyExc_ValueError,
394 "year is out of range");
395 return -1;
396 }
397 if (month < 1 || month > 12) {
398 PyErr_SetString(PyExc_ValueError,
399 "month must be in 1..12");
400 return -1;
401 }
402 if (day < 1 || day > days_in_month(year, month)) {
403 PyErr_SetString(PyExc_ValueError,
404 "day is out of range for month");
405 return -1;
406 }
407 return 0;
Tim Peters2a799bf2002-12-16 20:18:38 +0000408}
409
410/* Check that time arguments are in range. Return 0 if they are. If they
411 * aren't, raise ValueError and return -1.
412 */
413static int
414check_time_args(int h, int m, int s, int us)
415{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000416 if (h < 0 || h > 23) {
417 PyErr_SetString(PyExc_ValueError,
418 "hour must be in 0..23");
419 return -1;
420 }
421 if (m < 0 || m > 59) {
422 PyErr_SetString(PyExc_ValueError,
423 "minute must be in 0..59");
424 return -1;
425 }
426 if (s < 0 || s > 59) {
427 PyErr_SetString(PyExc_ValueError,
428 "second must be in 0..59");
429 return -1;
430 }
431 if (us < 0 || us > 999999) {
432 PyErr_SetString(PyExc_ValueError,
433 "microsecond must be in 0..999999");
434 return -1;
435 }
436 return 0;
Tim Peters2a799bf2002-12-16 20:18:38 +0000437}
438
439/* ---------------------------------------------------------------------------
440 * Normalization utilities.
441 */
442
443/* One step of a mixed-radix conversion. A "hi" unit is equivalent to
444 * factor "lo" units. factor must be > 0. If *lo is less than 0, or
445 * at least factor, enough of *lo is converted into "hi" units so that
446 * 0 <= *lo < factor. The input values must be such that int overflow
447 * is impossible.
448 */
449static void
450normalize_pair(int *hi, int *lo, int factor)
451{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000452 assert(factor > 0);
453 assert(lo != hi);
454 if (*lo < 0 || *lo >= factor) {
455 const int num_hi = divmod(*lo, factor, lo);
456 const int new_hi = *hi + num_hi;
457 assert(! SIGNED_ADD_OVERFLOWED(new_hi, *hi, num_hi));
458 *hi = new_hi;
459 }
460 assert(0 <= *lo && *lo < factor);
Tim Peters2a799bf2002-12-16 20:18:38 +0000461}
462
463/* Fiddle days (d), seconds (s), and microseconds (us) so that
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000464 * 0 <= *s < 24*3600
465 * 0 <= *us < 1000000
Tim Peters2a799bf2002-12-16 20:18:38 +0000466 * The input values must be such that the internals don't overflow.
467 * The way this routine is used, we don't get close.
468 */
469static void
470normalize_d_s_us(int *d, int *s, int *us)
471{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000472 if (*us < 0 || *us >= 1000000) {
473 normalize_pair(s, us, 1000000);
474 /* |s| can't be bigger than about
475 * |original s| + |original us|/1000000 now.
476 */
Tim Peters2a799bf2002-12-16 20:18:38 +0000477
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000478 }
479 if (*s < 0 || *s >= 24*3600) {
480 normalize_pair(d, s, 24*3600);
481 /* |d| can't be bigger than about
482 * |original d| +
483 * (|original s| + |original us|/1000000) / (24*3600) now.
484 */
485 }
486 assert(0 <= *s && *s < 24*3600);
487 assert(0 <= *us && *us < 1000000);
Tim Peters2a799bf2002-12-16 20:18:38 +0000488}
489
490/* Fiddle years (y), months (m), and days (d) so that
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000491 * 1 <= *m <= 12
492 * 1 <= *d <= days_in_month(*y, *m)
Tim Peters2a799bf2002-12-16 20:18:38 +0000493 * The input values must be such that the internals don't overflow.
494 * The way this routine is used, we don't get close.
495 */
Alexander Belopolskyf03a6162010-05-27 21:42:58 +0000496static int
Tim Peters2a799bf2002-12-16 20:18:38 +0000497normalize_y_m_d(int *y, int *m, int *d)
498{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000499 int dim; /* # of days in month */
Tim Peters2a799bf2002-12-16 20:18:38 +0000500
Alexander Belopolsky59a289d2010-10-13 22:54:34 +0000501 /* In actual use, m is always the month component extracted from a
502 * date/datetime object. Therefore it is always in [1, 12] range.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000503 */
Alexander Belopolsky59a289d2010-10-13 22:54:34 +0000504
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000505 assert(1 <= *m && *m <= 12);
Tim Peters2a799bf2002-12-16 20:18:38 +0000506
Antoine Pitrouf95a1b32010-05-09 15:52:27 +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 Belopolskyf03a6162010-05-27 21:42:58 +0000540 if (ordinal < 1 || ordinal > MAXORDINAL) {
541 goto error;
542 } else {
543 ord_to_ymd(ordinal, y, m, d);
544 return 0;
545 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000546 }
547 }
548 assert(*m > 0);
549 assert(*d > 0);
Alexander Belopolskyf03a6162010-05-27 21:42:58 +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 Belopolskyf03a6162010-05-27 21:42:58 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +0000608 PyObject *self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000609
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000610 self = (PyObject *)
611 PyObject_MALLOC(aware ?
612 sizeof(PyDateTime_Time) :
613 sizeof(_PyDateTime_BaseTime));
614 if (self == NULL)
615 return (PyObject *)PyErr_NoMemory();
Christian Heimesecb4e6a2013-12-04 09:34:29 +0100616 (void)PyObject_INIT(self, type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +0000623 PyObject *self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000624
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000625 self = (PyObject *)
626 PyObject_MALLOC(aware ?
627 sizeof(PyDateTime_DateTime) :
628 sizeof(_PyDateTime_BaseDateTime));
629 if (self == NULL)
630 return (PyObject *)PyErr_NoMemory();
Christian Heimesecb4e6a2013-12-04 09:34:29 +0100631 (void)PyObject_INIT(self, type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +0000658 PyDateTime_Date *self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000659
Antoine Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +0000672 int second, int usecond, PyObject *tzinfo, PyTypeObject *type)
Tim Petersb0c854d2003-05-17 15:57:00 +0000673{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000674 PyDateTime_DateTime *self;
675 char aware = tzinfo != Py_None;
Tim Petersb0c854d2003-05-17 15:57:00 +0000676
Antoine Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +0000700 PyObject *tzinfo, PyTypeObject *type)
Tim Petersb0c854d2003-05-17 15:57:00 +0000701{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000702 PyDateTime_Time *self;
703 char aware = tzinfo != Py_None;
Tim Petersb0c854d2003-05-17 15:57:00 +0000704
Antoine Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +0000732 PyTypeObject *type)
Tim Petersb0c854d2003-05-17 15:57:00 +0000733{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000734 PyDateTime_Delta *self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000735
Antoine Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +0000741 if (check_delta_day_range(days) < 0)
742 return NULL;
Tim Petersb0c854d2003-05-17 15:57:00 +0000743
Antoine Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000757
758typedef struct
759{
760 PyObject_HEAD
761 PyObject *offset;
762 PyObject *name;
763} PyDateTime_TimeZone;
764
Victor Stinner6ced7c42011-03-21 18:15:42 +0100765/* The interned UTC timezone instance */
Alexander Belopolsky1bcbaab2010-10-14 17:03:51 +0000766static PyObject *PyDateTime_TimeZone_UTC;
Alexander Belopolskya4415142012-06-08 12:33:09 -0400767/* The interned Epoch datetime instance */
768static PyObject *PyDateTime_Epoch;
Alexander Belopolskya11d8c02010-07-06 23:19:45 +0000769
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000770/* Create new timezone instance checking offset range. This
771 function does not check the name argument. Caller must assure
772 that offset is a timedelta instance and name is either NULL
773 or a unicode object. */
774static PyObject *
Alexander Belopolsky1bcbaab2010-10-14 17:03:51 +0000775create_timezone(PyObject *offset, PyObject *name)
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000776{
777 PyDateTime_TimeZone *self;
778 PyTypeObject *type = &PyDateTime_TimeZoneType;
779
780 assert(offset != NULL);
781 assert(PyDelta_Check(offset));
782 assert(name == NULL || PyUnicode_Check(name));
783
Alexander Belopolsky1bcbaab2010-10-14 17:03:51 +0000784 self = (PyDateTime_TimeZone *)(type->tp_alloc(type, 0));
785 if (self == NULL) {
786 return NULL;
787 }
788 Py_INCREF(offset);
789 self->offset = offset;
790 Py_XINCREF(name);
791 self->name = name;
792 return (PyObject *)self;
793}
794
795static int delta_bool(PyDateTime_Delta *self);
796
797static PyObject *
798new_timezone(PyObject *offset, PyObject *name)
799{
800 assert(offset != NULL);
801 assert(PyDelta_Check(offset));
802 assert(name == NULL || PyUnicode_Check(name));
803
804 if (name == NULL && delta_bool((PyDateTime_Delta *)offset) == 0) {
805 Py_INCREF(PyDateTime_TimeZone_UTC);
806 return PyDateTime_TimeZone_UTC;
807 }
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000808 if (GET_TD_MICROSECONDS(offset) != 0 || GET_TD_SECONDS(offset) % 60 != 0) {
809 PyErr_Format(PyExc_ValueError, "offset must be a timedelta"
Alexander Belopolsky31227ca2012-06-22 13:23:21 -0400810 " representing a whole number of minutes,"
811 " not %R.", offset);
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000812 return NULL;
813 }
814 if ((GET_TD_DAYS(offset) == -1 && GET_TD_SECONDS(offset) == 0) ||
815 GET_TD_DAYS(offset) < -1 || GET_TD_DAYS(offset) >= 1) {
816 PyErr_Format(PyExc_ValueError, "offset must be a timedelta"
817 " strictly between -timedelta(hours=24) and"
Alexander Belopolsky31227ca2012-06-22 13:23:21 -0400818 " timedelta(hours=24),"
819 " not %R.", offset);
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000820 return NULL;
821 }
822
Alexander Belopolsky1bcbaab2010-10-14 17:03:51 +0000823 return create_timezone(offset, name);
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000824}
825
Tim Petersb0c854d2003-05-17 15:57:00 +0000826/* ---------------------------------------------------------------------------
Tim Peters2a799bf2002-12-16 20:18:38 +0000827 * tzinfo helpers.
828 */
829
Tim Peters855fe882002-12-22 03:43:39 +0000830/* Ensure that p is None or of a tzinfo subclass. Return 0 if OK; if not
831 * raise TypeError and return -1.
832 */
833static int
834check_tzinfo_subclass(PyObject *p)
835{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000836 if (p == Py_None || PyTZInfo_Check(p))
837 return 0;
838 PyErr_Format(PyExc_TypeError,
839 "tzinfo argument must be None or of a tzinfo subclass, "
840 "not type '%s'",
841 Py_TYPE(p)->tp_name);
842 return -1;
Tim Peters855fe882002-12-22 03:43:39 +0000843}
844
Tim Peters2a799bf2002-12-16 20:18:38 +0000845/* If self has a tzinfo member, return a BORROWED reference to it. Else
846 * return NULL, which is NOT AN ERROR. There are no error returns here,
847 * and the caller must not decref the result.
848 */
849static PyObject *
850get_tzinfo_member(PyObject *self)
851{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000852 PyObject *tzinfo = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +0000853
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000854 if (PyDateTime_Check(self) && HASTZINFO(self))
855 tzinfo = ((PyDateTime_DateTime *)self)->tzinfo;
856 else if (PyTime_Check(self) && HASTZINFO(self))
857 tzinfo = ((PyDateTime_Time *)self)->tzinfo;
Tim Peters2a799bf2002-12-16 20:18:38 +0000858
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000859 return tzinfo;
Tim Peters2a799bf2002-12-16 20:18:38 +0000860}
861
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000862/* Call getattr(tzinfo, name)(tzinfoarg), and check the result. tzinfo must
863 * be an instance of the tzinfo class. If the method returns None, this
864 * returns None. If the method doesn't return None or timedelta, TypeError is
865 * raised and this returns NULL. If it returns a timedelta and the value is
866 * out of range or isn't a whole number of minutes, ValueError is raised and
867 * this returns NULL. Else result is returned.
Tim Peters2a799bf2002-12-16 20:18:38 +0000868 */
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000869static PyObject *
870call_tzinfo_method(PyObject *tzinfo, char *name, PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +0000871{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000872 PyObject *offset;
Tim Peters2a799bf2002-12-16 20:18:38 +0000873
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000874 assert(tzinfo != NULL);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000875 assert(PyTZInfo_Check(tzinfo) || tzinfo == Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000876 assert(tzinfoarg != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +0000877
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000878 if (tzinfo == Py_None)
879 Py_RETURN_NONE;
880 offset = PyObject_CallMethod(tzinfo, name, "O", tzinfoarg);
881 if (offset == Py_None || offset == NULL)
882 return offset;
883 if (PyDelta_Check(offset)) {
884 if (GET_TD_MICROSECONDS(offset) != 0 || GET_TD_SECONDS(offset) % 60 != 0) {
885 Py_DECREF(offset);
886 PyErr_Format(PyExc_ValueError, "offset must be a timedelta"
887 " representing a whole number of minutes");
888 return NULL;
889 }
890 if ((GET_TD_DAYS(offset) == -1 && GET_TD_SECONDS(offset) == 0) ||
891 GET_TD_DAYS(offset) < -1 || GET_TD_DAYS(offset) >= 1) {
892 Py_DECREF(offset);
893 PyErr_Format(PyExc_ValueError, "offset must be a timedelta"
894 " strictly between -timedelta(hours=24) and"
895 " timedelta(hours=24).");
896 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000897 }
898 }
899 else {
900 PyErr_Format(PyExc_TypeError,
901 "tzinfo.%s() must return None or "
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000902 "timedelta, not '%.200s'",
903 name, Py_TYPE(offset)->tp_name);
Raymond Hettinger5a2146a2014-07-25 14:59:48 -0700904 Py_DECREF(offset);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000905 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000906 }
Tim Peters2a799bf2002-12-16 20:18:38 +0000907
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000908 return offset;
Tim Peters2a799bf2002-12-16 20:18:38 +0000909}
910
911/* Call tzinfo.utcoffset(tzinfoarg), and extract an integer from the
912 * result. tzinfo must be an instance of the tzinfo class. If utcoffset()
913 * returns None, call_utcoffset returns 0 and sets *none to 1. If uctoffset()
Tim Peters397301e2003-01-02 21:28:08 +0000914 * doesn't return None or timedelta, TypeError is raised and this returns -1.
915 * If utcoffset() returns an invalid timedelta (out of range, or not a whole
916 * # of minutes), ValueError is raised and this returns -1. Else *none is
917 * set to 0 and the offset is returned (as int # of minutes east of UTC).
Tim Peters2a799bf2002-12-16 20:18:38 +0000918 */
Tim Peters855fe882002-12-22 03:43:39 +0000919static PyObject *
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000920call_utcoffset(PyObject *tzinfo, PyObject *tzinfoarg)
921{
922 return call_tzinfo_method(tzinfo, "utcoffset", tzinfoarg);
Tim Peters855fe882002-12-22 03:43:39 +0000923}
924
Tim Peters2a799bf2002-12-16 20:18:38 +0000925/* Call tzinfo.dst(tzinfoarg), and extract an integer from the
926 * result. tzinfo must be an instance of the tzinfo class. If dst()
927 * returns None, call_dst returns 0 and sets *none to 1. If dst()
Tim Peters397301e2003-01-02 21:28:08 +0000928 & doesn't return None or timedelta, TypeError is raised and this
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000929 * returns -1. If dst() returns an invalid timedelta for a UTC offset,
Tim Peters397301e2003-01-02 21:28:08 +0000930 * ValueError is raised and this returns -1. Else *none is set to 0 and
931 * the offset is returned (as an int # of minutes east of UTC).
Tim Peters2a799bf2002-12-16 20:18:38 +0000932 */
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000933static PyObject *
934call_dst(PyObject *tzinfo, PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +0000935{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000936 return call_tzinfo_method(tzinfo, "dst", tzinfoarg);
Tim Peters2a799bf2002-12-16 20:18:38 +0000937}
938
Tim Petersbad8ff02002-12-30 20:52:32 +0000939/* Call tzinfo.tzname(tzinfoarg), and return the result. tzinfo must be
Tim Peters855fe882002-12-22 03:43:39 +0000940 * an instance of the tzinfo class or None. If tzinfo isn't None, and
Tim Petersbad8ff02002-12-30 20:52:32 +0000941 * tzname() doesn't return None or a string, TypeError is raised and this
Guido van Rossume3d1d412007-05-23 21:24:35 +0000942 * returns NULL. If the result is a string, we ensure it is a Unicode
943 * string.
Tim Peters2a799bf2002-12-16 20:18:38 +0000944 */
945static PyObject *
Tim Petersbad8ff02002-12-30 20:52:32 +0000946call_tzname(PyObject *tzinfo, PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +0000947{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000948 PyObject *result;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200949 _Py_IDENTIFIER(tzname);
Tim Peters2a799bf2002-12-16 20:18:38 +0000950
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000951 assert(tzinfo != NULL);
952 assert(check_tzinfo_subclass(tzinfo) >= 0);
953 assert(tzinfoarg != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +0000954
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000955 if (tzinfo == Py_None)
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000956 Py_RETURN_NONE;
Tim Peters2a799bf2002-12-16 20:18:38 +0000957
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200958 result = _PyObject_CallMethodId(tzinfo, &PyId_tzname, "O", tzinfoarg);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000959
960 if (result == NULL || result == Py_None)
961 return result;
962
963 if (!PyUnicode_Check(result)) {
964 PyErr_Format(PyExc_TypeError, "tzinfo.tzname() must "
965 "return None or a string, not '%s'",
966 Py_TYPE(result)->tp_name);
967 Py_DECREF(result);
968 result = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000969 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000970
971 return result;
Tim Peters00237032002-12-27 02:21:51 +0000972}
973
Tim Peters2a799bf2002-12-16 20:18:38 +0000974/* repr is like "someclass(arg1, arg2)". If tzinfo isn't None,
975 * stuff
976 * ", tzinfo=" + repr(tzinfo)
977 * before the closing ")".
978 */
979static PyObject *
980append_keyword_tzinfo(PyObject *repr, PyObject *tzinfo)
981{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000982 PyObject *temp;
Tim Peters2a799bf2002-12-16 20:18:38 +0000983
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000984 assert(PyUnicode_Check(repr));
985 assert(tzinfo);
986 if (tzinfo == Py_None)
987 return repr;
988 /* Get rid of the trailing ')'. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200989 assert(PyUnicode_READ_CHAR(repr, PyUnicode_GET_LENGTH(repr)-1) == ')');
990 temp = PyUnicode_Substring(repr, 0, PyUnicode_GET_LENGTH(repr) - 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000991 Py_DECREF(repr);
992 if (temp == NULL)
993 return NULL;
994 repr = PyUnicode_FromFormat("%U, tzinfo=%R)", temp, tzinfo);
995 Py_DECREF(temp);
996 return repr;
Tim Peters2a799bf2002-12-16 20:18:38 +0000997}
998
999/* ---------------------------------------------------------------------------
1000 * String format helpers.
1001 */
1002
1003static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00001004format_ctime(PyDateTime_Date *date, int hours, int minutes, int seconds)
Tim Peters2a799bf2002-12-16 20:18:38 +00001005{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001006 static const char *DayNames[] = {
1007 "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"
1008 };
1009 static const char *MonthNames[] = {
1010 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
1011 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
1012 };
Tim Peters2a799bf2002-12-16 20:18:38 +00001013
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001014 int wday = weekday(GET_YEAR(date), GET_MONTH(date), GET_DAY(date));
Tim Peters2a799bf2002-12-16 20:18:38 +00001015
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001016 return PyUnicode_FromFormat("%s %s %2d %02d:%02d:%02d %04d",
1017 DayNames[wday], MonthNames[GET_MONTH(date)-1],
1018 GET_DAY(date), hours, minutes, seconds,
1019 GET_YEAR(date));
Tim Peters2a799bf2002-12-16 20:18:38 +00001020}
1021
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001022static PyObject *delta_negative(PyDateTime_Delta *self);
1023
Tim Peters2a799bf2002-12-16 20:18:38 +00001024/* Add an hours & minutes UTC offset string to buf. buf has no more than
1025 * buflen bytes remaining. The UTC offset is gotten by calling
1026 * tzinfo.uctoffset(tzinfoarg). If that returns None, \0 is stored into
1027 * *buf, and that's all. Else the returned value is checked for sanity (an
1028 * integer in range), and if that's OK it's converted to an hours & minutes
1029 * string of the form
1030 * sign HH sep MM
1031 * Returns 0 if everything is OK. If the return value from utcoffset() is
1032 * bogus, an appropriate exception is set and -1 is returned.
1033 */
1034static int
Tim Peters328fff72002-12-20 01:31:27 +00001035format_utcoffset(char *buf, size_t buflen, const char *sep,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001036 PyObject *tzinfo, PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +00001037{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001038 PyObject *offset;
1039 int hours, minutes, seconds;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001040 char sign;
Tim Peters2a799bf2002-12-16 20:18:38 +00001041
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001042 assert(buflen >= 1);
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00001043
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001044 offset = call_utcoffset(tzinfo, tzinfoarg);
1045 if (offset == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001046 return -1;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001047 if (offset == Py_None) {
1048 Py_DECREF(offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001049 *buf = '\0';
1050 return 0;
1051 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001052 /* Offset is normalized, so it is negative if days < 0 */
1053 if (GET_TD_DAYS(offset) < 0) {
1054 PyObject *temp = offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001055 sign = '-';
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001056 offset = delta_negative((PyDateTime_Delta *)offset);
1057 Py_DECREF(temp);
1058 if (offset == NULL)
1059 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001060 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001061 else {
1062 sign = '+';
1063 }
1064 /* Offset is not negative here. */
1065 seconds = GET_TD_SECONDS(offset);
1066 Py_DECREF(offset);
1067 minutes = divmod(seconds, 60, &seconds);
1068 hours = divmod(minutes, 60, &minutes);
1069 assert(seconds == 0);
1070 /* XXX ignore sub-minute data, curently not allowed. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001071 PyOS_snprintf(buf, buflen, "%c%02d%s%02d", sign, hours, sep, minutes);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001072
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001073 return 0;
Tim Peters2a799bf2002-12-16 20:18:38 +00001074}
1075
Guido van Rossumd8595fe2007-05-23 21:36:49 +00001076static PyObject *
1077make_Zreplacement(PyObject *object, PyObject *tzinfoarg)
1078{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001079 PyObject *temp;
1080 PyObject *tzinfo = get_tzinfo_member(object);
1081 PyObject *Zreplacement = PyUnicode_FromStringAndSize(NULL, 0);
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001082 _Py_IDENTIFIER(replace);
Victor Stinner9e30aa52011-11-21 02:49:52 +01001083
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001084 if (Zreplacement == NULL)
1085 return NULL;
1086 if (tzinfo == Py_None || tzinfo == NULL)
1087 return Zreplacement;
Neal Norwitzaea70e02007-08-12 04:32:26 +00001088
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001089 assert(tzinfoarg != NULL);
1090 temp = call_tzname(tzinfo, tzinfoarg);
1091 if (temp == NULL)
1092 goto Error;
1093 if (temp == Py_None) {
1094 Py_DECREF(temp);
1095 return Zreplacement;
1096 }
Neal Norwitzaea70e02007-08-12 04:32:26 +00001097
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001098 assert(PyUnicode_Check(temp));
1099 /* Since the tzname is getting stuffed into the
1100 * format, we have to double any % signs so that
1101 * strftime doesn't treat them as format codes.
1102 */
1103 Py_DECREF(Zreplacement);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001104 Zreplacement = _PyObject_CallMethodId(temp, &PyId_replace, "ss", "%", "%%");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001105 Py_DECREF(temp);
1106 if (Zreplacement == NULL)
1107 return NULL;
1108 if (!PyUnicode_Check(Zreplacement)) {
1109 PyErr_SetString(PyExc_TypeError,
1110 "tzname.replace() did not return a string");
1111 goto Error;
1112 }
1113 return Zreplacement;
Guido van Rossumd8595fe2007-05-23 21:36:49 +00001114
1115 Error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001116 Py_DECREF(Zreplacement);
1117 return NULL;
Guido van Rossumd8595fe2007-05-23 21:36:49 +00001118}
1119
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001120static PyObject *
1121make_freplacement(PyObject *object)
1122{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001123 char freplacement[64];
1124 if (PyTime_Check(object))
1125 sprintf(freplacement, "%06d", TIME_GET_MICROSECOND(object));
1126 else if (PyDateTime_Check(object))
1127 sprintf(freplacement, "%06d", DATE_GET_MICROSECOND(object));
1128 else
1129 sprintf(freplacement, "%06d", 0);
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001130
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001131 return PyBytes_FromStringAndSize(freplacement, strlen(freplacement));
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001132}
1133
Tim Peters2a799bf2002-12-16 20:18:38 +00001134/* I sure don't want to reproduce the strftime code from the time module,
1135 * so this imports the module and calls it. All the hair is due to
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001136 * giving special meanings to the %z, %Z and %f format codes via a
1137 * preprocessing step on the format string.
Tim Petersbad8ff02002-12-30 20:52:32 +00001138 * tzinfoarg is the argument to pass to the object's tzinfo method, if
1139 * needed.
Tim Peters2a799bf2002-12-16 20:18:38 +00001140 */
1141static PyObject *
Tim Petersbad8ff02002-12-30 20:52:32 +00001142wrap_strftime(PyObject *object, PyObject *format, PyObject *timetuple,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001143 PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +00001144{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001145 PyObject *result = NULL; /* guilty until proved innocent */
Tim Peters2a799bf2002-12-16 20:18:38 +00001146
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001147 PyObject *zreplacement = NULL; /* py string, replacement for %z */
1148 PyObject *Zreplacement = NULL; /* py string, replacement for %Z */
1149 PyObject *freplacement = NULL; /* py string, replacement for %f */
Tim Peters2a799bf2002-12-16 20:18:38 +00001150
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001151 const char *pin; /* pointer to next char in input format */
1152 Py_ssize_t flen; /* length of input format */
1153 char ch; /* next char in input format */
Tim Peters2a799bf2002-12-16 20:18:38 +00001154
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001155 PyObject *newfmt = NULL; /* py string, the output format */
1156 char *pnew; /* pointer to available byte in output format */
1157 size_t totalnew; /* number bytes total in output format buffer,
1158 exclusive of trailing \0 */
1159 size_t usednew; /* number bytes used so far in output format buffer */
Tim Peters2a799bf2002-12-16 20:18:38 +00001160
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001161 const char *ptoappend; /* ptr to string to append to output buffer */
1162 Py_ssize_t ntoappend; /* # of bytes to append to output buffer */
Tim Peters2a799bf2002-12-16 20:18:38 +00001163
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001164 assert(object && format && timetuple);
1165 assert(PyUnicode_Check(format));
1166 /* Convert the input format to a C string and size */
1167 pin = _PyUnicode_AsStringAndSize(format, &flen);
1168 if (!pin)
1169 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001170
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001171 /* Scan the input format, looking for %z/%Z/%f escapes, building
1172 * a new format. Since computing the replacements for those codes
1173 * is expensive, don't unless they're actually used.
1174 */
1175 if (flen > INT_MAX - 1) {
1176 PyErr_NoMemory();
1177 goto Done;
1178 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00001179
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001180 totalnew = flen + 1; /* realistic if no %z/%Z */
1181 newfmt = PyBytes_FromStringAndSize(NULL, totalnew);
1182 if (newfmt == NULL) goto Done;
1183 pnew = PyBytes_AsString(newfmt);
1184 usednew = 0;
Tim Peters2a799bf2002-12-16 20:18:38 +00001185
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001186 while ((ch = *pin++) != '\0') {
1187 if (ch != '%') {
1188 ptoappend = pin - 1;
1189 ntoappend = 1;
1190 }
1191 else if ((ch = *pin++) == '\0') {
1192 /* There's a lone trailing %; doesn't make sense. */
1193 PyErr_SetString(PyExc_ValueError, "strftime format "
1194 "ends with raw %");
1195 goto Done;
1196 }
1197 /* A % has been seen and ch is the character after it. */
1198 else if (ch == 'z') {
1199 if (zreplacement == NULL) {
1200 /* format utcoffset */
1201 char buf[100];
1202 PyObject *tzinfo = get_tzinfo_member(object);
1203 zreplacement = PyBytes_FromStringAndSize("", 0);
1204 if (zreplacement == NULL) goto Done;
1205 if (tzinfo != Py_None && tzinfo != NULL) {
1206 assert(tzinfoarg != NULL);
1207 if (format_utcoffset(buf,
1208 sizeof(buf),
1209 "",
1210 tzinfo,
1211 tzinfoarg) < 0)
1212 goto Done;
1213 Py_DECREF(zreplacement);
1214 zreplacement =
1215 PyBytes_FromStringAndSize(buf,
1216 strlen(buf));
1217 if (zreplacement == NULL)
1218 goto Done;
1219 }
1220 }
1221 assert(zreplacement != NULL);
1222 ptoappend = PyBytes_AS_STRING(zreplacement);
1223 ntoappend = PyBytes_GET_SIZE(zreplacement);
1224 }
1225 else if (ch == 'Z') {
1226 /* format tzname */
1227 if (Zreplacement == NULL) {
1228 Zreplacement = make_Zreplacement(object,
1229 tzinfoarg);
1230 if (Zreplacement == NULL)
1231 goto Done;
1232 }
1233 assert(Zreplacement != NULL);
1234 assert(PyUnicode_Check(Zreplacement));
1235 ptoappend = _PyUnicode_AsStringAndSize(Zreplacement,
1236 &ntoappend);
Alexander Belopolskye239d232010-12-08 23:31:48 +00001237 if (ptoappend == NULL)
1238 goto Done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001239 }
1240 else if (ch == 'f') {
1241 /* format microseconds */
1242 if (freplacement == NULL) {
1243 freplacement = make_freplacement(object);
1244 if (freplacement == NULL)
1245 goto Done;
1246 }
1247 assert(freplacement != NULL);
1248 assert(PyBytes_Check(freplacement));
1249 ptoappend = PyBytes_AS_STRING(freplacement);
1250 ntoappend = PyBytes_GET_SIZE(freplacement);
1251 }
1252 else {
1253 /* percent followed by neither z nor Z */
1254 ptoappend = pin - 2;
1255 ntoappend = 2;
1256 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001257
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001258 /* Append the ntoappend chars starting at ptoappend to
1259 * the new format.
1260 */
1261 if (ntoappend == 0)
1262 continue;
1263 assert(ptoappend != NULL);
1264 assert(ntoappend > 0);
1265 while (usednew + ntoappend > totalnew) {
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01001266 if (totalnew > (PY_SSIZE_T_MAX >> 1)) { /* overflow */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001267 PyErr_NoMemory();
1268 goto Done;
1269 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01001270 totalnew <<= 1;
1271 if (_PyBytes_Resize(&newfmt, totalnew) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001272 goto Done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001273 pnew = PyBytes_AsString(newfmt) + usednew;
1274 }
1275 memcpy(pnew, ptoappend, ntoappend);
1276 pnew += ntoappend;
1277 usednew += ntoappend;
1278 assert(usednew <= totalnew);
1279 } /* end while() */
Tim Peters2a799bf2002-12-16 20:18:38 +00001280
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001281 if (_PyBytes_Resize(&newfmt, usednew) < 0)
1282 goto Done;
1283 {
1284 PyObject *format;
1285 PyObject *time = PyImport_ImportModuleNoBlock("time");
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001287 if (time == NULL)
1288 goto Done;
1289 format = PyUnicode_FromString(PyBytes_AS_STRING(newfmt));
1290 if (format != NULL) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001291 result = _PyObject_CallMethodId(time, &PyId_strftime, "OO",
1292 format, timetuple, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001293 Py_DECREF(format);
1294 }
1295 Py_DECREF(time);
1296 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001297 Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001298 Py_XDECREF(freplacement);
1299 Py_XDECREF(zreplacement);
1300 Py_XDECREF(Zreplacement);
1301 Py_XDECREF(newfmt);
1302 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001303}
1304
Tim Peters2a799bf2002-12-16 20:18:38 +00001305/* ---------------------------------------------------------------------------
1306 * Wrap functions from the time module. These aren't directly available
1307 * from C. Perhaps they should be.
1308 */
1309
1310/* Call time.time() and return its result (a Python float). */
1311static PyObject *
Guido van Rossumbd43e912002-12-16 20:34:55 +00001312time_time(void)
Tim Peters2a799bf2002-12-16 20:18:38 +00001313{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001314 PyObject *result = NULL;
1315 PyObject *time = PyImport_ImportModuleNoBlock("time");
Tim Peters2a799bf2002-12-16 20:18:38 +00001316
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001317 if (time != NULL) {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001318 _Py_IDENTIFIER(time);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001319
1320 result = _PyObject_CallMethodId(time, &PyId_time, "()");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001321 Py_DECREF(time);
1322 }
1323 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001324}
1325
1326/* Build a time.struct_time. The weekday and day number are automatically
1327 * computed from the y,m,d args.
1328 */
1329static PyObject *
1330build_struct_time(int y, int m, int d, int hh, int mm, int ss, int dstflag)
1331{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001332 PyObject *time;
1333 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001334
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001335 time = PyImport_ImportModuleNoBlock("time");
1336 if (time != NULL) {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001337 _Py_IDENTIFIER(struct_time);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001338
1339 result = _PyObject_CallMethodId(time, &PyId_struct_time,
1340 "((iiiiiiiii))",
1341 y, m, d,
1342 hh, mm, ss,
1343 weekday(y, m, d),
1344 days_before_month(y, m) + d,
1345 dstflag);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001346 Py_DECREF(time);
1347 }
1348 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001349}
1350
1351/* ---------------------------------------------------------------------------
1352 * Miscellaneous helpers.
1353 */
1354
Mark Dickinsone94c6792009-02-02 20:36:42 +00001355/* For various reasons, we need to use tp_richcompare instead of tp_reserved.
Tim Peters2a799bf2002-12-16 20:18:38 +00001356 * The comparisons here all most naturally compute a cmp()-like result.
1357 * This little helper turns that into a bool result for rich comparisons.
1358 */
1359static PyObject *
1360diff_to_bool(int diff, int op)
1361{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001362 PyObject *result;
1363 int istrue;
Tim Peters2a799bf2002-12-16 20:18:38 +00001364
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001365 switch (op) {
1366 case Py_EQ: istrue = diff == 0; break;
1367 case Py_NE: istrue = diff != 0; break;
1368 case Py_LE: istrue = diff <= 0; break;
1369 case Py_GE: istrue = diff >= 0; break;
1370 case Py_LT: istrue = diff < 0; break;
1371 case Py_GT: istrue = diff > 0; break;
1372 default:
1373 assert(! "op unknown");
1374 istrue = 0; /* To shut up compiler */
1375 }
1376 result = istrue ? Py_True : Py_False;
1377 Py_INCREF(result);
1378 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001379}
1380
Tim Peters07534a62003-02-07 22:50:28 +00001381/* Raises a "can't compare" TypeError and returns NULL. */
1382static PyObject *
1383cmperror(PyObject *a, PyObject *b)
1384{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001385 PyErr_Format(PyExc_TypeError,
1386 "can't compare %s to %s",
1387 Py_TYPE(a)->tp_name, Py_TYPE(b)->tp_name);
1388 return NULL;
Tim Peters07534a62003-02-07 22:50:28 +00001389}
1390
Tim Peters2a799bf2002-12-16 20:18:38 +00001391/* ---------------------------------------------------------------------------
Tim Peters2a799bf2002-12-16 20:18:38 +00001392 * Cached Python objects; these are set by the module init function.
1393 */
1394
1395/* Conversion factors. */
Alexander Belopolsky790d2692013-08-04 14:51:35 -04001396static PyObject *one = NULL; /* 1 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001397static PyObject *us_per_ms = NULL; /* 1000 */
1398static PyObject *us_per_second = NULL; /* 1000000 */
1399static PyObject *us_per_minute = NULL; /* 1e6 * 60 as Python int */
Serhiy Storchaka95949422013-08-27 19:40:23 +03001400static PyObject *us_per_hour = NULL; /* 1e6 * 3600 as Python int */
1401static PyObject *us_per_day = NULL; /* 1e6 * 3600 * 24 as Python int */
1402static PyObject *us_per_week = NULL; /* 1e6*3600*24*7 as Python int */
Tim Peters2a799bf2002-12-16 20:18:38 +00001403static PyObject *seconds_per_day = NULL; /* 3600*24 as Python int */
1404
Tim Peters2a799bf2002-12-16 20:18:38 +00001405/* ---------------------------------------------------------------------------
1406 * Class implementations.
1407 */
1408
1409/*
1410 * PyDateTime_Delta implementation.
1411 */
1412
1413/* Convert a timedelta to a number of us,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001414 * (24*3600*self.days + self.seconds)*1000000 + self.microseconds
Serhiy Storchaka95949422013-08-27 19:40:23 +03001415 * as a Python int.
Tim Peters2a799bf2002-12-16 20:18:38 +00001416 * Doing mixed-radix arithmetic by hand instead is excruciating in C,
1417 * due to ubiquitous overflow possibilities.
1418 */
1419static PyObject *
1420delta_to_microseconds(PyDateTime_Delta *self)
1421{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001422 PyObject *x1 = NULL;
1423 PyObject *x2 = NULL;
1424 PyObject *x3 = NULL;
1425 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001426
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001427 x1 = PyLong_FromLong(GET_TD_DAYS(self));
1428 if (x1 == NULL)
1429 goto Done;
1430 x2 = PyNumber_Multiply(x1, seconds_per_day); /* days in seconds */
1431 if (x2 == NULL)
1432 goto Done;
1433 Py_DECREF(x1);
1434 x1 = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001435
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001436 /* x2 has days in seconds */
1437 x1 = PyLong_FromLong(GET_TD_SECONDS(self)); /* seconds */
1438 if (x1 == NULL)
1439 goto Done;
1440 x3 = PyNumber_Add(x1, x2); /* days and seconds in seconds */
1441 if (x3 == NULL)
1442 goto Done;
1443 Py_DECREF(x1);
1444 Py_DECREF(x2);
Brett Cannonb94767f2011-02-22 20:15:44 +00001445 /* x1 = */ x2 = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001446
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001447 /* x3 has days+seconds in seconds */
1448 x1 = PyNumber_Multiply(x3, us_per_second); /* us */
1449 if (x1 == NULL)
1450 goto Done;
1451 Py_DECREF(x3);
1452 x3 = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001453
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001454 /* x1 has days+seconds in us */
1455 x2 = PyLong_FromLong(GET_TD_MICROSECONDS(self));
1456 if (x2 == NULL)
1457 goto Done;
1458 result = PyNumber_Add(x1, x2);
Tim Peters2a799bf2002-12-16 20:18:38 +00001459
1460Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001461 Py_XDECREF(x1);
1462 Py_XDECREF(x2);
1463 Py_XDECREF(x3);
1464 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001465}
1466
Serhiy Storchaka95949422013-08-27 19:40:23 +03001467/* Convert a number of us (as a Python int) to a timedelta.
Tim Peters2a799bf2002-12-16 20:18:38 +00001468 */
1469static PyObject *
Tim Petersb0c854d2003-05-17 15:57:00 +00001470microseconds_to_delta_ex(PyObject *pyus, PyTypeObject *type)
Tim Peters2a799bf2002-12-16 20:18:38 +00001471{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001472 int us;
1473 int s;
1474 int d;
1475 long temp;
Tim Peters2a799bf2002-12-16 20:18:38 +00001476
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001477 PyObject *tuple = NULL;
1478 PyObject *num = NULL;
1479 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001480
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001481 tuple = PyNumber_Divmod(pyus, us_per_second);
1482 if (tuple == NULL)
1483 goto Done;
Tim Peters2a799bf2002-12-16 20:18:38 +00001484
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001485 num = PyTuple_GetItem(tuple, 1); /* us */
1486 if (num == NULL)
1487 goto Done;
1488 temp = PyLong_AsLong(num);
1489 num = NULL;
1490 if (temp == -1 && PyErr_Occurred())
1491 goto Done;
1492 assert(0 <= temp && temp < 1000000);
1493 us = (int)temp;
1494 if (us < 0) {
1495 /* The divisor was positive, so this must be an error. */
1496 assert(PyErr_Occurred());
1497 goto Done;
1498 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001499
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001500 num = PyTuple_GetItem(tuple, 0); /* leftover seconds */
1501 if (num == NULL)
1502 goto Done;
1503 Py_INCREF(num);
1504 Py_DECREF(tuple);
Tim Peters2a799bf2002-12-16 20:18:38 +00001505
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001506 tuple = PyNumber_Divmod(num, seconds_per_day);
1507 if (tuple == NULL)
1508 goto Done;
1509 Py_DECREF(num);
Tim Peters2a799bf2002-12-16 20:18:38 +00001510
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001511 num = PyTuple_GetItem(tuple, 1); /* seconds */
1512 if (num == NULL)
1513 goto Done;
1514 temp = PyLong_AsLong(num);
1515 num = NULL;
1516 if (temp == -1 && PyErr_Occurred())
1517 goto Done;
1518 assert(0 <= temp && temp < 24*3600);
1519 s = (int)temp;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001520
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001521 if (s < 0) {
1522 /* The divisor was positive, so this must be an error. */
1523 assert(PyErr_Occurred());
1524 goto Done;
1525 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001526
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001527 num = PyTuple_GetItem(tuple, 0); /* leftover days */
1528 if (num == NULL)
1529 goto Done;
1530 Py_INCREF(num);
1531 temp = PyLong_AsLong(num);
1532 if (temp == -1 && PyErr_Occurred())
1533 goto Done;
1534 d = (int)temp;
1535 if ((long)d != temp) {
1536 PyErr_SetString(PyExc_OverflowError, "normalized days too "
1537 "large to fit in a C int");
1538 goto Done;
1539 }
1540 result = new_delta_ex(d, s, us, 0, type);
Tim Peters2a799bf2002-12-16 20:18:38 +00001541
1542Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001543 Py_XDECREF(tuple);
1544 Py_XDECREF(num);
1545 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001546}
1547
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001548#define microseconds_to_delta(pymicros) \
1549 microseconds_to_delta_ex(pymicros, &PyDateTime_DeltaType)
Tim Petersb0c854d2003-05-17 15:57:00 +00001550
Tim Peters2a799bf2002-12-16 20:18:38 +00001551static PyObject *
1552multiply_int_timedelta(PyObject *intobj, PyDateTime_Delta *delta)
1553{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001554 PyObject *pyus_in;
1555 PyObject *pyus_out;
1556 PyObject *result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001557
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001558 pyus_in = delta_to_microseconds(delta);
1559 if (pyus_in == NULL)
1560 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001562 pyus_out = PyNumber_Multiply(pyus_in, intobj);
1563 Py_DECREF(pyus_in);
1564 if (pyus_out == NULL)
1565 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001566
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001567 result = microseconds_to_delta(pyus_out);
1568 Py_DECREF(pyus_out);
1569 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001570}
1571
1572static PyObject *
Alexander Belopolsky1790bc42010-05-31 17:33:47 +00001573multiply_float_timedelta(PyObject *floatobj, PyDateTime_Delta *delta)
1574{
1575 PyObject *result = NULL;
1576 PyObject *pyus_in = NULL, *temp, *pyus_out;
1577 PyObject *ratio = NULL;
1578
1579 pyus_in = delta_to_microseconds(delta);
1580 if (pyus_in == NULL)
1581 return NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001582 ratio = _PyObject_CallMethodId(floatobj, &PyId_as_integer_ratio, NULL);
Alexander Belopolsky1790bc42010-05-31 17:33:47 +00001583 if (ratio == NULL)
1584 goto error;
1585 temp = PyNumber_Multiply(pyus_in, PyTuple_GET_ITEM(ratio, 0));
1586 Py_DECREF(pyus_in);
1587 pyus_in = NULL;
1588 if (temp == NULL)
1589 goto error;
1590 pyus_out = divide_nearest(temp, PyTuple_GET_ITEM(ratio, 1));
1591 Py_DECREF(temp);
1592 if (pyus_out == NULL)
1593 goto error;
1594 result = microseconds_to_delta(pyus_out);
1595 Py_DECREF(pyus_out);
1596 error:
1597 Py_XDECREF(pyus_in);
1598 Py_XDECREF(ratio);
1599
1600 return result;
1601}
1602
1603static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00001604divide_timedelta_int(PyDateTime_Delta *delta, PyObject *intobj)
1605{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001606 PyObject *pyus_in;
1607 PyObject *pyus_out;
1608 PyObject *result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001609
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001610 pyus_in = delta_to_microseconds(delta);
1611 if (pyus_in == NULL)
1612 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001613
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001614 pyus_out = PyNumber_FloorDivide(pyus_in, intobj);
1615 Py_DECREF(pyus_in);
1616 if (pyus_out == NULL)
1617 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001619 result = microseconds_to_delta(pyus_out);
1620 Py_DECREF(pyus_out);
1621 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001622}
1623
1624static PyObject *
Mark Dickinson7c186e22010-04-20 22:32:49 +00001625divide_timedelta_timedelta(PyDateTime_Delta *left, PyDateTime_Delta *right)
1626{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001627 PyObject *pyus_left;
1628 PyObject *pyus_right;
1629 PyObject *result;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001630
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001631 pyus_left = delta_to_microseconds(left);
1632 if (pyus_left == NULL)
1633 return NULL;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001634
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001635 pyus_right = delta_to_microseconds(right);
1636 if (pyus_right == NULL) {
1637 Py_DECREF(pyus_left);
1638 return NULL;
1639 }
Mark Dickinson7c186e22010-04-20 22:32:49 +00001640
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001641 result = PyNumber_FloorDivide(pyus_left, pyus_right);
1642 Py_DECREF(pyus_left);
1643 Py_DECREF(pyus_right);
1644 return result;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001645}
1646
1647static PyObject *
1648truedivide_timedelta_timedelta(PyDateTime_Delta *left, PyDateTime_Delta *right)
1649{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001650 PyObject *pyus_left;
1651 PyObject *pyus_right;
1652 PyObject *result;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001653
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001654 pyus_left = delta_to_microseconds(left);
1655 if (pyus_left == NULL)
1656 return NULL;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001657
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001658 pyus_right = delta_to_microseconds(right);
1659 if (pyus_right == NULL) {
1660 Py_DECREF(pyus_left);
1661 return NULL;
1662 }
Mark Dickinson7c186e22010-04-20 22:32:49 +00001663
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001664 result = PyNumber_TrueDivide(pyus_left, pyus_right);
1665 Py_DECREF(pyus_left);
1666 Py_DECREF(pyus_right);
1667 return result;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001668}
1669
1670static PyObject *
Alexander Belopolsky1790bc42010-05-31 17:33:47 +00001671truedivide_timedelta_float(PyDateTime_Delta *delta, PyObject *f)
1672{
1673 PyObject *result = NULL;
1674 PyObject *pyus_in = NULL, *temp, *pyus_out;
1675 PyObject *ratio = NULL;
1676
1677 pyus_in = delta_to_microseconds(delta);
1678 if (pyus_in == NULL)
1679 return NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001680 ratio = _PyObject_CallMethodId(f, &PyId_as_integer_ratio, NULL);
Alexander Belopolsky1790bc42010-05-31 17:33:47 +00001681 if (ratio == NULL)
1682 goto error;
1683 temp = PyNumber_Multiply(pyus_in, PyTuple_GET_ITEM(ratio, 1));
1684 Py_DECREF(pyus_in);
1685 pyus_in = NULL;
1686 if (temp == NULL)
1687 goto error;
1688 pyus_out = divide_nearest(temp, PyTuple_GET_ITEM(ratio, 0));
1689 Py_DECREF(temp);
1690 if (pyus_out == NULL)
1691 goto error;
1692 result = microseconds_to_delta(pyus_out);
1693 Py_DECREF(pyus_out);
1694 error:
1695 Py_XDECREF(pyus_in);
1696 Py_XDECREF(ratio);
1697
1698 return result;
1699}
1700
1701static PyObject *
1702truedivide_timedelta_int(PyDateTime_Delta *delta, PyObject *i)
1703{
1704 PyObject *result;
1705 PyObject *pyus_in, *pyus_out;
1706 pyus_in = delta_to_microseconds(delta);
1707 if (pyus_in == NULL)
1708 return NULL;
1709 pyus_out = divide_nearest(pyus_in, i);
1710 Py_DECREF(pyus_in);
1711 if (pyus_out == NULL)
1712 return NULL;
1713 result = microseconds_to_delta(pyus_out);
1714 Py_DECREF(pyus_out);
1715
1716 return result;
1717}
1718
1719static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00001720delta_add(PyObject *left, PyObject *right)
1721{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001722 PyObject *result = Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00001723
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001724 if (PyDelta_Check(left) && PyDelta_Check(right)) {
1725 /* delta + delta */
1726 /* The C-level additions can't overflow because of the
1727 * invariant bounds.
1728 */
1729 int days = GET_TD_DAYS(left) + GET_TD_DAYS(right);
1730 int seconds = GET_TD_SECONDS(left) + GET_TD_SECONDS(right);
1731 int microseconds = GET_TD_MICROSECONDS(left) +
1732 GET_TD_MICROSECONDS(right);
1733 result = new_delta(days, seconds, microseconds, 1);
1734 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001735
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001736 if (result == Py_NotImplemented)
1737 Py_INCREF(result);
1738 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001739}
1740
1741static PyObject *
1742delta_negative(PyDateTime_Delta *self)
1743{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001744 return new_delta(-GET_TD_DAYS(self),
1745 -GET_TD_SECONDS(self),
1746 -GET_TD_MICROSECONDS(self),
1747 1);
Tim Peters2a799bf2002-12-16 20:18:38 +00001748}
1749
1750static PyObject *
1751delta_positive(PyDateTime_Delta *self)
1752{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001753 /* Could optimize this (by returning self) if this isn't a
1754 * subclass -- but who uses unary + ? Approximately nobody.
1755 */
1756 return new_delta(GET_TD_DAYS(self),
1757 GET_TD_SECONDS(self),
1758 GET_TD_MICROSECONDS(self),
1759 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00001760}
1761
1762static PyObject *
1763delta_abs(PyDateTime_Delta *self)
1764{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001765 PyObject *result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001766
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001767 assert(GET_TD_MICROSECONDS(self) >= 0);
1768 assert(GET_TD_SECONDS(self) >= 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00001769
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001770 if (GET_TD_DAYS(self) < 0)
1771 result = delta_negative(self);
1772 else
1773 result = delta_positive(self);
Tim Peters2a799bf2002-12-16 20:18:38 +00001774
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001775 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001776}
1777
1778static PyObject *
1779delta_subtract(PyObject *left, PyObject *right)
1780{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001781 PyObject *result = Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00001782
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001783 if (PyDelta_Check(left) && PyDelta_Check(right)) {
1784 /* delta - delta */
Alexander Belopolskyb6f5ec72011-04-05 20:07:38 -04001785 /* The C-level additions can't overflow because of the
1786 * invariant bounds.
1787 */
1788 int days = GET_TD_DAYS(left) - GET_TD_DAYS(right);
1789 int seconds = GET_TD_SECONDS(left) - GET_TD_SECONDS(right);
1790 int microseconds = GET_TD_MICROSECONDS(left) -
1791 GET_TD_MICROSECONDS(right);
1792 result = new_delta(days, seconds, microseconds, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001793 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001794
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001795 if (result == Py_NotImplemented)
1796 Py_INCREF(result);
1797 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001798}
1799
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001800static int
1801delta_cmp(PyObject *self, PyObject *other)
1802{
1803 int diff = GET_TD_DAYS(self) - GET_TD_DAYS(other);
1804 if (diff == 0) {
1805 diff = GET_TD_SECONDS(self) - GET_TD_SECONDS(other);
1806 if (diff == 0)
1807 diff = GET_TD_MICROSECONDS(self) -
1808 GET_TD_MICROSECONDS(other);
1809 }
1810 return diff;
1811}
1812
Tim Peters2a799bf2002-12-16 20:18:38 +00001813static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00001814delta_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters2a799bf2002-12-16 20:18:38 +00001815{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001816 if (PyDelta_Check(other)) {
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001817 int diff = delta_cmp(self, other);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001818 return diff_to_bool(diff, op);
1819 }
1820 else {
Brian Curtindfc80e32011-08-10 20:28:54 -05001821 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001822 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001823}
1824
1825static PyObject *delta_getstate(PyDateTime_Delta *self);
1826
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001827static Py_hash_t
Tim Peters2a799bf2002-12-16 20:18:38 +00001828delta_hash(PyDateTime_Delta *self)
1829{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001830 if (self->hashcode == -1) {
1831 PyObject *temp = delta_getstate(self);
1832 if (temp != NULL) {
1833 self->hashcode = PyObject_Hash(temp);
1834 Py_DECREF(temp);
1835 }
1836 }
1837 return self->hashcode;
Tim Peters2a799bf2002-12-16 20:18:38 +00001838}
1839
1840static PyObject *
1841delta_multiply(PyObject *left, PyObject *right)
1842{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001843 PyObject *result = Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00001844
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001845 if (PyDelta_Check(left)) {
1846 /* delta * ??? */
1847 if (PyLong_Check(right))
1848 result = multiply_int_timedelta(right,
1849 (PyDateTime_Delta *) left);
Alexander Belopolsky1790bc42010-05-31 17:33:47 +00001850 else if (PyFloat_Check(right))
1851 result = multiply_float_timedelta(right,
1852 (PyDateTime_Delta *) left);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001853 }
1854 else if (PyLong_Check(left))
1855 result = multiply_int_timedelta(left,
Alexander Belopolsky1790bc42010-05-31 17:33:47 +00001856 (PyDateTime_Delta *) right);
1857 else if (PyFloat_Check(left))
1858 result = multiply_float_timedelta(left,
1859 (PyDateTime_Delta *) right);
Tim Peters2a799bf2002-12-16 20:18:38 +00001860
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001861 if (result == Py_NotImplemented)
1862 Py_INCREF(result);
1863 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001864}
1865
1866static PyObject *
1867delta_divide(PyObject *left, PyObject *right)
1868{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001869 PyObject *result = Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00001870
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001871 if (PyDelta_Check(left)) {
1872 /* delta * ??? */
1873 if (PyLong_Check(right))
1874 result = divide_timedelta_int(
1875 (PyDateTime_Delta *)left,
1876 right);
1877 else if (PyDelta_Check(right))
1878 result = divide_timedelta_timedelta(
1879 (PyDateTime_Delta *)left,
1880 (PyDateTime_Delta *)right);
1881 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001882
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001883 if (result == Py_NotImplemented)
1884 Py_INCREF(result);
1885 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001886}
1887
Mark Dickinson7c186e22010-04-20 22:32:49 +00001888static PyObject *
1889delta_truedivide(PyObject *left, PyObject *right)
1890{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001891 PyObject *result = Py_NotImplemented;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001892
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001893 if (PyDelta_Check(left)) {
1894 if (PyDelta_Check(right))
1895 result = truedivide_timedelta_timedelta(
1896 (PyDateTime_Delta *)left,
1897 (PyDateTime_Delta *)right);
Alexander Belopolsky1790bc42010-05-31 17:33:47 +00001898 else if (PyFloat_Check(right))
1899 result = truedivide_timedelta_float(
1900 (PyDateTime_Delta *)left, right);
1901 else if (PyLong_Check(right))
1902 result = truedivide_timedelta_int(
1903 (PyDateTime_Delta *)left, right);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001904 }
Mark Dickinson7c186e22010-04-20 22:32:49 +00001905
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001906 if (result == Py_NotImplemented)
1907 Py_INCREF(result);
1908 return result;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001909}
1910
1911static PyObject *
1912delta_remainder(PyObject *left, PyObject *right)
1913{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001914 PyObject *pyus_left;
1915 PyObject *pyus_right;
1916 PyObject *pyus_remainder;
1917 PyObject *remainder;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001918
Brian Curtindfc80e32011-08-10 20:28:54 -05001919 if (!PyDelta_Check(left) || !PyDelta_Check(right))
1920 Py_RETURN_NOTIMPLEMENTED;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001921
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001922 pyus_left = delta_to_microseconds((PyDateTime_Delta *)left);
1923 if (pyus_left == NULL)
1924 return NULL;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001925
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001926 pyus_right = delta_to_microseconds((PyDateTime_Delta *)right);
1927 if (pyus_right == NULL) {
1928 Py_DECREF(pyus_left);
1929 return NULL;
1930 }
Mark Dickinson7c186e22010-04-20 22:32:49 +00001931
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001932 pyus_remainder = PyNumber_Remainder(pyus_left, pyus_right);
1933 Py_DECREF(pyus_left);
1934 Py_DECREF(pyus_right);
1935 if (pyus_remainder == NULL)
1936 return NULL;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001937
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001938 remainder = microseconds_to_delta(pyus_remainder);
1939 Py_DECREF(pyus_remainder);
1940 if (remainder == NULL)
1941 return NULL;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001942
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001943 return remainder;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001944}
1945
1946static PyObject *
1947delta_divmod(PyObject *left, PyObject *right)
1948{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001949 PyObject *pyus_left;
1950 PyObject *pyus_right;
1951 PyObject *divmod;
1952 PyObject *delta;
1953 PyObject *result;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001954
Brian Curtindfc80e32011-08-10 20:28:54 -05001955 if (!PyDelta_Check(left) || !PyDelta_Check(right))
1956 Py_RETURN_NOTIMPLEMENTED;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001957
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001958 pyus_left = delta_to_microseconds((PyDateTime_Delta *)left);
1959 if (pyus_left == NULL)
1960 return NULL;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001961
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001962 pyus_right = delta_to_microseconds((PyDateTime_Delta *)right);
1963 if (pyus_right == NULL) {
1964 Py_DECREF(pyus_left);
1965 return NULL;
1966 }
Mark Dickinson7c186e22010-04-20 22:32:49 +00001967
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001968 divmod = PyNumber_Divmod(pyus_left, pyus_right);
1969 Py_DECREF(pyus_left);
1970 Py_DECREF(pyus_right);
1971 if (divmod == NULL)
1972 return NULL;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001973
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001974 assert(PyTuple_Size(divmod) == 2);
1975 delta = microseconds_to_delta(PyTuple_GET_ITEM(divmod, 1));
1976 if (delta == NULL) {
1977 Py_DECREF(divmod);
1978 return NULL;
1979 }
1980 result = PyTuple_Pack(2, PyTuple_GET_ITEM(divmod, 0), delta);
1981 Py_DECREF(delta);
1982 Py_DECREF(divmod);
1983 return result;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001984}
1985
Tim Peters2a799bf2002-12-16 20:18:38 +00001986/* Fold in the value of the tag ("seconds", "weeks", etc) component of a
1987 * timedelta constructor. sofar is the # of microseconds accounted for
1988 * so far, and there are factor microseconds per current unit, the number
1989 * of which is given by num. num * factor is added to sofar in a
1990 * numerically careful way, and that's the result. Any fractional
1991 * microseconds left over (this can happen if num is a float type) are
1992 * added into *leftover.
1993 * Note that there are many ways this can give an error (NULL) return.
1994 */
1995static PyObject *
1996accum(const char* tag, PyObject *sofar, PyObject *num, PyObject *factor,
1997 double *leftover)
1998{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001999 PyObject *prod;
2000 PyObject *sum;
Tim Peters2a799bf2002-12-16 20:18:38 +00002001
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002002 assert(num != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +00002003
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002004 if (PyLong_Check(num)) {
2005 prod = PyNumber_Multiply(num, factor);
2006 if (prod == NULL)
2007 return NULL;
2008 sum = PyNumber_Add(sofar, prod);
2009 Py_DECREF(prod);
2010 return sum;
2011 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002012
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002013 if (PyFloat_Check(num)) {
2014 double dnum;
2015 double fracpart;
2016 double intpart;
2017 PyObject *x;
2018 PyObject *y;
Tim Peters2a799bf2002-12-16 20:18:38 +00002019
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002020 /* The Plan: decompose num into an integer part and a
2021 * fractional part, num = intpart + fracpart.
2022 * Then num * factor ==
2023 * intpart * factor + fracpart * factor
2024 * and the LHS can be computed exactly in long arithmetic.
2025 * The RHS is again broken into an int part and frac part.
2026 * and the frac part is added into *leftover.
2027 */
2028 dnum = PyFloat_AsDouble(num);
2029 if (dnum == -1.0 && PyErr_Occurred())
2030 return NULL;
2031 fracpart = modf(dnum, &intpart);
2032 x = PyLong_FromDouble(intpart);
2033 if (x == NULL)
2034 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002035
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002036 prod = PyNumber_Multiply(x, factor);
2037 Py_DECREF(x);
2038 if (prod == NULL)
2039 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002040
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002041 sum = PyNumber_Add(sofar, prod);
2042 Py_DECREF(prod);
2043 if (sum == NULL)
2044 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002045
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002046 if (fracpart == 0.0)
2047 return sum;
2048 /* So far we've lost no information. Dealing with the
2049 * fractional part requires float arithmetic, and may
2050 * lose a little info.
2051 */
2052 assert(PyLong_Check(factor));
2053 dnum = PyLong_AsDouble(factor);
Tim Peters2a799bf2002-12-16 20:18:38 +00002054
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002055 dnum *= fracpart;
2056 fracpart = modf(dnum, &intpart);
2057 x = PyLong_FromDouble(intpart);
2058 if (x == NULL) {
2059 Py_DECREF(sum);
2060 return NULL;
2061 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002062
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002063 y = PyNumber_Add(sum, x);
2064 Py_DECREF(sum);
2065 Py_DECREF(x);
2066 *leftover += fracpart;
2067 return y;
2068 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002069
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002070 PyErr_Format(PyExc_TypeError,
2071 "unsupported type for timedelta %s component: %s",
2072 tag, Py_TYPE(num)->tp_name);
2073 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002074}
2075
2076static PyObject *
2077delta_new(PyTypeObject *type, PyObject *args, PyObject *kw)
2078{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002079 PyObject *self = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002080
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002081 /* Argument objects. */
2082 PyObject *day = NULL;
2083 PyObject *second = NULL;
2084 PyObject *us = NULL;
2085 PyObject *ms = NULL;
2086 PyObject *minute = NULL;
2087 PyObject *hour = NULL;
2088 PyObject *week = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002089
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002090 PyObject *x = NULL; /* running sum of microseconds */
2091 PyObject *y = NULL; /* temp sum of microseconds */
2092 double leftover_us = 0.0;
Tim Peters2a799bf2002-12-16 20:18:38 +00002093
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002094 static char *keywords[] = {
2095 "days", "seconds", "microseconds", "milliseconds",
2096 "minutes", "hours", "weeks", NULL
2097 };
Tim Peters2a799bf2002-12-16 20:18:38 +00002098
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002099 if (PyArg_ParseTupleAndKeywords(args, kw, "|OOOOOOO:__new__",
2100 keywords,
2101 &day, &second, &us,
2102 &ms, &minute, &hour, &week) == 0)
2103 goto Done;
Tim Peters2a799bf2002-12-16 20:18:38 +00002104
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002105 x = PyLong_FromLong(0);
2106 if (x == NULL)
2107 goto Done;
Tim Peters2a799bf2002-12-16 20:18:38 +00002108
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002109#define CLEANUP \
2110 Py_DECREF(x); \
2111 x = y; \
2112 if (x == NULL) \
2113 goto Done
Tim Peters2a799bf2002-12-16 20:18:38 +00002114
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002115 if (us) {
Alexander Belopolsky790d2692013-08-04 14:51:35 -04002116 y = accum("microseconds", x, us, one, &leftover_us);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002117 CLEANUP;
2118 }
2119 if (ms) {
2120 y = accum("milliseconds", x, ms, us_per_ms, &leftover_us);
2121 CLEANUP;
2122 }
2123 if (second) {
2124 y = accum("seconds", x, second, us_per_second, &leftover_us);
2125 CLEANUP;
2126 }
2127 if (minute) {
2128 y = accum("minutes", x, minute, us_per_minute, &leftover_us);
2129 CLEANUP;
2130 }
2131 if (hour) {
2132 y = accum("hours", x, hour, us_per_hour, &leftover_us);
2133 CLEANUP;
2134 }
2135 if (day) {
2136 y = accum("days", x, day, us_per_day, &leftover_us);
2137 CLEANUP;
2138 }
2139 if (week) {
2140 y = accum("weeks", x, week, us_per_week, &leftover_us);
2141 CLEANUP;
2142 }
2143 if (leftover_us) {
2144 /* Round to nearest whole # of us, and add into x. */
Alexander Belopolsky790d2692013-08-04 14:51:35 -04002145 double whole_us = round(leftover_us);
2146 int x_is_odd;
2147 PyObject *temp;
2148
2149 whole_us = round(leftover_us);
2150 if (fabs(whole_us - leftover_us) == 0.5) {
2151 /* We're exactly halfway between two integers. In order
2152 * to do round-half-to-even, we must determine whether x
2153 * is odd. Note that x is odd when it's last bit is 1. The
2154 * code below uses bitwise and operation to check the last
2155 * bit. */
Raymond Hettinger5a2146a2014-07-25 14:59:48 -07002156 temp = PyNumber_And(x, one); /* temp <- x & 1 */
Alexander Belopolsky790d2692013-08-04 14:51:35 -04002157 if (temp == NULL) {
2158 Py_DECREF(x);
2159 goto Done;
2160 }
2161 x_is_odd = PyObject_IsTrue(temp);
2162 Py_DECREF(temp);
2163 if (x_is_odd == -1) {
2164 Py_DECREF(x);
2165 goto Done;
2166 }
2167 whole_us = 2.0 * round((leftover_us + x_is_odd) * 0.5) - x_is_odd;
2168 }
2169
Victor Stinner36a5a062013-08-28 01:53:39 +02002170 temp = PyLong_FromLong((long)whole_us);
Alexander Belopolsky790d2692013-08-04 14:51:35 -04002171
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002172 if (temp == NULL) {
2173 Py_DECREF(x);
2174 goto Done;
2175 }
2176 y = PyNumber_Add(x, temp);
2177 Py_DECREF(temp);
2178 CLEANUP;
2179 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002180
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002181 self = microseconds_to_delta_ex(x, type);
2182 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00002183Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002184 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00002185
2186#undef CLEANUP
2187}
2188
2189static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00002190delta_bool(PyDateTime_Delta *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00002191{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002192 return (GET_TD_DAYS(self) != 0
2193 || GET_TD_SECONDS(self) != 0
2194 || GET_TD_MICROSECONDS(self) != 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00002195}
2196
2197static PyObject *
2198delta_repr(PyDateTime_Delta *self)
2199{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002200 if (GET_TD_MICROSECONDS(self) != 0)
2201 return PyUnicode_FromFormat("%s(%d, %d, %d)",
2202 Py_TYPE(self)->tp_name,
2203 GET_TD_DAYS(self),
2204 GET_TD_SECONDS(self),
2205 GET_TD_MICROSECONDS(self));
2206 if (GET_TD_SECONDS(self) != 0)
2207 return PyUnicode_FromFormat("%s(%d, %d)",
2208 Py_TYPE(self)->tp_name,
2209 GET_TD_DAYS(self),
2210 GET_TD_SECONDS(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002211
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002212 return PyUnicode_FromFormat("%s(%d)",
2213 Py_TYPE(self)->tp_name,
2214 GET_TD_DAYS(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002215}
2216
2217static PyObject *
2218delta_str(PyDateTime_Delta *self)
2219{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002220 int us = GET_TD_MICROSECONDS(self);
2221 int seconds = GET_TD_SECONDS(self);
2222 int minutes = divmod(seconds, 60, &seconds);
2223 int hours = divmod(minutes, 60, &minutes);
2224 int days = GET_TD_DAYS(self);
Tim Peters2a799bf2002-12-16 20:18:38 +00002225
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002226 if (days) {
2227 if (us)
2228 return PyUnicode_FromFormat("%d day%s, %d:%02d:%02d.%06d",
2229 days, (days == 1 || days == -1) ? "" : "s",
2230 hours, minutes, seconds, us);
2231 else
2232 return PyUnicode_FromFormat("%d day%s, %d:%02d:%02d",
2233 days, (days == 1 || days == -1) ? "" : "s",
2234 hours, minutes, seconds);
2235 } else {
2236 if (us)
2237 return PyUnicode_FromFormat("%d:%02d:%02d.%06d",
2238 hours, minutes, seconds, us);
2239 else
2240 return PyUnicode_FromFormat("%d:%02d:%02d",
2241 hours, minutes, seconds);
2242 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002243
Tim Peters2a799bf2002-12-16 20:18:38 +00002244}
2245
Tim Peters371935f2003-02-01 01:52:50 +00002246/* Pickle support, a simple use of __reduce__. */
2247
Tim Petersb57f8f02003-02-01 02:54:15 +00002248/* __getstate__ isn't exposed */
Tim Peters2a799bf2002-12-16 20:18:38 +00002249static PyObject *
2250delta_getstate(PyDateTime_Delta *self)
2251{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002252 return Py_BuildValue("iii", GET_TD_DAYS(self),
2253 GET_TD_SECONDS(self),
2254 GET_TD_MICROSECONDS(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002255}
2256
Tim Peters2a799bf2002-12-16 20:18:38 +00002257static PyObject *
Antoine Pitroube6859d2009-11-25 23:02:32 +00002258delta_total_seconds(PyObject *self)
2259{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002260 PyObject *total_seconds;
2261 PyObject *total_microseconds;
Mark Dickinson0381e3f2010-05-08 14:35:02 +00002262
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002263 total_microseconds = delta_to_microseconds((PyDateTime_Delta *)self);
2264 if (total_microseconds == NULL)
2265 return NULL;
Mark Dickinson0381e3f2010-05-08 14:35:02 +00002266
Alexander Belopolskydf7027b2013-08-04 15:18:58 -04002267 total_seconds = PyNumber_TrueDivide(total_microseconds, us_per_second);
Mark Dickinson0381e3f2010-05-08 14:35:02 +00002268
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002269 Py_DECREF(total_microseconds);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002270 return total_seconds;
Antoine Pitroube6859d2009-11-25 23:02:32 +00002271}
2272
2273static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002274delta_reduce(PyDateTime_Delta* self)
2275{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002276 return Py_BuildValue("ON", Py_TYPE(self), delta_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002277}
2278
2279#define OFFSET(field) offsetof(PyDateTime_Delta, field)
2280
2281static PyMemberDef delta_members[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002282
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002283 {"days", T_INT, OFFSET(days), READONLY,
2284 PyDoc_STR("Number of days.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002285
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002286 {"seconds", T_INT, OFFSET(seconds), READONLY,
2287 PyDoc_STR("Number of seconds (>= 0 and less than 1 day).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002288
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002289 {"microseconds", T_INT, OFFSET(microseconds), READONLY,
2290 PyDoc_STR("Number of microseconds (>= 0 and less than 1 second).")},
2291 {NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00002292};
2293
2294static PyMethodDef delta_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002295 {"total_seconds", (PyCFunction)delta_total_seconds, METH_NOARGS,
2296 PyDoc_STR("Total seconds in the duration.")},
Antoine Pitroube6859d2009-11-25 23:02:32 +00002297
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002298 {"__reduce__", (PyCFunction)delta_reduce, METH_NOARGS,
2299 PyDoc_STR("__reduce__() -> (cls, state)")},
Guido van Rossum177e41a2003-01-30 22:06:23 +00002300
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002301 {NULL, NULL},
Tim Peters2a799bf2002-12-16 20:18:38 +00002302};
2303
2304static char delta_doc[] =
2305PyDoc_STR("Difference between two datetime values.");
2306
2307static PyNumberMethods delta_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002308 delta_add, /* nb_add */
2309 delta_subtract, /* nb_subtract */
2310 delta_multiply, /* nb_multiply */
2311 delta_remainder, /* nb_remainder */
2312 delta_divmod, /* nb_divmod */
2313 0, /* nb_power */
2314 (unaryfunc)delta_negative, /* nb_negative */
2315 (unaryfunc)delta_positive, /* nb_positive */
2316 (unaryfunc)delta_abs, /* nb_absolute */
2317 (inquiry)delta_bool, /* nb_bool */
2318 0, /*nb_invert*/
2319 0, /*nb_lshift*/
2320 0, /*nb_rshift*/
2321 0, /*nb_and*/
2322 0, /*nb_xor*/
2323 0, /*nb_or*/
2324 0, /*nb_int*/
2325 0, /*nb_reserved*/
2326 0, /*nb_float*/
2327 0, /*nb_inplace_add*/
2328 0, /*nb_inplace_subtract*/
2329 0, /*nb_inplace_multiply*/
2330 0, /*nb_inplace_remainder*/
2331 0, /*nb_inplace_power*/
2332 0, /*nb_inplace_lshift*/
2333 0, /*nb_inplace_rshift*/
2334 0, /*nb_inplace_and*/
2335 0, /*nb_inplace_xor*/
2336 0, /*nb_inplace_or*/
2337 delta_divide, /* nb_floor_divide */
2338 delta_truedivide, /* nb_true_divide */
2339 0, /* nb_inplace_floor_divide */
2340 0, /* nb_inplace_true_divide */
Tim Peters2a799bf2002-12-16 20:18:38 +00002341};
2342
2343static PyTypeObject PyDateTime_DeltaType = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002344 PyVarObject_HEAD_INIT(NULL, 0)
2345 "datetime.timedelta", /* tp_name */
2346 sizeof(PyDateTime_Delta), /* tp_basicsize */
2347 0, /* tp_itemsize */
2348 0, /* tp_dealloc */
2349 0, /* tp_print */
2350 0, /* tp_getattr */
2351 0, /* tp_setattr */
2352 0, /* tp_reserved */
2353 (reprfunc)delta_repr, /* tp_repr */
2354 &delta_as_number, /* tp_as_number */
2355 0, /* tp_as_sequence */
2356 0, /* tp_as_mapping */
2357 (hashfunc)delta_hash, /* tp_hash */
2358 0, /* tp_call */
2359 (reprfunc)delta_str, /* tp_str */
2360 PyObject_GenericGetAttr, /* tp_getattro */
2361 0, /* tp_setattro */
2362 0, /* tp_as_buffer */
2363 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
2364 delta_doc, /* tp_doc */
2365 0, /* tp_traverse */
2366 0, /* tp_clear */
2367 delta_richcompare, /* tp_richcompare */
2368 0, /* tp_weaklistoffset */
2369 0, /* tp_iter */
2370 0, /* tp_iternext */
2371 delta_methods, /* tp_methods */
2372 delta_members, /* tp_members */
2373 0, /* tp_getset */
2374 0, /* tp_base */
2375 0, /* tp_dict */
2376 0, /* tp_descr_get */
2377 0, /* tp_descr_set */
2378 0, /* tp_dictoffset */
2379 0, /* tp_init */
2380 0, /* tp_alloc */
2381 delta_new, /* tp_new */
2382 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00002383};
2384
2385/*
2386 * PyDateTime_Date implementation.
2387 */
2388
2389/* Accessor properties. */
2390
2391static PyObject *
2392date_year(PyDateTime_Date *self, void *unused)
2393{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002394 return PyLong_FromLong(GET_YEAR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002395}
2396
2397static PyObject *
2398date_month(PyDateTime_Date *self, void *unused)
2399{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002400 return PyLong_FromLong(GET_MONTH(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002401}
2402
2403static PyObject *
2404date_day(PyDateTime_Date *self, void *unused)
2405{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002406 return PyLong_FromLong(GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002407}
2408
2409static PyGetSetDef date_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002410 {"year", (getter)date_year},
2411 {"month", (getter)date_month},
2412 {"day", (getter)date_day},
2413 {NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00002414};
2415
2416/* Constructors. */
2417
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00002418static char *date_kws[] = {"year", "month", "day", NULL};
Tim Peters12bf3392002-12-24 05:41:27 +00002419
Tim Peters2a799bf2002-12-16 20:18:38 +00002420static PyObject *
2421date_new(PyTypeObject *type, PyObject *args, PyObject *kw)
2422{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002423 PyObject *self = NULL;
2424 PyObject *state;
2425 int year;
2426 int month;
2427 int day;
Tim Peters2a799bf2002-12-16 20:18:38 +00002428
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002429 /* Check for invocation from pickle with __getstate__ state */
2430 if (PyTuple_GET_SIZE(args) == 1 &&
2431 PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) &&
2432 PyBytes_GET_SIZE(state) == _PyDateTime_DATE_DATASIZE &&
2433 MONTH_IS_SANE(PyBytes_AS_STRING(state)[2]))
2434 {
2435 PyDateTime_Date *me;
Tim Peters70533e22003-02-01 04:40:04 +00002436
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002437 me = (PyDateTime_Date *) (type->tp_alloc(type, 0));
2438 if (me != NULL) {
2439 char *pdata = PyBytes_AS_STRING(state);
2440 memcpy(me->data, pdata, _PyDateTime_DATE_DATASIZE);
2441 me->hashcode = -1;
2442 }
2443 return (PyObject *)me;
2444 }
Guido van Rossum177e41a2003-01-30 22:06:23 +00002445
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002446 if (PyArg_ParseTupleAndKeywords(args, kw, "iii", date_kws,
2447 &year, &month, &day)) {
2448 if (check_date_args(year, month, day) < 0)
2449 return NULL;
2450 self = new_date_ex(year, month, day, type);
2451 }
2452 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00002453}
2454
2455/* Return new date from localtime(t). */
2456static PyObject *
Victor Stinner5d272cc2012-03-13 13:35:55 +01002457date_local_from_object(PyObject *cls, PyObject *obj)
Tim Peters2a799bf2002-12-16 20:18:38 +00002458{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002459 struct tm *tm;
2460 time_t t;
Tim Peters2a799bf2002-12-16 20:18:38 +00002461
Victor Stinner3c1b3792014-02-17 00:02:43 +01002462 if (_PyTime_ObjectToTime_t(obj, &t, _PyTime_ROUND_DOWN) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002463 return NULL;
Victor Stinner5d272cc2012-03-13 13:35:55 +01002464
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002465 tm = localtime(&t);
Victor Stinner21f58932012-03-14 00:15:40 +01002466 if (tm == NULL) {
2467 /* unconvertible time */
2468#ifdef EINVAL
2469 if (errno == 0)
2470 errno = EINVAL;
2471#endif
2472 PyErr_SetFromErrno(PyExc_OSError);
2473 return NULL;
2474 }
2475
2476 return PyObject_CallFunction(cls, "iii",
2477 tm->tm_year + 1900,
2478 tm->tm_mon + 1,
2479 tm->tm_mday);
Tim Peters2a799bf2002-12-16 20:18:38 +00002480}
2481
2482/* Return new date from current time.
2483 * We say this is equivalent to fromtimestamp(time.time()), and the
2484 * only way to be sure of that is to *call* time.time(). That's not
2485 * generally the same as calling C's time.
2486 */
2487static PyObject *
2488date_today(PyObject *cls, PyObject *dummy)
2489{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002490 PyObject *time;
2491 PyObject *result;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002492 _Py_IDENTIFIER(fromtimestamp);
Tim Peters2a799bf2002-12-16 20:18:38 +00002493
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002494 time = time_time();
2495 if (time == NULL)
2496 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002497
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002498 /* Note well: today() is a class method, so this may not call
2499 * date.fromtimestamp. For example, it may call
2500 * datetime.fromtimestamp. That's why we need all the accuracy
2501 * time.time() delivers; if someone were gonzo about optimization,
2502 * date.today() could get away with plain C time().
2503 */
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002504 result = _PyObject_CallMethodId(cls, &PyId_fromtimestamp, "O", time);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002505 Py_DECREF(time);
2506 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002507}
2508
2509/* Return new date from given timestamp (Python timestamp -- a double). */
2510static PyObject *
2511date_fromtimestamp(PyObject *cls, PyObject *args)
2512{
Victor Stinner5d272cc2012-03-13 13:35:55 +01002513 PyObject *timestamp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002514 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002515
Victor Stinner5d272cc2012-03-13 13:35:55 +01002516 if (PyArg_ParseTuple(args, "O:fromtimestamp", &timestamp))
2517 result = date_local_from_object(cls, timestamp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002518 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002519}
2520
2521/* Return new date from proleptic Gregorian ordinal. Raises ValueError if
2522 * the ordinal is out of range.
2523 */
2524static PyObject *
2525date_fromordinal(PyObject *cls, PyObject *args)
2526{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002527 PyObject *result = NULL;
2528 int ordinal;
Tim Peters2a799bf2002-12-16 20:18:38 +00002529
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002530 if (PyArg_ParseTuple(args, "i:fromordinal", &ordinal)) {
2531 int year;
2532 int month;
2533 int day;
Tim Peters2a799bf2002-12-16 20:18:38 +00002534
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002535 if (ordinal < 1)
2536 PyErr_SetString(PyExc_ValueError, "ordinal must be "
2537 ">= 1");
2538 else {
2539 ord_to_ymd(ordinal, &year, &month, &day);
2540 result = PyObject_CallFunction(cls, "iii",
2541 year, month, day);
2542 }
2543 }
2544 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002545}
2546
2547/*
2548 * Date arithmetic.
2549 */
2550
2551/* date + timedelta -> date. If arg negate is true, subtract the timedelta
2552 * instead.
2553 */
2554static PyObject *
2555add_date_timedelta(PyDateTime_Date *date, PyDateTime_Delta *delta, int negate)
2556{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002557 PyObject *result = NULL;
2558 int year = GET_YEAR(date);
2559 int month = GET_MONTH(date);
2560 int deltadays = GET_TD_DAYS(delta);
2561 /* C-level overflow is impossible because |deltadays| < 1e9. */
2562 int day = GET_DAY(date) + (negate ? -deltadays : deltadays);
Tim Peters2a799bf2002-12-16 20:18:38 +00002563
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002564 if (normalize_date(&year, &month, &day) >= 0)
2565 result = new_date(year, month, day);
2566 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002567}
2568
2569static PyObject *
2570date_add(PyObject *left, PyObject *right)
2571{
Brian Curtindfc80e32011-08-10 20:28:54 -05002572 if (PyDateTime_Check(left) || PyDateTime_Check(right))
2573 Py_RETURN_NOTIMPLEMENTED;
2574
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002575 if (PyDate_Check(left)) {
2576 /* date + ??? */
2577 if (PyDelta_Check(right))
2578 /* date + delta */
2579 return add_date_timedelta((PyDateTime_Date *) left,
2580 (PyDateTime_Delta *) right,
2581 0);
2582 }
2583 else {
2584 /* ??? + date
2585 * 'right' must be one of us, or we wouldn't have been called
2586 */
2587 if (PyDelta_Check(left))
2588 /* delta + date */
2589 return add_date_timedelta((PyDateTime_Date *) right,
2590 (PyDateTime_Delta *) left,
2591 0);
2592 }
Brian Curtindfc80e32011-08-10 20:28:54 -05002593 Py_RETURN_NOTIMPLEMENTED;
Tim Peters2a799bf2002-12-16 20:18:38 +00002594}
2595
2596static PyObject *
2597date_subtract(PyObject *left, PyObject *right)
2598{
Brian Curtindfc80e32011-08-10 20:28:54 -05002599 if (PyDateTime_Check(left) || PyDateTime_Check(right))
2600 Py_RETURN_NOTIMPLEMENTED;
2601
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002602 if (PyDate_Check(left)) {
2603 if (PyDate_Check(right)) {
2604 /* date - date */
2605 int left_ord = ymd_to_ord(GET_YEAR(left),
2606 GET_MONTH(left),
2607 GET_DAY(left));
2608 int right_ord = ymd_to_ord(GET_YEAR(right),
2609 GET_MONTH(right),
2610 GET_DAY(right));
2611 return new_delta(left_ord - right_ord, 0, 0, 0);
2612 }
2613 if (PyDelta_Check(right)) {
2614 /* date - delta */
2615 return add_date_timedelta((PyDateTime_Date *) left,
2616 (PyDateTime_Delta *) right,
2617 1);
2618 }
2619 }
Brian Curtindfc80e32011-08-10 20:28:54 -05002620 Py_RETURN_NOTIMPLEMENTED;
Tim Peters2a799bf2002-12-16 20:18:38 +00002621}
2622
2623
2624/* Various ways to turn a date into a string. */
2625
2626static PyObject *
2627date_repr(PyDateTime_Date *self)
2628{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002629 return PyUnicode_FromFormat("%s(%d, %d, %d)",
2630 Py_TYPE(self)->tp_name,
2631 GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002632}
2633
2634static PyObject *
2635date_isoformat(PyDateTime_Date *self)
2636{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002637 return PyUnicode_FromFormat("%04d-%02d-%02d",
2638 GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002639}
2640
Tim Peterse2df5ff2003-05-02 18:39:55 +00002641/* str() calls the appropriate isoformat() method. */
Tim Peters2a799bf2002-12-16 20:18:38 +00002642static PyObject *
2643date_str(PyDateTime_Date *self)
2644{
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002645 return _PyObject_CallMethodId((PyObject *)self, &PyId_isoformat, "()");
Tim Peters2a799bf2002-12-16 20:18:38 +00002646}
2647
2648
2649static PyObject *
2650date_ctime(PyDateTime_Date *self)
2651{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002652 return format_ctime(self, 0, 0, 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00002653}
2654
2655static PyObject *
2656date_strftime(PyDateTime_Date *self, PyObject *args, PyObject *kw)
2657{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002658 /* This method can be inherited, and needs to call the
2659 * timetuple() method appropriate to self's class.
2660 */
2661 PyObject *result;
2662 PyObject *tuple;
2663 PyObject *format;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002664 _Py_IDENTIFIER(timetuple);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002665 static char *keywords[] = {"format", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00002666
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002667 if (! PyArg_ParseTupleAndKeywords(args, kw, "U:strftime", keywords,
2668 &format))
2669 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002670
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002671 tuple = _PyObject_CallMethodId((PyObject *)self, &PyId_timetuple, "()");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002672 if (tuple == NULL)
2673 return NULL;
2674 result = wrap_strftime((PyObject *)self, format, tuple,
2675 (PyObject *)self);
2676 Py_DECREF(tuple);
2677 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002678}
2679
Eric Smith1ba31142007-09-11 18:06:02 +00002680static PyObject *
2681date_format(PyDateTime_Date *self, PyObject *args)
2682{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002683 PyObject *format;
Eric Smith1ba31142007-09-11 18:06:02 +00002684
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002685 if (!PyArg_ParseTuple(args, "U:__format__", &format))
2686 return NULL;
Eric Smith1ba31142007-09-11 18:06:02 +00002687
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002688 /* if the format is zero length, return str(self) */
Victor Stinner9e30aa52011-11-21 02:49:52 +01002689 if (PyUnicode_GetLength(format) == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002690 return PyObject_Str((PyObject *)self);
Eric Smith1ba31142007-09-11 18:06:02 +00002691
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002692 return _PyObject_CallMethodId((PyObject *)self, &PyId_strftime, "O", format);
Eric Smith1ba31142007-09-11 18:06:02 +00002693}
2694
Tim Peters2a799bf2002-12-16 20:18:38 +00002695/* ISO methods. */
2696
2697static PyObject *
2698date_isoweekday(PyDateTime_Date *self)
2699{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002700 int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002701
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002702 return PyLong_FromLong(dow + 1);
Tim Peters2a799bf2002-12-16 20:18:38 +00002703}
2704
2705static PyObject *
2706date_isocalendar(PyDateTime_Date *self)
2707{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002708 int year = GET_YEAR(self);
2709 int week1_monday = iso_week1_monday(year);
2710 int today = ymd_to_ord(year, GET_MONTH(self), GET_DAY(self));
2711 int week;
2712 int day;
Tim Peters2a799bf2002-12-16 20:18:38 +00002713
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002714 week = divmod(today - week1_monday, 7, &day);
2715 if (week < 0) {
2716 --year;
2717 week1_monday = iso_week1_monday(year);
2718 week = divmod(today - week1_monday, 7, &day);
2719 }
2720 else if (week >= 52 && today >= iso_week1_monday(year + 1)) {
2721 ++year;
2722 week = 0;
2723 }
2724 return Py_BuildValue("iii", year, week + 1, day + 1);
Tim Peters2a799bf2002-12-16 20:18:38 +00002725}
2726
2727/* Miscellaneous methods. */
2728
Tim Peters2a799bf2002-12-16 20:18:38 +00002729static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00002730date_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters2a799bf2002-12-16 20:18:38 +00002731{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002732 if (PyDate_Check(other)) {
2733 int diff = memcmp(((PyDateTime_Date *)self)->data,
2734 ((PyDateTime_Date *)other)->data,
2735 _PyDateTime_DATE_DATASIZE);
2736 return diff_to_bool(diff, op);
2737 }
Brian Curtindfc80e32011-08-10 20:28:54 -05002738 else
2739 Py_RETURN_NOTIMPLEMENTED;
Tim Peters2a799bf2002-12-16 20:18:38 +00002740}
2741
2742static PyObject *
2743date_timetuple(PyDateTime_Date *self)
2744{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002745 return build_struct_time(GET_YEAR(self),
2746 GET_MONTH(self),
2747 GET_DAY(self),
2748 0, 0, 0, -1);
Tim Peters2a799bf2002-12-16 20:18:38 +00002749}
2750
Tim Peters12bf3392002-12-24 05:41:27 +00002751static PyObject *
2752date_replace(PyDateTime_Date *self, PyObject *args, PyObject *kw)
2753{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002754 PyObject *clone;
2755 PyObject *tuple;
2756 int year = GET_YEAR(self);
2757 int month = GET_MONTH(self);
2758 int day = GET_DAY(self);
Tim Peters12bf3392002-12-24 05:41:27 +00002759
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002760 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iii:replace", date_kws,
2761 &year, &month, &day))
2762 return NULL;
2763 tuple = Py_BuildValue("iii", year, month, day);
2764 if (tuple == NULL)
2765 return NULL;
2766 clone = date_new(Py_TYPE(self), tuple, NULL);
2767 Py_DECREF(tuple);
2768 return clone;
Tim Peters12bf3392002-12-24 05:41:27 +00002769}
2770
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002771static Py_hash_t
Guido van Rossumfd53fd62007-08-24 04:05:13 +00002772generic_hash(unsigned char *data, int len)
2773{
Gregory P. Smith5831bd22012-01-14 14:31:13 -08002774 return _Py_HashBytes(data, len);
Guido van Rossumfd53fd62007-08-24 04:05:13 +00002775}
2776
2777
2778static PyObject *date_getstate(PyDateTime_Date *self);
Tim Peters2a799bf2002-12-16 20:18:38 +00002779
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002780static Py_hash_t
Tim Peters2a799bf2002-12-16 20:18:38 +00002781date_hash(PyDateTime_Date *self)
2782{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002783 if (self->hashcode == -1)
2784 self->hashcode = generic_hash(
2785 (unsigned char *)self->data, _PyDateTime_DATE_DATASIZE);
Guido van Rossum254348e2007-11-21 19:29:53 +00002786
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002787 return self->hashcode;
Tim Peters2a799bf2002-12-16 20:18:38 +00002788}
2789
2790static PyObject *
2791date_toordinal(PyDateTime_Date *self)
2792{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002793 return PyLong_FromLong(ymd_to_ord(GET_YEAR(self), GET_MONTH(self),
2794 GET_DAY(self)));
Tim Peters2a799bf2002-12-16 20:18:38 +00002795}
2796
2797static PyObject *
2798date_weekday(PyDateTime_Date *self)
2799{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002800 int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002801
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002802 return PyLong_FromLong(dow);
Tim Peters2a799bf2002-12-16 20:18:38 +00002803}
2804
Tim Peters371935f2003-02-01 01:52:50 +00002805/* Pickle support, a simple use of __reduce__. */
Tim Peters2a799bf2002-12-16 20:18:38 +00002806
Tim Petersb57f8f02003-02-01 02:54:15 +00002807/* __getstate__ isn't exposed */
Tim Peters2a799bf2002-12-16 20:18:38 +00002808static PyObject *
Guido van Rossumfd53fd62007-08-24 04:05:13 +00002809date_getstate(PyDateTime_Date *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00002810{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002811 PyObject* field;
2812 field = PyBytes_FromStringAndSize((char*)self->data,
2813 _PyDateTime_DATE_DATASIZE);
2814 return Py_BuildValue("(N)", field);
Tim Peters2a799bf2002-12-16 20:18:38 +00002815}
2816
2817static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00002818date_reduce(PyDateTime_Date *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00002819{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002820 return Py_BuildValue("(ON)", Py_TYPE(self), date_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002821}
2822
2823static PyMethodDef date_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002824
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002825 /* Class methods: */
Guido van Rossum177e41a2003-01-30 22:06:23 +00002826
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002827 {"fromtimestamp", (PyCFunction)date_fromtimestamp, METH_VARARGS |
2828 METH_CLASS,
2829 PyDoc_STR("timestamp -> local date from a POSIX timestamp (like "
2830 "time.time()).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002831
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002832 {"fromordinal", (PyCFunction)date_fromordinal, METH_VARARGS |
2833 METH_CLASS,
2834 PyDoc_STR("int -> date corresponding to a proleptic Gregorian "
2835 "ordinal.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002836
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002837 {"today", (PyCFunction)date_today, METH_NOARGS | METH_CLASS,
2838 PyDoc_STR("Current date or datetime: same as "
2839 "self.__class__.fromtimestamp(time.time()).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002840
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002841 /* Instance methods: */
Tim Peters2a799bf2002-12-16 20:18:38 +00002842
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002843 {"ctime", (PyCFunction)date_ctime, METH_NOARGS,
2844 PyDoc_STR("Return ctime() style string.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002845
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002846 {"strftime", (PyCFunction)date_strftime, METH_VARARGS | METH_KEYWORDS,
2847 PyDoc_STR("format -> strftime() style string.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002848
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002849 {"__format__", (PyCFunction)date_format, METH_VARARGS,
2850 PyDoc_STR("Formats self with strftime.")},
Eric Smith1ba31142007-09-11 18:06:02 +00002851
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002852 {"timetuple", (PyCFunction)date_timetuple, METH_NOARGS,
2853 PyDoc_STR("Return time tuple, compatible with time.localtime().")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002854
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002855 {"isocalendar", (PyCFunction)date_isocalendar, METH_NOARGS,
2856 PyDoc_STR("Return a 3-tuple containing ISO year, week number, and "
2857 "weekday.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002858
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002859 {"isoformat", (PyCFunction)date_isoformat, METH_NOARGS,
2860 PyDoc_STR("Return string in ISO 8601 format, YYYY-MM-DD.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002861
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002862 {"isoweekday", (PyCFunction)date_isoweekday, METH_NOARGS,
2863 PyDoc_STR("Return the day of the week represented by the date.\n"
2864 "Monday == 1 ... Sunday == 7")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002865
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002866 {"toordinal", (PyCFunction)date_toordinal, METH_NOARGS,
2867 PyDoc_STR("Return proleptic Gregorian ordinal. January 1 of year "
2868 "1 is day 1.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002869
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002870 {"weekday", (PyCFunction)date_weekday, METH_NOARGS,
2871 PyDoc_STR("Return the day of the week represented by the date.\n"
2872 "Monday == 0 ... Sunday == 6")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002873
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002874 {"replace", (PyCFunction)date_replace, METH_VARARGS | METH_KEYWORDS,
2875 PyDoc_STR("Return date with new specified fields.")},
Tim Peters12bf3392002-12-24 05:41:27 +00002876
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002877 {"__reduce__", (PyCFunction)date_reduce, METH_NOARGS,
2878 PyDoc_STR("__reduce__() -> (cls, state)")},
Guido van Rossum177e41a2003-01-30 22:06:23 +00002879
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002880 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00002881};
2882
2883static char date_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00002884PyDoc_STR("date(year, month, day) --> date object");
Tim Peters2a799bf2002-12-16 20:18:38 +00002885
2886static PyNumberMethods date_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002887 date_add, /* nb_add */
2888 date_subtract, /* nb_subtract */
2889 0, /* nb_multiply */
2890 0, /* nb_remainder */
2891 0, /* nb_divmod */
2892 0, /* nb_power */
2893 0, /* nb_negative */
2894 0, /* nb_positive */
2895 0, /* nb_absolute */
2896 0, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00002897};
2898
2899static PyTypeObject PyDateTime_DateType = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002900 PyVarObject_HEAD_INIT(NULL, 0)
2901 "datetime.date", /* tp_name */
2902 sizeof(PyDateTime_Date), /* tp_basicsize */
2903 0, /* tp_itemsize */
2904 0, /* tp_dealloc */
2905 0, /* tp_print */
2906 0, /* tp_getattr */
2907 0, /* tp_setattr */
2908 0, /* tp_reserved */
2909 (reprfunc)date_repr, /* tp_repr */
2910 &date_as_number, /* tp_as_number */
2911 0, /* tp_as_sequence */
2912 0, /* tp_as_mapping */
2913 (hashfunc)date_hash, /* tp_hash */
2914 0, /* tp_call */
2915 (reprfunc)date_str, /* tp_str */
2916 PyObject_GenericGetAttr, /* tp_getattro */
2917 0, /* tp_setattro */
2918 0, /* tp_as_buffer */
2919 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
2920 date_doc, /* tp_doc */
2921 0, /* tp_traverse */
2922 0, /* tp_clear */
2923 date_richcompare, /* tp_richcompare */
2924 0, /* tp_weaklistoffset */
2925 0, /* tp_iter */
2926 0, /* tp_iternext */
2927 date_methods, /* tp_methods */
2928 0, /* tp_members */
2929 date_getset, /* tp_getset */
2930 0, /* tp_base */
2931 0, /* tp_dict */
2932 0, /* tp_descr_get */
2933 0, /* tp_descr_set */
2934 0, /* tp_dictoffset */
2935 0, /* tp_init */
2936 0, /* tp_alloc */
2937 date_new, /* tp_new */
2938 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00002939};
2940
2941/*
Tim Peters2a799bf2002-12-16 20:18:38 +00002942 * PyDateTime_TZInfo implementation.
2943 */
2944
2945/* This is a pure abstract base class, so doesn't do anything beyond
2946 * raising NotImplemented exceptions. Real tzinfo classes need
2947 * to derive from this. This is mostly for clarity, and for efficiency in
Tim Petersa9bc1682003-01-11 03:39:11 +00002948 * datetime and time constructors (their tzinfo arguments need to
Tim Peters2a799bf2002-12-16 20:18:38 +00002949 * be subclasses of this tzinfo class, which is easy and quick to check).
2950 *
2951 * Note: For reasons having to do with pickling of subclasses, we have
2952 * to allow tzinfo objects to be instantiated. This wasn't an issue
2953 * in the Python implementation (__init__() could raise NotImplementedError
2954 * there without ill effect), but doing so in the C implementation hit a
2955 * brick wall.
2956 */
2957
2958static PyObject *
2959tzinfo_nogo(const char* methodname)
2960{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002961 PyErr_Format(PyExc_NotImplementedError,
2962 "a tzinfo subclass must implement %s()",
2963 methodname);
2964 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002965}
2966
2967/* Methods. A subclass must implement these. */
2968
Tim Peters52dcce22003-01-23 16:36:11 +00002969static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002970tzinfo_tzname(PyDateTime_TZInfo *self, PyObject *dt)
2971{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002972 return tzinfo_nogo("tzname");
Tim Peters2a799bf2002-12-16 20:18:38 +00002973}
2974
Tim Peters52dcce22003-01-23 16:36:11 +00002975static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002976tzinfo_utcoffset(PyDateTime_TZInfo *self, PyObject *dt)
2977{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002978 return tzinfo_nogo("utcoffset");
Tim Peters2a799bf2002-12-16 20:18:38 +00002979}
2980
Tim Peters52dcce22003-01-23 16:36:11 +00002981static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002982tzinfo_dst(PyDateTime_TZInfo *self, PyObject *dt)
2983{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002984 return tzinfo_nogo("dst");
Tim Peters2a799bf2002-12-16 20:18:38 +00002985}
2986
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00002987
2988static PyObject *add_datetime_timedelta(PyDateTime_DateTime *date,
2989 PyDateTime_Delta *delta,
2990 int factor);
2991static PyObject *datetime_utcoffset(PyObject *self, PyObject *);
2992static PyObject *datetime_dst(PyObject *self, PyObject *);
2993
Tim Peters52dcce22003-01-23 16:36:11 +00002994static PyObject *
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00002995tzinfo_fromutc(PyDateTime_TZInfo *self, PyObject *dt)
Tim Peters52dcce22003-01-23 16:36:11 +00002996{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00002997 PyObject *result = NULL;
2998 PyObject *off = NULL, *dst = NULL;
2999 PyDateTime_Delta *delta = NULL;
Tim Peters52dcce22003-01-23 16:36:11 +00003000
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003001 if (!PyDateTime_Check(dt)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003002 PyErr_SetString(PyExc_TypeError,
3003 "fromutc: argument must be a datetime");
3004 return NULL;
3005 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003006 if (GET_DT_TZINFO(dt) != (PyObject *)self) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003007 PyErr_SetString(PyExc_ValueError, "fromutc: dt.tzinfo "
3008 "is not self");
3009 return NULL;
3010 }
Tim Peters52dcce22003-01-23 16:36:11 +00003011
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003012 off = datetime_utcoffset(dt, NULL);
3013 if (off == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003014 return NULL;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003015 if (off == Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003016 PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
3017 "utcoffset() result required");
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003018 goto Fail;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003019 }
Tim Peters52dcce22003-01-23 16:36:11 +00003020
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003021 dst = datetime_dst(dt, NULL);
3022 if (dst == NULL)
3023 goto Fail;
3024 if (dst == Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003025 PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
3026 "dst() result required");
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003027 goto Fail;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003028 }
Tim Peters52dcce22003-01-23 16:36:11 +00003029
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003030 delta = (PyDateTime_Delta *)delta_subtract(off, dst);
3031 if (delta == NULL)
3032 goto Fail;
3033 result = add_datetime_timedelta((PyDateTime_DateTime *)dt, delta, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003034 if (result == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003035 goto Fail;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003036
3037 Py_DECREF(dst);
3038 dst = call_dst(GET_DT_TZINFO(dt), result);
3039 if (dst == NULL)
3040 goto Fail;
3041 if (dst == Py_None)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003042 goto Inconsistent;
Alexander Belopolskyedc68852015-09-27 22:31:45 -04003043 if (delta_bool((PyDateTime_Delta *)dst) != 0) {
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003044 PyObject *temp = result;
3045 result = add_datetime_timedelta((PyDateTime_DateTime *)result,
3046 (PyDateTime_Delta *)dst, 1);
3047 Py_DECREF(temp);
3048 if (result == NULL)
3049 goto Fail;
3050 }
3051 Py_DECREF(delta);
3052 Py_DECREF(dst);
3053 Py_DECREF(off);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003054 return result;
Tim Peters52dcce22003-01-23 16:36:11 +00003055
3056Inconsistent:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003057 PyErr_SetString(PyExc_ValueError, "fromutc: tz.dst() gave"
3058 "inconsistent results; cannot convert");
Tim Peters52dcce22003-01-23 16:36:11 +00003059
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003060 /* fall thru to failure */
Tim Peters52dcce22003-01-23 16:36:11 +00003061Fail:
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003062 Py_XDECREF(off);
3063 Py_XDECREF(dst);
3064 Py_XDECREF(delta);
3065 Py_XDECREF(result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003066 return NULL;
Tim Peters52dcce22003-01-23 16:36:11 +00003067}
3068
Tim Peters2a799bf2002-12-16 20:18:38 +00003069/*
3070 * Pickle support. This is solely so that tzinfo subclasses can use
Guido van Rossum177e41a2003-01-30 22:06:23 +00003071 * pickling -- tzinfo itself is supposed to be uninstantiable.
Tim Peters2a799bf2002-12-16 20:18:38 +00003072 */
3073
Guido van Rossum177e41a2003-01-30 22:06:23 +00003074static PyObject *
3075tzinfo_reduce(PyObject *self)
3076{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003077 PyObject *args, *state, *tmp;
3078 PyObject *getinitargs, *getstate;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02003079 _Py_IDENTIFIER(__getinitargs__);
3080 _Py_IDENTIFIER(__getstate__);
Tim Peters2a799bf2002-12-16 20:18:38 +00003081
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003082 tmp = PyTuple_New(0);
3083 if (tmp == NULL)
3084 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00003085
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02003086 getinitargs = _PyObject_GetAttrId(self, &PyId___getinitargs__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003087 if (getinitargs != NULL) {
3088 args = PyObject_CallObject(getinitargs, tmp);
3089 Py_DECREF(getinitargs);
3090 if (args == NULL) {
3091 Py_DECREF(tmp);
3092 return NULL;
3093 }
3094 }
3095 else {
3096 PyErr_Clear();
3097 args = tmp;
3098 Py_INCREF(args);
3099 }
Guido van Rossum177e41a2003-01-30 22:06:23 +00003100
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02003101 getstate = _PyObject_GetAttrId(self, &PyId___getstate__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003102 if (getstate != NULL) {
3103 state = PyObject_CallObject(getstate, tmp);
3104 Py_DECREF(getstate);
3105 if (state == NULL) {
3106 Py_DECREF(args);
3107 Py_DECREF(tmp);
3108 return NULL;
3109 }
3110 }
3111 else {
3112 PyObject **dictptr;
3113 PyErr_Clear();
3114 state = Py_None;
3115 dictptr = _PyObject_GetDictPtr(self);
3116 if (dictptr && *dictptr && PyDict_Size(*dictptr))
3117 state = *dictptr;
3118 Py_INCREF(state);
3119 }
Guido van Rossum177e41a2003-01-30 22:06:23 +00003120
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003121 Py_DECREF(tmp);
Guido van Rossum177e41a2003-01-30 22:06:23 +00003122
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003123 if (state == Py_None) {
3124 Py_DECREF(state);
3125 return Py_BuildValue("(ON)", Py_TYPE(self), args);
3126 }
3127 else
3128 return Py_BuildValue("(ONN)", Py_TYPE(self), args, state);
Guido van Rossum177e41a2003-01-30 22:06:23 +00003129}
Tim Peters2a799bf2002-12-16 20:18:38 +00003130
3131static PyMethodDef tzinfo_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00003132
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003133 {"tzname", (PyCFunction)tzinfo_tzname, METH_O,
3134 PyDoc_STR("datetime -> string name of time zone.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003135
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003136 {"utcoffset", (PyCFunction)tzinfo_utcoffset, METH_O,
Sean Reifscheiderdeda8cb2010-06-04 01:51:38 +00003137 PyDoc_STR("datetime -> timedelta showing offset from UTC, negative "
3138 "values indicating West of UTC")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003139
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003140 {"dst", (PyCFunction)tzinfo_dst, METH_O,
3141 PyDoc_STR("datetime -> DST offset in minutes east of UTC.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003142
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003143 {"fromutc", (PyCFunction)tzinfo_fromutc, METH_O,
Alexander Belopolsky2f194b92010-07-03 03:35:27 +00003144 PyDoc_STR("datetime in UTC -> datetime in local time.")},
Tim Peters52dcce22003-01-23 16:36:11 +00003145
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003146 {"__reduce__", (PyCFunction)tzinfo_reduce, METH_NOARGS,
3147 PyDoc_STR("-> (cls, state)")},
Guido van Rossum177e41a2003-01-30 22:06:23 +00003148
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003149 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00003150};
3151
3152static char tzinfo_doc[] =
3153PyDoc_STR("Abstract base class for time zone info objects.");
3154
Neal Norwitz227b5332006-03-22 09:28:35 +00003155static PyTypeObject PyDateTime_TZInfoType = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003156 PyVarObject_HEAD_INIT(NULL, 0)
3157 "datetime.tzinfo", /* tp_name */
3158 sizeof(PyDateTime_TZInfo), /* tp_basicsize */
3159 0, /* tp_itemsize */
3160 0, /* tp_dealloc */
3161 0, /* tp_print */
3162 0, /* tp_getattr */
3163 0, /* tp_setattr */
3164 0, /* tp_reserved */
3165 0, /* tp_repr */
3166 0, /* tp_as_number */
3167 0, /* tp_as_sequence */
3168 0, /* tp_as_mapping */
3169 0, /* tp_hash */
3170 0, /* tp_call */
3171 0, /* tp_str */
3172 PyObject_GenericGetAttr, /* tp_getattro */
3173 0, /* tp_setattro */
3174 0, /* tp_as_buffer */
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003175 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003176 tzinfo_doc, /* tp_doc */
3177 0, /* tp_traverse */
3178 0, /* tp_clear */
3179 0, /* tp_richcompare */
3180 0, /* tp_weaklistoffset */
3181 0, /* tp_iter */
3182 0, /* tp_iternext */
3183 tzinfo_methods, /* tp_methods */
3184 0, /* tp_members */
3185 0, /* tp_getset */
3186 0, /* tp_base */
3187 0, /* tp_dict */
3188 0, /* tp_descr_get */
3189 0, /* tp_descr_set */
3190 0, /* tp_dictoffset */
3191 0, /* tp_init */
3192 0, /* tp_alloc */
3193 PyType_GenericNew, /* tp_new */
3194 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00003195};
3196
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003197static char *timezone_kws[] = {"offset", "name", NULL};
3198
3199static PyObject *
3200timezone_new(PyTypeObject *type, PyObject *args, PyObject *kw)
3201{
3202 PyObject *offset;
3203 PyObject *name = NULL;
3204 if (PyArg_ParseTupleAndKeywords(args, kw, "O!|O!:timezone", timezone_kws,
3205 &PyDateTime_DeltaType, &offset,
3206 &PyUnicode_Type, &name))
3207 return new_timezone(offset, name);
3208
3209 return NULL;
3210}
3211
3212static void
3213timezone_dealloc(PyDateTime_TimeZone *self)
3214{
3215 Py_CLEAR(self->offset);
3216 Py_CLEAR(self->name);
3217 Py_TYPE(self)->tp_free((PyObject *)self);
3218}
3219
3220static PyObject *
3221timezone_richcompare(PyDateTime_TimeZone *self,
3222 PyDateTime_TimeZone *other, int op)
3223{
Brian Curtindfc80e32011-08-10 20:28:54 -05003224 if (op != Py_EQ && op != Py_NE)
3225 Py_RETURN_NOTIMPLEMENTED;
Georg Brandl0085a242012-09-22 09:23:12 +02003226 if (Py_TYPE(other) != &PyDateTime_TimeZoneType) {
Raymond Hettinger5a2146a2014-07-25 14:59:48 -07003227 if (op == Py_EQ)
3228 Py_RETURN_FALSE;
3229 else
3230 Py_RETURN_TRUE;
Georg Brandl0085a242012-09-22 09:23:12 +02003231 }
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003232 return delta_richcompare(self->offset, other->offset, op);
3233}
3234
Benjamin Peterson8f67d082010-10-17 20:54:53 +00003235static Py_hash_t
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003236timezone_hash(PyDateTime_TimeZone *self)
3237{
3238 return delta_hash((PyDateTime_Delta *)self->offset);
3239}
3240
3241/* Check argument type passed to tzname, utcoffset, or dst methods.
3242 Returns 0 for good argument. Returns -1 and sets exception info
3243 otherwise.
3244 */
3245static int
3246_timezone_check_argument(PyObject *dt, const char *meth)
3247{
3248 if (dt == Py_None || PyDateTime_Check(dt))
3249 return 0;
3250 PyErr_Format(PyExc_TypeError, "%s(dt) argument must be a datetime instance"
3251 " or None, not %.200s", meth, Py_TYPE(dt)->tp_name);
3252 return -1;
3253}
3254
3255static PyObject *
Alexander Belopolskya11d8c02010-07-06 23:19:45 +00003256timezone_repr(PyDateTime_TimeZone *self)
3257{
3258 /* Note that although timezone is not subclassable, it is convenient
3259 to use Py_TYPE(self)->tp_name here. */
3260 const char *type_name = Py_TYPE(self)->tp_name;
3261
3262 if (((PyObject *)self) == PyDateTime_TimeZone_UTC)
3263 return PyUnicode_FromFormat("%s.utc", type_name);
3264
3265 if (self->name == NULL)
3266 return PyUnicode_FromFormat("%s(%R)", type_name, self->offset);
3267
3268 return PyUnicode_FromFormat("%s(%R, %R)", type_name, self->offset,
3269 self->name);
3270}
3271
3272
3273static PyObject *
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003274timezone_str(PyDateTime_TimeZone *self)
3275{
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003276 int hours, minutes, seconds;
3277 PyObject *offset;
3278 char sign;
3279
3280 if (self->name != NULL) {
3281 Py_INCREF(self->name);
3282 return self->name;
3283 }
3284 /* Offset is normalized, so it is negative if days < 0 */
3285 if (GET_TD_DAYS(self->offset) < 0) {
3286 sign = '-';
3287 offset = delta_negative((PyDateTime_Delta *)self->offset);
3288 if (offset == NULL)
3289 return NULL;
3290 }
3291 else {
3292 sign = '+';
3293 offset = self->offset;
3294 Py_INCREF(offset);
3295 }
3296 /* Offset is not negative here. */
3297 seconds = GET_TD_SECONDS(offset);
3298 Py_DECREF(offset);
3299 minutes = divmod(seconds, 60, &seconds);
3300 hours = divmod(minutes, 60, &minutes);
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003301 /* XXX ignore sub-minute data, curently not allowed. */
Victor Stinner6ced7c42011-03-21 18:15:42 +01003302 assert(seconds == 0);
3303 return PyUnicode_FromFormat("UTC%c%02d:%02d", sign, hours, minutes);
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003304}
3305
3306static PyObject *
3307timezone_tzname(PyDateTime_TimeZone *self, PyObject *dt)
3308{
3309 if (_timezone_check_argument(dt, "tzname") == -1)
3310 return NULL;
3311
3312 return timezone_str(self);
3313}
3314
3315static PyObject *
3316timezone_utcoffset(PyDateTime_TimeZone *self, PyObject *dt)
3317{
3318 if (_timezone_check_argument(dt, "utcoffset") == -1)
3319 return NULL;
3320
3321 Py_INCREF(self->offset);
3322 return self->offset;
3323}
3324
3325static PyObject *
3326timezone_dst(PyObject *self, PyObject *dt)
3327{
3328 if (_timezone_check_argument(dt, "dst") == -1)
3329 return NULL;
3330
3331 Py_RETURN_NONE;
3332}
3333
3334static PyObject *
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003335timezone_fromutc(PyDateTime_TimeZone *self, PyDateTime_DateTime *dt)
3336{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003337 if (!PyDateTime_Check(dt)) {
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003338 PyErr_SetString(PyExc_TypeError,
3339 "fromutc: argument must be a datetime");
3340 return NULL;
3341 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003342 if (!HASTZINFO(dt) || dt->tzinfo != (PyObject *)self) {
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003343 PyErr_SetString(PyExc_ValueError, "fromutc: dt.tzinfo "
3344 "is not self");
3345 return NULL;
3346 }
3347
3348 return add_datetime_timedelta(dt, (PyDateTime_Delta *)self->offset, 1);
3349}
3350
Alexander Belopolsky1b7046b2010-06-23 21:40:15 +00003351static PyObject *
3352timezone_getinitargs(PyDateTime_TimeZone *self)
3353{
3354 if (self->name == NULL)
3355 return Py_BuildValue("(O)", self->offset);
3356 return Py_BuildValue("(OO)", self->offset, self->name);
3357}
3358
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003359static PyMethodDef timezone_methods[] = {
3360 {"tzname", (PyCFunction)timezone_tzname, METH_O,
3361 PyDoc_STR("If name is specified when timezone is created, returns the name."
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00003362 " Otherwise returns offset as 'UTC(+|-)HH:MM'.")},
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003363
3364 {"utcoffset", (PyCFunction)timezone_utcoffset, METH_O,
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00003365 PyDoc_STR("Return fixed offset.")},
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003366
3367 {"dst", (PyCFunction)timezone_dst, METH_O,
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00003368 PyDoc_STR("Return None.")},
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003369
3370 {"fromutc", (PyCFunction)timezone_fromutc, METH_O,
3371 PyDoc_STR("datetime in UTC -> datetime in local time.")},
3372
Alexander Belopolsky1b7046b2010-06-23 21:40:15 +00003373 {"__getinitargs__", (PyCFunction)timezone_getinitargs, METH_NOARGS,
3374 PyDoc_STR("pickle support")},
3375
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003376 {NULL, NULL}
3377};
3378
3379static char timezone_doc[] =
3380PyDoc_STR("Fixed offset from UTC implementation of tzinfo.");
3381
3382static PyTypeObject PyDateTime_TimeZoneType = {
3383 PyVarObject_HEAD_INIT(NULL, 0)
3384 "datetime.timezone", /* tp_name */
3385 sizeof(PyDateTime_TimeZone), /* tp_basicsize */
3386 0, /* tp_itemsize */
3387 (destructor)timezone_dealloc, /* tp_dealloc */
3388 0, /* tp_print */
3389 0, /* tp_getattr */
3390 0, /* tp_setattr */
3391 0, /* tp_reserved */
Alexander Belopolskya11d8c02010-07-06 23:19:45 +00003392 (reprfunc)timezone_repr, /* tp_repr */
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003393 0, /* tp_as_number */
3394 0, /* tp_as_sequence */
3395 0, /* tp_as_mapping */
3396 (hashfunc)timezone_hash, /* tp_hash */
3397 0, /* tp_call */
3398 (reprfunc)timezone_str, /* tp_str */
3399 0, /* tp_getattro */
3400 0, /* tp_setattro */
3401 0, /* tp_as_buffer */
3402 Py_TPFLAGS_DEFAULT, /* tp_flags */
3403 timezone_doc, /* tp_doc */
3404 0, /* tp_traverse */
3405 0, /* tp_clear */
3406 (richcmpfunc)timezone_richcompare,/* tp_richcompare */
3407 0, /* tp_weaklistoffset */
3408 0, /* tp_iter */
3409 0, /* tp_iternext */
3410 timezone_methods, /* tp_methods */
3411 0, /* tp_members */
3412 0, /* tp_getset */
3413 &PyDateTime_TZInfoType, /* tp_base */
3414 0, /* tp_dict */
3415 0, /* tp_descr_get */
3416 0, /* tp_descr_set */
3417 0, /* tp_dictoffset */
3418 0, /* tp_init */
3419 0, /* tp_alloc */
3420 timezone_new, /* tp_new */
3421};
3422
Tim Peters2a799bf2002-12-16 20:18:38 +00003423/*
Tim Peters37f39822003-01-10 03:49:02 +00003424 * PyDateTime_Time implementation.
Tim Peters2a799bf2002-12-16 20:18:38 +00003425 */
3426
Tim Peters37f39822003-01-10 03:49:02 +00003427/* Accessor properties.
Tim Peters2a799bf2002-12-16 20:18:38 +00003428 */
3429
3430static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003431time_hour(PyDateTime_Time *self, void *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00003432{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003433 return PyLong_FromLong(TIME_GET_HOUR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00003434}
3435
Tim Peters37f39822003-01-10 03:49:02 +00003436static PyObject *
3437time_minute(PyDateTime_Time *self, void *unused)
3438{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003439 return PyLong_FromLong(TIME_GET_MINUTE(self));
Tim Peters37f39822003-01-10 03:49:02 +00003440}
3441
3442/* The name time_second conflicted with some platform header file. */
3443static PyObject *
3444py_time_second(PyDateTime_Time *self, void *unused)
3445{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003446 return PyLong_FromLong(TIME_GET_SECOND(self));
Tim Peters37f39822003-01-10 03:49:02 +00003447}
3448
3449static PyObject *
3450time_microsecond(PyDateTime_Time *self, void *unused)
3451{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003452 return PyLong_FromLong(TIME_GET_MICROSECOND(self));
Tim Peters37f39822003-01-10 03:49:02 +00003453}
3454
3455static PyObject *
3456time_tzinfo(PyDateTime_Time *self, void *unused)
3457{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003458 PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
3459 Py_INCREF(result);
3460 return result;
Tim Peters37f39822003-01-10 03:49:02 +00003461}
3462
3463static PyGetSetDef time_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003464 {"hour", (getter)time_hour},
3465 {"minute", (getter)time_minute},
3466 {"second", (getter)py_time_second},
3467 {"microsecond", (getter)time_microsecond},
3468 {"tzinfo", (getter)time_tzinfo},
3469 {NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00003470};
3471
3472/*
3473 * Constructors.
3474 */
3475
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003476static char *time_kws[] = {"hour", "minute", "second", "microsecond",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003477 "tzinfo", NULL};
Tim Peters12bf3392002-12-24 05:41:27 +00003478
Tim Peters2a799bf2002-12-16 20:18:38 +00003479static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003480time_new(PyTypeObject *type, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003481{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003482 PyObject *self = NULL;
3483 PyObject *state;
3484 int hour = 0;
3485 int minute = 0;
3486 int second = 0;
3487 int usecond = 0;
3488 PyObject *tzinfo = Py_None;
Tim Peters2a799bf2002-12-16 20:18:38 +00003489
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003490 /* Check for invocation from pickle with __getstate__ state */
3491 if (PyTuple_GET_SIZE(args) >= 1 &&
3492 PyTuple_GET_SIZE(args) <= 2 &&
3493 PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) &&
3494 PyBytes_GET_SIZE(state) == _PyDateTime_TIME_DATASIZE &&
3495 ((unsigned char) (PyBytes_AS_STRING(state)[0])) < 24)
3496 {
3497 PyDateTime_Time *me;
3498 char aware;
Tim Peters70533e22003-02-01 04:40:04 +00003499
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003500 if (PyTuple_GET_SIZE(args) == 2) {
3501 tzinfo = PyTuple_GET_ITEM(args, 1);
3502 if (check_tzinfo_subclass(tzinfo) < 0) {
3503 PyErr_SetString(PyExc_TypeError, "bad "
3504 "tzinfo state arg");
3505 return NULL;
3506 }
3507 }
3508 aware = (char)(tzinfo != Py_None);
3509 me = (PyDateTime_Time *) (type->tp_alloc(type, aware));
3510 if (me != NULL) {
3511 char *pdata = PyBytes_AS_STRING(state);
Tim Peters70533e22003-02-01 04:40:04 +00003512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003513 memcpy(me->data, pdata, _PyDateTime_TIME_DATASIZE);
3514 me->hashcode = -1;
3515 me->hastzinfo = aware;
3516 if (aware) {
3517 Py_INCREF(tzinfo);
3518 me->tzinfo = tzinfo;
3519 }
3520 }
3521 return (PyObject *)me;
3522 }
Guido van Rossum177e41a2003-01-30 22:06:23 +00003523
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003524 if (PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO", time_kws,
3525 &hour, &minute, &second, &usecond,
3526 &tzinfo)) {
3527 if (check_time_args(hour, minute, second, usecond) < 0)
3528 return NULL;
3529 if (check_tzinfo_subclass(tzinfo) < 0)
3530 return NULL;
3531 self = new_time_ex(hour, minute, second, usecond, tzinfo,
3532 type);
3533 }
3534 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00003535}
3536
3537/*
3538 * Destructor.
3539 */
3540
3541static void
Tim Peters37f39822003-01-10 03:49:02 +00003542time_dealloc(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003543{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003544 if (HASTZINFO(self)) {
3545 Py_XDECREF(self->tzinfo);
3546 }
3547 Py_TYPE(self)->tp_free((PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00003548}
3549
3550/*
Tim Peters855fe882002-12-22 03:43:39 +00003551 * Indirect access to tzinfo methods.
Tim Peters2a799bf2002-12-16 20:18:38 +00003552 */
3553
Tim Peters2a799bf2002-12-16 20:18:38 +00003554/* These are all METH_NOARGS, so don't need to check the arglist. */
3555static PyObject *
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003556time_utcoffset(PyObject *self, PyObject *unused) {
3557 return call_utcoffset(GET_TIME_TZINFO(self), Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00003558}
3559
3560static PyObject *
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003561time_dst(PyObject *self, PyObject *unused) {
3562 return call_dst(GET_TIME_TZINFO(self), Py_None);
Tim Peters855fe882002-12-22 03:43:39 +00003563}
3564
3565static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003566time_tzname(PyDateTime_Time *self, PyObject *unused) {
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003567 return call_tzname(GET_TIME_TZINFO(self), Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00003568}
3569
3570/*
Tim Peters37f39822003-01-10 03:49:02 +00003571 * Various ways to turn a time into a string.
Tim Peters2a799bf2002-12-16 20:18:38 +00003572 */
3573
3574static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003575time_repr(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003576{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003577 const char *type_name = Py_TYPE(self)->tp_name;
3578 int h = TIME_GET_HOUR(self);
3579 int m = TIME_GET_MINUTE(self);
3580 int s = TIME_GET_SECOND(self);
3581 int us = TIME_GET_MICROSECOND(self);
3582 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00003583
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003584 if (us)
3585 result = PyUnicode_FromFormat("%s(%d, %d, %d, %d)",
3586 type_name, h, m, s, us);
3587 else if (s)
3588 result = PyUnicode_FromFormat("%s(%d, %d, %d)",
3589 type_name, h, m, s);
3590 else
3591 result = PyUnicode_FromFormat("%s(%d, %d)", type_name, h, m);
3592 if (result != NULL && HASTZINFO(self))
3593 result = append_keyword_tzinfo(result, self->tzinfo);
3594 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00003595}
3596
Tim Peters37f39822003-01-10 03:49:02 +00003597static PyObject *
3598time_str(PyDateTime_Time *self)
3599{
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02003600 return _PyObject_CallMethodId((PyObject *)self, &PyId_isoformat, "()");
Tim Peters37f39822003-01-10 03:49:02 +00003601}
Tim Peters2a799bf2002-12-16 20:18:38 +00003602
3603static PyObject *
Thomas Wouterscf297e42007-02-23 15:07:44 +00003604time_isoformat(PyDateTime_Time *self, PyObject *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00003605{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003606 char buf[100];
3607 PyObject *result;
Ezio Melotti3f5db392013-01-27 06:20:14 +02003608 int us = TIME_GET_MICROSECOND(self);
Tim Peters2a799bf2002-12-16 20:18:38 +00003609
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003610 if (us)
3611 result = PyUnicode_FromFormat("%02d:%02d:%02d.%06d",
3612 TIME_GET_HOUR(self),
3613 TIME_GET_MINUTE(self),
3614 TIME_GET_SECOND(self),
3615 us);
3616 else
3617 result = PyUnicode_FromFormat("%02d:%02d:%02d",
3618 TIME_GET_HOUR(self),
3619 TIME_GET_MINUTE(self),
3620 TIME_GET_SECOND(self));
Tim Peters37f39822003-01-10 03:49:02 +00003621
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003622 if (result == NULL || !HASTZINFO(self) || self->tzinfo == Py_None)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003623 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00003624
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003625 /* We need to append the UTC offset. */
3626 if (format_utcoffset(buf, sizeof(buf), ":", self->tzinfo,
3627 Py_None) < 0) {
3628 Py_DECREF(result);
3629 return NULL;
3630 }
3631 PyUnicode_AppendAndDel(&result, PyUnicode_FromString(buf));
3632 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00003633}
3634
Tim Peters37f39822003-01-10 03:49:02 +00003635static PyObject *
3636time_strftime(PyDateTime_Time *self, PyObject *args, PyObject *kw)
3637{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003638 PyObject *result;
3639 PyObject *tuple;
3640 PyObject *format;
3641 static char *keywords[] = {"format", NULL};
Tim Peters37f39822003-01-10 03:49:02 +00003642
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003643 if (! PyArg_ParseTupleAndKeywords(args, kw, "U:strftime", keywords,
3644 &format))
3645 return NULL;
Tim Peters37f39822003-01-10 03:49:02 +00003646
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003647 /* Python's strftime does insane things with the year part of the
3648 * timetuple. The year is forced to (the otherwise nonsensical)
Alexander Belopolskyb8bb4662011-01-08 00:13:34 +00003649 * 1900 to work around that.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003650 */
3651 tuple = Py_BuildValue("iiiiiiiii",
3652 1900, 1, 1, /* year, month, day */
3653 TIME_GET_HOUR(self),
3654 TIME_GET_MINUTE(self),
3655 TIME_GET_SECOND(self),
3656 0, 1, -1); /* weekday, daynum, dst */
3657 if (tuple == NULL)
3658 return NULL;
3659 assert(PyTuple_Size(tuple) == 9);
3660 result = wrap_strftime((PyObject *)self, format, tuple,
3661 Py_None);
3662 Py_DECREF(tuple);
3663 return result;
Tim Peters37f39822003-01-10 03:49:02 +00003664}
Tim Peters2a799bf2002-12-16 20:18:38 +00003665
3666/*
3667 * Miscellaneous methods.
3668 */
3669
Tim Peters37f39822003-01-10 03:49:02 +00003670static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00003671time_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters37f39822003-01-10 03:49:02 +00003672{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003673 PyObject *result = NULL;
3674 PyObject *offset1, *offset2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003675 int diff;
Tim Peters37f39822003-01-10 03:49:02 +00003676
Brian Curtindfc80e32011-08-10 20:28:54 -05003677 if (! PyTime_Check(other))
3678 Py_RETURN_NOTIMPLEMENTED;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003679
3680 if (GET_TIME_TZINFO(self) == GET_TIME_TZINFO(other)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003681 diff = memcmp(((PyDateTime_Time *)self)->data,
3682 ((PyDateTime_Time *)other)->data,
3683 _PyDateTime_TIME_DATASIZE);
3684 return diff_to_bool(diff, op);
3685 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003686 offset1 = time_utcoffset(self, NULL);
3687 if (offset1 == NULL)
3688 return NULL;
3689 offset2 = time_utcoffset(other, NULL);
3690 if (offset2 == NULL)
3691 goto done;
3692 /* If they're both naive, or both aware and have the same offsets,
3693 * we get off cheap. Note that if they're both naive, offset1 ==
3694 * offset2 == Py_None at this point.
3695 */
3696 if ((offset1 == offset2) ||
3697 (PyDelta_Check(offset1) && PyDelta_Check(offset2) &&
3698 delta_cmp(offset1, offset2) == 0)) {
3699 diff = memcmp(((PyDateTime_Time *)self)->data,
3700 ((PyDateTime_Time *)other)->data,
3701 _PyDateTime_TIME_DATASIZE);
3702 result = diff_to_bool(diff, op);
3703 }
3704 /* The hard case: both aware with different UTC offsets */
3705 else if (offset1 != Py_None && offset2 != Py_None) {
3706 int offsecs1, offsecs2;
3707 assert(offset1 != offset2); /* else last "if" handled it */
3708 offsecs1 = TIME_GET_HOUR(self) * 3600 +
3709 TIME_GET_MINUTE(self) * 60 +
3710 TIME_GET_SECOND(self) -
3711 GET_TD_DAYS(offset1) * 86400 -
3712 GET_TD_SECONDS(offset1);
3713 offsecs2 = TIME_GET_HOUR(other) * 3600 +
3714 TIME_GET_MINUTE(other) * 60 +
3715 TIME_GET_SECOND(other) -
3716 GET_TD_DAYS(offset2) * 86400 -
3717 GET_TD_SECONDS(offset2);
3718 diff = offsecs1 - offsecs2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003719 if (diff == 0)
3720 diff = TIME_GET_MICROSECOND(self) -
3721 TIME_GET_MICROSECOND(other);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003722 result = diff_to_bool(diff, op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003723 }
Alexander Belopolsky08313822012-06-15 20:19:47 -04003724 else if (op == Py_EQ) {
3725 result = Py_False;
3726 Py_INCREF(result);
3727 }
3728 else if (op == Py_NE) {
3729 result = Py_True;
3730 Py_INCREF(result);
3731 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003732 else {
3733 PyErr_SetString(PyExc_TypeError,
3734 "can't compare offset-naive and "
3735 "offset-aware times");
3736 }
3737 done:
3738 Py_DECREF(offset1);
3739 Py_XDECREF(offset2);
3740 return result;
Tim Peters37f39822003-01-10 03:49:02 +00003741}
3742
Benjamin Peterson8f67d082010-10-17 20:54:53 +00003743static Py_hash_t
Tim Peters37f39822003-01-10 03:49:02 +00003744time_hash(PyDateTime_Time *self)
3745{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003746 if (self->hashcode == -1) {
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003747 PyObject *offset;
Tim Peters37f39822003-01-10 03:49:02 +00003748
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003749 offset = time_utcoffset((PyObject *)self, NULL);
3750
3751 if (offset == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003752 return -1;
Tim Peters37f39822003-01-10 03:49:02 +00003753
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003754 /* Reduce this to a hash of another object. */
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003755 if (offset == Py_None)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003756 self->hashcode = generic_hash(
3757 (unsigned char *)self->data, _PyDateTime_TIME_DATASIZE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003758 else {
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003759 PyObject *temp1, *temp2;
3760 int seconds, microseconds;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003761 assert(HASTZINFO(self));
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003762 seconds = TIME_GET_HOUR(self) * 3600 +
3763 TIME_GET_MINUTE(self) * 60 +
3764 TIME_GET_SECOND(self);
3765 microseconds = TIME_GET_MICROSECOND(self);
3766 temp1 = new_delta(0, seconds, microseconds, 1);
3767 if (temp1 == NULL) {
3768 Py_DECREF(offset);
3769 return -1;
3770 }
3771 temp2 = delta_subtract(temp1, offset);
3772 Py_DECREF(temp1);
3773 if (temp2 == NULL) {
3774 Py_DECREF(offset);
3775 return -1;
3776 }
3777 self->hashcode = PyObject_Hash(temp2);
3778 Py_DECREF(temp2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003779 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003780 Py_DECREF(offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003781 }
3782 return self->hashcode;
Tim Peters37f39822003-01-10 03:49:02 +00003783}
Tim Peters2a799bf2002-12-16 20:18:38 +00003784
Tim Peters12bf3392002-12-24 05:41:27 +00003785static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003786time_replace(PyDateTime_Time *self, PyObject *args, PyObject *kw)
Tim Peters12bf3392002-12-24 05:41:27 +00003787{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003788 PyObject *clone;
3789 PyObject *tuple;
3790 int hh = TIME_GET_HOUR(self);
3791 int mm = TIME_GET_MINUTE(self);
3792 int ss = TIME_GET_SECOND(self);
3793 int us = TIME_GET_MICROSECOND(self);
3794 PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
Tim Peters12bf3392002-12-24 05:41:27 +00003795
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003796 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO:replace",
3797 time_kws,
3798 &hh, &mm, &ss, &us, &tzinfo))
3799 return NULL;
3800 tuple = Py_BuildValue("iiiiO", hh, mm, ss, us, tzinfo);
3801 if (tuple == NULL)
3802 return NULL;
3803 clone = time_new(Py_TYPE(self), tuple, NULL);
3804 Py_DECREF(tuple);
3805 return clone;
Tim Peters12bf3392002-12-24 05:41:27 +00003806}
3807
Tim Peters2a799bf2002-12-16 20:18:38 +00003808static int
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003809time_bool(PyObject *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003810{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003811 PyObject *offset, *tzinfo;
3812 int offsecs = 0;
Tim Peters2a799bf2002-12-16 20:18:38 +00003813
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003814 if (TIME_GET_SECOND(self) || TIME_GET_MICROSECOND(self)) {
3815 /* Since utcoffset is in whole minutes, nothing can
3816 * alter the conclusion that this is nonzero.
3817 */
3818 return 1;
3819 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003820 tzinfo = GET_TIME_TZINFO(self);
3821 if (tzinfo != Py_None) {
3822 offset = call_utcoffset(tzinfo, Py_None);
3823 if (offset == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003824 return -1;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003825 offsecs = GET_TD_DAYS(offset)*86400 + GET_TD_SECONDS(offset);
3826 Py_DECREF(offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003827 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003828 return (TIME_GET_MINUTE(self)*60 - offsecs + TIME_GET_HOUR(self)*3600) != 0;
Tim Peters2a799bf2002-12-16 20:18:38 +00003829}
3830
Tim Peters371935f2003-02-01 01:52:50 +00003831/* Pickle support, a simple use of __reduce__. */
Tim Peters2a799bf2002-12-16 20:18:38 +00003832
Tim Peters33e0f382003-01-10 02:05:14 +00003833/* Let basestate be the non-tzinfo data string.
Tim Peters2a799bf2002-12-16 20:18:38 +00003834 * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
3835 * So it's a tuple in any (non-error) case.
Tim Petersb57f8f02003-02-01 02:54:15 +00003836 * __getstate__ isn't exposed.
Tim Peters2a799bf2002-12-16 20:18:38 +00003837 */
3838static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003839time_getstate(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003840{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003841 PyObject *basestate;
3842 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00003843
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003844 basestate = PyBytes_FromStringAndSize((char *)self->data,
3845 _PyDateTime_TIME_DATASIZE);
3846 if (basestate != NULL) {
3847 if (! HASTZINFO(self) || self->tzinfo == Py_None)
3848 result = PyTuple_Pack(1, basestate);
3849 else
3850 result = PyTuple_Pack(2, basestate, self->tzinfo);
3851 Py_DECREF(basestate);
3852 }
3853 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00003854}
3855
3856static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00003857time_reduce(PyDateTime_Time *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00003858{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003859 return Py_BuildValue("(ON)", Py_TYPE(self), time_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00003860}
3861
Tim Peters37f39822003-01-10 03:49:02 +00003862static PyMethodDef time_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00003863
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003864 {"isoformat", (PyCFunction)time_isoformat, METH_NOARGS,
3865 PyDoc_STR("Return string in ISO 8601 format, HH:MM:SS[.mmmmmm]"
3866 "[+HH:MM].")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003867
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003868 {"strftime", (PyCFunction)time_strftime, METH_VARARGS | METH_KEYWORDS,
3869 PyDoc_STR("format -> strftime() style string.")},
Tim Peters37f39822003-01-10 03:49:02 +00003870
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003871 {"__format__", (PyCFunction)date_format, METH_VARARGS,
3872 PyDoc_STR("Formats self with strftime.")},
Eric Smith1ba31142007-09-11 18:06:02 +00003873
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003874 {"utcoffset", (PyCFunction)time_utcoffset, METH_NOARGS,
3875 PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003876
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003877 {"tzname", (PyCFunction)time_tzname, METH_NOARGS,
3878 PyDoc_STR("Return self.tzinfo.tzname(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003879
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003880 {"dst", (PyCFunction)time_dst, METH_NOARGS,
3881 PyDoc_STR("Return self.tzinfo.dst(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003882
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003883 {"replace", (PyCFunction)time_replace, METH_VARARGS | METH_KEYWORDS,
3884 PyDoc_STR("Return time with new specified fields.")},
Tim Peters12bf3392002-12-24 05:41:27 +00003885
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003886 {"__reduce__", (PyCFunction)time_reduce, METH_NOARGS,
3887 PyDoc_STR("__reduce__() -> (cls, state)")},
Guido van Rossum177e41a2003-01-30 22:06:23 +00003888
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003889 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00003890};
3891
Tim Peters37f39822003-01-10 03:49:02 +00003892static char time_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00003893PyDoc_STR("time([hour[, minute[, second[, microsecond[, tzinfo]]]]]) --> a time object\n\
3894\n\
3895All arguments are optional. tzinfo may be None, or an instance of\n\
Serhiy Storchaka95949422013-08-27 19:40:23 +03003896a tzinfo subclass. The remaining arguments may be ints.\n");
Tim Peters2a799bf2002-12-16 20:18:38 +00003897
Tim Peters37f39822003-01-10 03:49:02 +00003898static PyNumberMethods time_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003899 0, /* nb_add */
3900 0, /* nb_subtract */
3901 0, /* nb_multiply */
3902 0, /* nb_remainder */
3903 0, /* nb_divmod */
3904 0, /* nb_power */
3905 0, /* nb_negative */
3906 0, /* nb_positive */
3907 0, /* nb_absolute */
3908 (inquiry)time_bool, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00003909};
3910
Neal Norwitz227b5332006-03-22 09:28:35 +00003911static PyTypeObject PyDateTime_TimeType = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003912 PyVarObject_HEAD_INIT(NULL, 0)
3913 "datetime.time", /* tp_name */
3914 sizeof(PyDateTime_Time), /* tp_basicsize */
3915 0, /* tp_itemsize */
3916 (destructor)time_dealloc, /* tp_dealloc */
3917 0, /* tp_print */
3918 0, /* tp_getattr */
3919 0, /* tp_setattr */
3920 0, /* tp_reserved */
3921 (reprfunc)time_repr, /* tp_repr */
3922 &time_as_number, /* tp_as_number */
3923 0, /* tp_as_sequence */
3924 0, /* tp_as_mapping */
3925 (hashfunc)time_hash, /* tp_hash */
3926 0, /* tp_call */
3927 (reprfunc)time_str, /* tp_str */
3928 PyObject_GenericGetAttr, /* tp_getattro */
3929 0, /* tp_setattro */
3930 0, /* tp_as_buffer */
3931 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
3932 time_doc, /* tp_doc */
3933 0, /* tp_traverse */
3934 0, /* tp_clear */
3935 time_richcompare, /* tp_richcompare */
3936 0, /* tp_weaklistoffset */
3937 0, /* tp_iter */
3938 0, /* tp_iternext */
3939 time_methods, /* tp_methods */
3940 0, /* tp_members */
3941 time_getset, /* tp_getset */
3942 0, /* tp_base */
3943 0, /* tp_dict */
3944 0, /* tp_descr_get */
3945 0, /* tp_descr_set */
3946 0, /* tp_dictoffset */
3947 0, /* tp_init */
3948 time_alloc, /* tp_alloc */
3949 time_new, /* tp_new */
3950 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00003951};
3952
3953/*
Tim Petersa9bc1682003-01-11 03:39:11 +00003954 * PyDateTime_DateTime implementation.
Tim Peters2a799bf2002-12-16 20:18:38 +00003955 */
3956
Tim Petersa9bc1682003-01-11 03:39:11 +00003957/* Accessor properties. Properties for day, month, and year are inherited
3958 * from date.
Tim Peters2a799bf2002-12-16 20:18:38 +00003959 */
3960
3961static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003962datetime_hour(PyDateTime_DateTime *self, void *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00003963{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003964 return PyLong_FromLong(DATE_GET_HOUR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00003965}
3966
Tim Petersa9bc1682003-01-11 03:39:11 +00003967static PyObject *
3968datetime_minute(PyDateTime_DateTime *self, void *unused)
3969{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003970 return PyLong_FromLong(DATE_GET_MINUTE(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00003971}
3972
3973static PyObject *
3974datetime_second(PyDateTime_DateTime *self, void *unused)
3975{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003976 return PyLong_FromLong(DATE_GET_SECOND(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00003977}
3978
3979static PyObject *
3980datetime_microsecond(PyDateTime_DateTime *self, void *unused)
3981{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003982 return PyLong_FromLong(DATE_GET_MICROSECOND(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00003983}
3984
3985static PyObject *
3986datetime_tzinfo(PyDateTime_DateTime *self, void *unused)
3987{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003988 PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
3989 Py_INCREF(result);
3990 return result;
Tim Petersa9bc1682003-01-11 03:39:11 +00003991}
3992
3993static PyGetSetDef datetime_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003994 {"hour", (getter)datetime_hour},
3995 {"minute", (getter)datetime_minute},
3996 {"second", (getter)datetime_second},
3997 {"microsecond", (getter)datetime_microsecond},
3998 {"tzinfo", (getter)datetime_tzinfo},
3999 {NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00004000};
4001
4002/*
4003 * Constructors.
Tim Peters2a799bf2002-12-16 20:18:38 +00004004 */
4005
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00004006static char *datetime_kws[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004007 "year", "month", "day", "hour", "minute", "second",
4008 "microsecond", "tzinfo", NULL
Tim Peters12bf3392002-12-24 05:41:27 +00004009};
4010
Tim Peters2a799bf2002-12-16 20:18:38 +00004011static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004012datetime_new(PyTypeObject *type, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00004013{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004014 PyObject *self = NULL;
4015 PyObject *state;
4016 int year;
4017 int month;
4018 int day;
4019 int hour = 0;
4020 int minute = 0;
4021 int second = 0;
4022 int usecond = 0;
4023 PyObject *tzinfo = Py_None;
Tim Peters2a799bf2002-12-16 20:18:38 +00004024
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004025 /* Check for invocation from pickle with __getstate__ state */
4026 if (PyTuple_GET_SIZE(args) >= 1 &&
4027 PyTuple_GET_SIZE(args) <= 2 &&
4028 PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) &&
4029 PyBytes_GET_SIZE(state) == _PyDateTime_DATETIME_DATASIZE &&
4030 MONTH_IS_SANE(PyBytes_AS_STRING(state)[2]))
4031 {
4032 PyDateTime_DateTime *me;
4033 char aware;
Tim Peters70533e22003-02-01 04:40:04 +00004034
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004035 if (PyTuple_GET_SIZE(args) == 2) {
4036 tzinfo = PyTuple_GET_ITEM(args, 1);
4037 if (check_tzinfo_subclass(tzinfo) < 0) {
4038 PyErr_SetString(PyExc_TypeError, "bad "
4039 "tzinfo state arg");
4040 return NULL;
4041 }
4042 }
4043 aware = (char)(tzinfo != Py_None);
4044 me = (PyDateTime_DateTime *) (type->tp_alloc(type , aware));
4045 if (me != NULL) {
4046 char *pdata = PyBytes_AS_STRING(state);
Tim Peters70533e22003-02-01 04:40:04 +00004047
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004048 memcpy(me->data, pdata, _PyDateTime_DATETIME_DATASIZE);
4049 me->hashcode = -1;
4050 me->hastzinfo = aware;
4051 if (aware) {
4052 Py_INCREF(tzinfo);
4053 me->tzinfo = tzinfo;
4054 }
4055 }
4056 return (PyObject *)me;
4057 }
Guido van Rossum177e41a2003-01-30 22:06:23 +00004058
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004059 if (PyArg_ParseTupleAndKeywords(args, kw, "iii|iiiiO", datetime_kws,
4060 &year, &month, &day, &hour, &minute,
4061 &second, &usecond, &tzinfo)) {
4062 if (check_date_args(year, month, day) < 0)
4063 return NULL;
4064 if (check_time_args(hour, minute, second, usecond) < 0)
4065 return NULL;
4066 if (check_tzinfo_subclass(tzinfo) < 0)
4067 return NULL;
4068 self = new_datetime_ex(year, month, day,
4069 hour, minute, second, usecond,
4070 tzinfo, type);
4071 }
4072 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00004073}
4074
Tim Petersa9bc1682003-01-11 03:39:11 +00004075/* TM_FUNC is the shared type of localtime() and gmtime(). */
4076typedef struct tm *(*TM_FUNC)(const time_t *timer);
4077
4078/* Internal helper.
4079 * Build datetime from a time_t and a distinct count of microseconds.
4080 * Pass localtime or gmtime for f, to control the interpretation of timet.
4081 */
4082static PyObject *
4083datetime_from_timet_and_us(PyObject *cls, TM_FUNC f, time_t timet, int us,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004084 PyObject *tzinfo)
Tim Petersa9bc1682003-01-11 03:39:11 +00004085{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004086 struct tm *tm;
Tim Petersa9bc1682003-01-11 03:39:11 +00004087
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004088 tm = f(&timet);
Victor Stinner21f58932012-03-14 00:15:40 +01004089 if (tm == NULL) {
4090#ifdef EINVAL
4091 if (errno == 0)
4092 errno = EINVAL;
4093#endif
4094 return PyErr_SetFromErrno(PyExc_OSError);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004095 }
Victor Stinner21f58932012-03-14 00:15:40 +01004096
4097 /* The platform localtime/gmtime may insert leap seconds,
4098 * indicated by tm->tm_sec > 59. We don't care about them,
4099 * except to the extent that passing them on to the datetime
4100 * constructor would raise ValueError for a reason that
4101 * made no sense to the user.
4102 */
4103 if (tm->tm_sec > 59)
4104 tm->tm_sec = 59;
4105 return PyObject_CallFunction(cls, "iiiiiiiO",
4106 tm->tm_year + 1900,
4107 tm->tm_mon + 1,
4108 tm->tm_mday,
4109 tm->tm_hour,
4110 tm->tm_min,
4111 tm->tm_sec,
4112 us,
4113 tzinfo);
Tim Petersa9bc1682003-01-11 03:39:11 +00004114}
4115
Victor Stinner511491a2015-09-18 14:42:05 +02004116static time_t
4117_PyTime_DoubleToTimet(double x)
4118{
4119 time_t result;
4120 double diff;
4121
4122 result = (time_t)x;
4123 /* How much info did we lose? time_t may be an integral or
4124 * floating type, and we don't know which. If it's integral,
4125 * we don't know whether C truncates, rounds, returns the floor,
4126 * etc. If we lost a second or more, the C rounding is
4127 * unreasonable, or the input just doesn't fit in a time_t;
4128 * call it an error regardless. Note that the original cast to
4129 * time_t can cause a C error too, but nothing we can do to
4130 * worm around that.
4131 */
4132 diff = x - (double)result;
4133 if (diff <= -1.0 || diff >= 1.0) {
4134 PyErr_SetString(PyExc_OverflowError,
4135 "timestamp out of range for platform time_t");
4136 result = (time_t)-1;
4137 }
4138 return result;
4139}
4140
4141/* Round a double to the nearest long. |x| must be small enough to fit
4142 * in a C long; this is not checked.
4143 */
4144static double
4145_PyTime_RoundHalfEven(double x)
4146{
4147 double rounded = round(x);
4148 if (fabs(x-rounded) == 0.5)
4149 /* halfway case: round to even */
4150 rounded = 2.0*round(x/2.0);
4151 return rounded;
4152}
4153
Tim Petersa9bc1682003-01-11 03:39:11 +00004154/* Internal helper.
4155 * Build datetime from a Python timestamp. Pass localtime or gmtime for f,
4156 * to control the interpretation of the timestamp. Since a double doesn't
4157 * have enough bits to cover a datetime's full range of precision, it's
4158 * better to call datetime_from_timet_and_us provided you have a way
4159 * to get that much precision (e.g., C time() isn't good enough).
4160 */
4161static PyObject *
Victor Stinner511491a2015-09-18 14:42:05 +02004162datetime_from_timestamp(PyObject *cls, TM_FUNC f, double timestamp,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004163 PyObject *tzinfo)
Tim Petersa9bc1682003-01-11 03:39:11 +00004164{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004165 time_t timet;
Victor Stinner511491a2015-09-18 14:42:05 +02004166 double fraction;
4167 int us;
Tim Petersa9bc1682003-01-11 03:39:11 +00004168
Victor Stinner511491a2015-09-18 14:42:05 +02004169 timet = _PyTime_DoubleToTimet(timestamp);
4170 if (timet == (time_t)-1 && PyErr_Occurred())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004171 return NULL;
Victor Stinner511491a2015-09-18 14:42:05 +02004172 fraction = timestamp - (double)timet;
4173 us = (int)_PyTime_RoundHalfEven(fraction * 1e6);
4174 if (us < 0) {
4175 /* Truncation towards zero is not what we wanted
4176 for negative numbers (Python's mod semantics) */
4177 timet -= 1;
4178 us += 1000000;
4179 }
4180 /* If timestamp is less than one microsecond smaller than a
4181 * full second, round up. Otherwise, ValueErrors are raised
4182 * for some floats. */
4183 if (us == 1000000) {
4184 timet += 1;
4185 us = 0;
4186 }
4187 return datetime_from_timet_and_us(cls, f, timet, us, tzinfo);
Tim Petersa9bc1682003-01-11 03:39:11 +00004188}
4189
4190/* Internal helper.
4191 * Build most accurate possible datetime for current time. Pass localtime or
4192 * gmtime for f as appropriate.
4193 */
4194static PyObject *
4195datetime_best_possible(PyObject *cls, TM_FUNC f, PyObject *tzinfo)
4196{
Alexander Belopolsky6fc4ade2010-08-05 17:34:27 +00004197 _PyTime_timeval t;
4198 _PyTime_gettimeofday(&t);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004199 return datetime_from_timet_and_us(cls, f, t.tv_sec, (int)t.tv_usec,
4200 tzinfo);
Tim Petersa9bc1682003-01-11 03:39:11 +00004201}
4202
Larry Hastings61272b72014-01-07 12:41:53 -08004203/*[clinic input]
Larry Hastings31826802013-10-19 00:09:25 -07004204
4205@classmethod
Larry Hastingsed4a1c52013-11-18 09:32:13 -08004206datetime.datetime.now
Larry Hastings31826802013-10-19 00:09:25 -07004207
4208 tz: object = None
4209 Timezone object.
4210
4211Returns new datetime object representing current time local to tz.
4212
4213If no tz is specified, uses local timezone.
Larry Hastings61272b72014-01-07 12:41:53 -08004214[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -07004215
Larry Hastingsed4a1c52013-11-18 09:32:13 -08004216PyDoc_STRVAR(datetime_datetime_now__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -08004217"now($type, /, tz=None)\n"
4218"--\n"
4219"\n"
Larry Hastings31826802013-10-19 00:09:25 -07004220"Returns new datetime object representing current time local to tz.\n"
4221"\n"
Larry Hastings31826802013-10-19 00:09:25 -07004222" tz\n"
4223" Timezone object.\n"
4224"\n"
4225"If no tz is specified, uses local timezone.");
4226
Larry Hastingsed4a1c52013-11-18 09:32:13 -08004227#define DATETIME_DATETIME_NOW_METHODDEF \
4228 {"now", (PyCFunction)datetime_datetime_now, METH_VARARGS|METH_KEYWORDS|METH_CLASS, datetime_datetime_now__doc__},
Larry Hastings31826802013-10-19 00:09:25 -07004229
Tim Peters2a799bf2002-12-16 20:18:38 +00004230static PyObject *
Larry Hastings5c661892014-01-24 06:17:25 -08004231datetime_datetime_now_impl(PyTypeObject *type, PyObject *tz);
Larry Hastings31826802013-10-19 00:09:25 -07004232
4233static PyObject *
Larry Hastings5c661892014-01-24 06:17:25 -08004234datetime_datetime_now(PyTypeObject *type, PyObject *args, PyObject *kwargs)
Larry Hastings31826802013-10-19 00:09:25 -07004235{
4236 PyObject *return_value = NULL;
4237 static char *_keywords[] = {"tz", NULL};
4238 PyObject *tz = Py_None;
4239
4240 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
4241 "|O:now", _keywords,
4242 &tz))
4243 goto exit;
Larry Hastings5c661892014-01-24 06:17:25 -08004244 return_value = datetime_datetime_now_impl(type, tz);
Larry Hastings31826802013-10-19 00:09:25 -07004245
4246exit:
4247 return return_value;
4248}
4249
4250static PyObject *
Larry Hastings5c661892014-01-24 06:17:25 -08004251datetime_datetime_now_impl(PyTypeObject *type, PyObject *tz)
Larry Hastings2623c8c2014-02-08 22:15:29 -08004252/*[clinic end generated code: output=583c5637e3c843fa input=80d09869c5267d00]*/
Tim Peters2a799bf2002-12-16 20:18:38 +00004253{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004254 PyObject *self;
Tim Peters2a799bf2002-12-16 20:18:38 +00004255
Larry Hastings31826802013-10-19 00:09:25 -07004256 /* Return best possible local time -- this isn't constrained by the
4257 * precision of a timestamp.
4258 */
4259 if (check_tzinfo_subclass(tz) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004260 return NULL;
Tim Peters10cadce2003-01-23 19:58:02 +00004261
Larry Hastings5c661892014-01-24 06:17:25 -08004262 self = datetime_best_possible((PyObject *)type,
Larry Hastings31826802013-10-19 00:09:25 -07004263 tz == Py_None ? localtime : gmtime,
4264 tz);
4265 if (self != NULL && tz != Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004266 /* Convert UTC to tzinfo's zone. */
4267 PyObject *temp = self;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02004268
Larry Hastings31826802013-10-19 00:09:25 -07004269 self = _PyObject_CallMethodId(tz, &PyId_fromutc, "O", self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004270 Py_DECREF(temp);
4271 }
4272 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00004273}
4274
Tim Petersa9bc1682003-01-11 03:39:11 +00004275/* Return best possible UTC time -- this isn't constrained by the
4276 * precision of a timestamp.
4277 */
4278static PyObject *
4279datetime_utcnow(PyObject *cls, PyObject *dummy)
4280{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004281 return datetime_best_possible(cls, gmtime, Py_None);
Tim Petersa9bc1682003-01-11 03:39:11 +00004282}
4283
Tim Peters2a799bf2002-12-16 20:18:38 +00004284/* Return new local datetime from timestamp (Python timestamp -- a double). */
4285static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004286datetime_fromtimestamp(PyObject *cls, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00004287{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004288 PyObject *self;
Victor Stinner511491a2015-09-18 14:42:05 +02004289 double timestamp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004290 PyObject *tzinfo = Py_None;
4291 static char *keywords[] = {"timestamp", "tz", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00004292
Victor Stinner511491a2015-09-18 14:42:05 +02004293 if (! PyArg_ParseTupleAndKeywords(args, kw, "d|O:fromtimestamp",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004294 keywords, &timestamp, &tzinfo))
4295 return NULL;
4296 if (check_tzinfo_subclass(tzinfo) < 0)
4297 return NULL;
Tim Peters2a44a8d2003-01-23 20:53:10 +00004298
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004299 self = datetime_from_timestamp(cls,
4300 tzinfo == Py_None ? localtime : gmtime,
4301 timestamp,
4302 tzinfo);
4303 if (self != NULL && tzinfo != Py_None) {
4304 /* Convert UTC to tzinfo's zone. */
4305 PyObject *temp = self;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02004306
4307 self = _PyObject_CallMethodId(tzinfo, &PyId_fromutc, "O", self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004308 Py_DECREF(temp);
4309 }
4310 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00004311}
4312
Tim Petersa9bc1682003-01-11 03:39:11 +00004313/* Return new UTC datetime from timestamp (Python timestamp -- a double). */
4314static PyObject *
4315datetime_utcfromtimestamp(PyObject *cls, PyObject *args)
4316{
Victor Stinner511491a2015-09-18 14:42:05 +02004317 double timestamp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004318 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004319
Victor Stinner511491a2015-09-18 14:42:05 +02004320 if (PyArg_ParseTuple(args, "d:utcfromtimestamp", &timestamp))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004321 result = datetime_from_timestamp(cls, gmtime, timestamp,
4322 Py_None);
4323 return result;
Tim Petersa9bc1682003-01-11 03:39:11 +00004324}
4325
Alexander Belopolskyca94f552010-06-17 18:30:34 +00004326/* Return new datetime from _strptime.strptime_datetime(). */
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004327static PyObject *
4328datetime_strptime(PyObject *cls, PyObject *args)
4329{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004330 static PyObject *module = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004331 PyObject *string, *format;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02004332 _Py_IDENTIFIER(_strptime_datetime);
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004333
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004334 if (!PyArg_ParseTuple(args, "UU:strptime", &string, &format))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004335 return NULL;
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004336
Alexander Belopolskyca94f552010-06-17 18:30:34 +00004337 if (module == NULL) {
4338 module = PyImport_ImportModuleNoBlock("_strptime");
Alexander Belopolsky311d2a92010-06-28 14:36:55 +00004339 if (module == NULL)
Alexander Belopolskyca94f552010-06-17 18:30:34 +00004340 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004341 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02004342 return _PyObject_CallMethodId(module, &PyId__strptime_datetime, "OOO",
4343 cls, string, format);
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004344}
4345
Tim Petersa9bc1682003-01-11 03:39:11 +00004346/* Return new datetime from date/datetime and time arguments. */
4347static PyObject *
4348datetime_combine(PyObject *cls, PyObject *args, PyObject *kw)
4349{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004350 static char *keywords[] = {"date", "time", NULL};
4351 PyObject *date;
4352 PyObject *time;
4353 PyObject *result = NULL;
Tim Petersa9bc1682003-01-11 03:39:11 +00004354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004355 if (PyArg_ParseTupleAndKeywords(args, kw, "O!O!:combine", keywords,
4356 &PyDateTime_DateType, &date,
4357 &PyDateTime_TimeType, &time)) {
4358 PyObject *tzinfo = Py_None;
Tim Petersa9bc1682003-01-11 03:39:11 +00004359
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004360 if (HASTZINFO(time))
4361 tzinfo = ((PyDateTime_Time *)time)->tzinfo;
4362 result = PyObject_CallFunction(cls, "iiiiiiiO",
4363 GET_YEAR(date),
4364 GET_MONTH(date),
4365 GET_DAY(date),
4366 TIME_GET_HOUR(time),
4367 TIME_GET_MINUTE(time),
4368 TIME_GET_SECOND(time),
4369 TIME_GET_MICROSECOND(time),
4370 tzinfo);
4371 }
4372 return result;
Tim Petersa9bc1682003-01-11 03:39:11 +00004373}
Tim Peters2a799bf2002-12-16 20:18:38 +00004374
4375/*
4376 * Destructor.
4377 */
4378
4379static void
Tim Petersa9bc1682003-01-11 03:39:11 +00004380datetime_dealloc(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004381{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004382 if (HASTZINFO(self)) {
4383 Py_XDECREF(self->tzinfo);
4384 }
4385 Py_TYPE(self)->tp_free((PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00004386}
4387
4388/*
4389 * Indirect access to tzinfo methods.
4390 */
4391
Tim Peters2a799bf2002-12-16 20:18:38 +00004392/* These are all METH_NOARGS, so don't need to check the arglist. */
4393static PyObject *
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004394datetime_utcoffset(PyObject *self, PyObject *unused) {
4395 return call_utcoffset(GET_DT_TZINFO(self), self);
Tim Peters2a799bf2002-12-16 20:18:38 +00004396}
4397
4398static PyObject *
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004399datetime_dst(PyObject *self, PyObject *unused) {
4400 return call_dst(GET_DT_TZINFO(self), self);
Tim Peters855fe882002-12-22 03:43:39 +00004401}
4402
4403static PyObject *
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004404datetime_tzname(PyObject *self, PyObject *unused) {
4405 return call_tzname(GET_DT_TZINFO(self), self);
Tim Peters2a799bf2002-12-16 20:18:38 +00004406}
4407
4408/*
Tim Petersa9bc1682003-01-11 03:39:11 +00004409 * datetime arithmetic.
Tim Peters2a799bf2002-12-16 20:18:38 +00004410 */
4411
Tim Petersa9bc1682003-01-11 03:39:11 +00004412/* factor must be 1 (to add) or -1 (to subtract). The result inherits
4413 * the tzinfo state of date.
Tim Peters2a799bf2002-12-16 20:18:38 +00004414 */
4415static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004416add_datetime_timedelta(PyDateTime_DateTime *date, PyDateTime_Delta *delta,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004417 int factor)
Tim Peters2a799bf2002-12-16 20:18:38 +00004418{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004419 /* Note that the C-level additions can't overflow, because of
4420 * invariant bounds on the member values.
4421 */
4422 int year = GET_YEAR(date);
4423 int month = GET_MONTH(date);
4424 int day = GET_DAY(date) + GET_TD_DAYS(delta) * factor;
4425 int hour = DATE_GET_HOUR(date);
4426 int minute = DATE_GET_MINUTE(date);
4427 int second = DATE_GET_SECOND(date) + GET_TD_SECONDS(delta) * factor;
4428 int microsecond = DATE_GET_MICROSECOND(date) +
4429 GET_TD_MICROSECONDS(delta) * factor;
Tim Peters2a799bf2002-12-16 20:18:38 +00004430
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004431 assert(factor == 1 || factor == -1);
4432 if (normalize_datetime(&year, &month, &day,
4433 &hour, &minute, &second, &microsecond) < 0)
4434 return NULL;
4435 else
4436 return new_datetime(year, month, day,
4437 hour, minute, second, microsecond,
4438 HASTZINFO(date) ? date->tzinfo : Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004439}
4440
4441static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004442datetime_add(PyObject *left, PyObject *right)
Tim Peters2a799bf2002-12-16 20:18:38 +00004443{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004444 if (PyDateTime_Check(left)) {
4445 /* datetime + ??? */
4446 if (PyDelta_Check(right))
4447 /* datetime + delta */
4448 return add_datetime_timedelta(
4449 (PyDateTime_DateTime *)left,
4450 (PyDateTime_Delta *)right,
4451 1);
4452 }
4453 else if (PyDelta_Check(left)) {
4454 /* delta + datetime */
4455 return add_datetime_timedelta((PyDateTime_DateTime *) right,
4456 (PyDateTime_Delta *) left,
4457 1);
4458 }
Brian Curtindfc80e32011-08-10 20:28:54 -05004459 Py_RETURN_NOTIMPLEMENTED;
Tim Peters2a799bf2002-12-16 20:18:38 +00004460}
4461
4462static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004463datetime_subtract(PyObject *left, PyObject *right)
Tim Peters2a799bf2002-12-16 20:18:38 +00004464{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004465 PyObject *result = Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00004466
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004467 if (PyDateTime_Check(left)) {
4468 /* datetime - ??? */
4469 if (PyDateTime_Check(right)) {
4470 /* datetime - datetime */
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004471 PyObject *offset1, *offset2, *offdiff = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004472 int delta_d, delta_s, delta_us;
Tim Peters2a799bf2002-12-16 20:18:38 +00004473
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004474 if (GET_DT_TZINFO(left) == GET_DT_TZINFO(right)) {
4475 offset2 = offset1 = Py_None;
4476 Py_INCREF(offset1);
4477 Py_INCREF(offset2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004478 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004479 else {
4480 offset1 = datetime_utcoffset(left, NULL);
4481 if (offset1 == NULL)
4482 return NULL;
4483 offset2 = datetime_utcoffset(right, NULL);
4484 if (offset2 == NULL) {
4485 Py_DECREF(offset1);
4486 return NULL;
4487 }
4488 if ((offset1 != Py_None) != (offset2 != Py_None)) {
4489 PyErr_SetString(PyExc_TypeError,
4490 "can't subtract offset-naive and "
4491 "offset-aware datetimes");
4492 Py_DECREF(offset1);
4493 Py_DECREF(offset2);
4494 return NULL;
4495 }
4496 }
4497 if ((offset1 != offset2) &&
4498 delta_cmp(offset1, offset2) != 0) {
4499 offdiff = delta_subtract(offset1, offset2);
4500 if (offdiff == NULL) {
4501 Py_DECREF(offset1);
4502 Py_DECREF(offset2);
4503 return NULL;
4504 }
4505 }
4506 Py_DECREF(offset1);
4507 Py_DECREF(offset2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004508 delta_d = ymd_to_ord(GET_YEAR(left),
4509 GET_MONTH(left),
4510 GET_DAY(left)) -
4511 ymd_to_ord(GET_YEAR(right),
4512 GET_MONTH(right),
4513 GET_DAY(right));
4514 /* These can't overflow, since the values are
4515 * normalized. At most this gives the number of
4516 * seconds in one day.
4517 */
4518 delta_s = (DATE_GET_HOUR(left) -
4519 DATE_GET_HOUR(right)) * 3600 +
4520 (DATE_GET_MINUTE(left) -
4521 DATE_GET_MINUTE(right)) * 60 +
4522 (DATE_GET_SECOND(left) -
4523 DATE_GET_SECOND(right));
4524 delta_us = DATE_GET_MICROSECOND(left) -
4525 DATE_GET_MICROSECOND(right);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004526 result = new_delta(delta_d, delta_s, delta_us, 1);
Victor Stinner70e11ac2013-11-08 00:50:58 +01004527 if (result == NULL)
4528 return NULL;
4529
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004530 if (offdiff != NULL) {
4531 PyObject *temp = result;
4532 result = delta_subtract(result, offdiff);
4533 Py_DECREF(temp);
4534 Py_DECREF(offdiff);
4535 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004536 }
4537 else if (PyDelta_Check(right)) {
4538 /* datetime - delta */
4539 result = add_datetime_timedelta(
4540 (PyDateTime_DateTime *)left,
4541 (PyDateTime_Delta *)right,
4542 -1);
4543 }
4544 }
Tim Peters2a799bf2002-12-16 20:18:38 +00004545
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004546 if (result == Py_NotImplemented)
4547 Py_INCREF(result);
4548 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00004549}
4550
4551/* Various ways to turn a datetime into a string. */
4552
4553static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004554datetime_repr(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004555{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004556 const char *type_name = Py_TYPE(self)->tp_name;
4557 PyObject *baserepr;
Tim Peters2a799bf2002-12-16 20:18:38 +00004558
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004559 if (DATE_GET_MICROSECOND(self)) {
4560 baserepr = PyUnicode_FromFormat(
4561 "%s(%d, %d, %d, %d, %d, %d, %d)",
4562 type_name,
4563 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4564 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4565 DATE_GET_SECOND(self),
4566 DATE_GET_MICROSECOND(self));
4567 }
4568 else if (DATE_GET_SECOND(self)) {
4569 baserepr = PyUnicode_FromFormat(
4570 "%s(%d, %d, %d, %d, %d, %d)",
4571 type_name,
4572 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4573 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4574 DATE_GET_SECOND(self));
4575 }
4576 else {
4577 baserepr = PyUnicode_FromFormat(
4578 "%s(%d, %d, %d, %d, %d)",
4579 type_name,
4580 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4581 DATE_GET_HOUR(self), DATE_GET_MINUTE(self));
4582 }
4583 if (baserepr == NULL || ! HASTZINFO(self))
4584 return baserepr;
4585 return append_keyword_tzinfo(baserepr, self->tzinfo);
Tim Peters2a799bf2002-12-16 20:18:38 +00004586}
4587
Tim Petersa9bc1682003-01-11 03:39:11 +00004588static PyObject *
4589datetime_str(PyDateTime_DateTime *self)
4590{
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02004591 return _PyObject_CallMethodId((PyObject *)self, &PyId_isoformat, "(s)", " ");
Tim Petersa9bc1682003-01-11 03:39:11 +00004592}
Tim Peters2a799bf2002-12-16 20:18:38 +00004593
4594static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004595datetime_isoformat(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00004596{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004597 int sep = 'T';
4598 static char *keywords[] = {"sep", NULL};
4599 char buffer[100];
4600 PyObject *result;
4601 int us = DATE_GET_MICROSECOND(self);
Tim Peters2a799bf2002-12-16 20:18:38 +00004602
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004603 if (!PyArg_ParseTupleAndKeywords(args, kw, "|C:isoformat", keywords, &sep))
4604 return NULL;
4605 if (us)
4606 result = PyUnicode_FromFormat("%04d-%02d-%02d%c%02d:%02d:%02d.%06d",
4607 GET_YEAR(self), GET_MONTH(self),
4608 GET_DAY(self), (int)sep,
4609 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4610 DATE_GET_SECOND(self), us);
4611 else
4612 result = PyUnicode_FromFormat("%04d-%02d-%02d%c%02d:%02d:%02d",
4613 GET_YEAR(self), GET_MONTH(self),
4614 GET_DAY(self), (int)sep,
4615 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4616 DATE_GET_SECOND(self));
Walter Dörwaldbafa1372007-05-31 17:50:48 +00004617
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004618 if (!result || !HASTZINFO(self))
4619 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00004620
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004621 /* We need to append the UTC offset. */
4622 if (format_utcoffset(buffer, sizeof(buffer), ":", self->tzinfo,
4623 (PyObject *)self) < 0) {
4624 Py_DECREF(result);
4625 return NULL;
4626 }
4627 PyUnicode_AppendAndDel(&result, PyUnicode_FromString(buffer));
4628 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00004629}
4630
Tim Petersa9bc1682003-01-11 03:39:11 +00004631static PyObject *
4632datetime_ctime(PyDateTime_DateTime *self)
4633{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004634 return format_ctime((PyDateTime_Date *)self,
4635 DATE_GET_HOUR(self),
4636 DATE_GET_MINUTE(self),
4637 DATE_GET_SECOND(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00004638}
4639
Tim Peters2a799bf2002-12-16 20:18:38 +00004640/* Miscellaneous methods. */
4641
Tim Petersa9bc1682003-01-11 03:39:11 +00004642static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00004643datetime_richcompare(PyObject *self, PyObject *other, int op)
Tim Petersa9bc1682003-01-11 03:39:11 +00004644{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004645 PyObject *result = NULL;
4646 PyObject *offset1, *offset2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004647 int diff;
Tim Petersa9bc1682003-01-11 03:39:11 +00004648
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004649 if (! PyDateTime_Check(other)) {
4650 if (PyDate_Check(other)) {
4651 /* Prevent invocation of date_richcompare. We want to
4652 return NotImplemented here to give the other object
4653 a chance. But since DateTime is a subclass of
4654 Date, if the other object is a Date, it would
4655 compute an ordering based on the date part alone,
4656 and we don't want that. So force unequal or
4657 uncomparable here in that case. */
4658 if (op == Py_EQ)
4659 Py_RETURN_FALSE;
4660 if (op == Py_NE)
4661 Py_RETURN_TRUE;
4662 return cmperror(self, other);
4663 }
Brian Curtindfc80e32011-08-10 20:28:54 -05004664 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004665 }
Tim Petersa9bc1682003-01-11 03:39:11 +00004666
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004667 if (GET_DT_TZINFO(self) == GET_DT_TZINFO(other)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004668 diff = memcmp(((PyDateTime_DateTime *)self)->data,
4669 ((PyDateTime_DateTime *)other)->data,
4670 _PyDateTime_DATETIME_DATASIZE);
4671 return diff_to_bool(diff, op);
4672 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004673 offset1 = datetime_utcoffset(self, NULL);
4674 if (offset1 == NULL)
4675 return NULL;
4676 offset2 = datetime_utcoffset(other, NULL);
4677 if (offset2 == NULL)
4678 goto done;
4679 /* If they're both naive, or both aware and have the same offsets,
4680 * we get off cheap. Note that if they're both naive, offset1 ==
4681 * offset2 == Py_None at this point.
4682 */
4683 if ((offset1 == offset2) ||
4684 (PyDelta_Check(offset1) && PyDelta_Check(offset2) &&
4685 delta_cmp(offset1, offset2) == 0)) {
4686 diff = memcmp(((PyDateTime_DateTime *)self)->data,
4687 ((PyDateTime_DateTime *)other)->data,
4688 _PyDateTime_DATETIME_DATASIZE);
4689 result = diff_to_bool(diff, op);
4690 }
4691 else if (offset1 != Py_None && offset2 != Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004692 PyDateTime_Delta *delta;
Tim Petersa9bc1682003-01-11 03:39:11 +00004693
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004694 assert(offset1 != offset2); /* else last "if" handled it */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004695 delta = (PyDateTime_Delta *)datetime_subtract((PyObject *)self,
4696 other);
4697 if (delta == NULL)
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004698 goto done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004699 diff = GET_TD_DAYS(delta);
4700 if (diff == 0)
4701 diff = GET_TD_SECONDS(delta) |
4702 GET_TD_MICROSECONDS(delta);
4703 Py_DECREF(delta);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004704 result = diff_to_bool(diff, op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004705 }
Alexander Belopolsky08313822012-06-15 20:19:47 -04004706 else if (op == Py_EQ) {
4707 result = Py_False;
4708 Py_INCREF(result);
4709 }
4710 else if (op == Py_NE) {
4711 result = Py_True;
4712 Py_INCREF(result);
4713 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004714 else {
4715 PyErr_SetString(PyExc_TypeError,
4716 "can't compare offset-naive and "
4717 "offset-aware datetimes");
4718 }
4719 done:
4720 Py_DECREF(offset1);
4721 Py_XDECREF(offset2);
4722 return result;
Tim Petersa9bc1682003-01-11 03:39:11 +00004723}
4724
Benjamin Peterson8f67d082010-10-17 20:54:53 +00004725static Py_hash_t
Tim Petersa9bc1682003-01-11 03:39:11 +00004726datetime_hash(PyDateTime_DateTime *self)
4727{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004728 if (self->hashcode == -1) {
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004729 PyObject *offset;
Tim Petersa9bc1682003-01-11 03:39:11 +00004730
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004731 offset = datetime_utcoffset((PyObject *)self, NULL);
4732
4733 if (offset == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004734 return -1;
Tim Petersa9bc1682003-01-11 03:39:11 +00004735
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004736 /* Reduce this to a hash of another object. */
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004737 if (offset == Py_None)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004738 self->hashcode = generic_hash(
4739 (unsigned char *)self->data, _PyDateTime_DATETIME_DATASIZE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004740 else {
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004741 PyObject *temp1, *temp2;
4742 int days, seconds;
Tim Petersa9bc1682003-01-11 03:39:11 +00004743
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004744 assert(HASTZINFO(self));
4745 days = ymd_to_ord(GET_YEAR(self),
4746 GET_MONTH(self),
4747 GET_DAY(self));
4748 seconds = DATE_GET_HOUR(self) * 3600 +
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004749 DATE_GET_MINUTE(self) * 60 +
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004750 DATE_GET_SECOND(self);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004751 temp1 = new_delta(days, seconds,
4752 DATE_GET_MICROSECOND(self),
4753 1);
4754 if (temp1 == NULL) {
4755 Py_DECREF(offset);
4756 return -1;
4757 }
4758 temp2 = delta_subtract(temp1, offset);
4759 Py_DECREF(temp1);
4760 if (temp2 == NULL) {
4761 Py_DECREF(offset);
4762 return -1;
4763 }
4764 self->hashcode = PyObject_Hash(temp2);
4765 Py_DECREF(temp2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004766 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004767 Py_DECREF(offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004768 }
4769 return self->hashcode;
Tim Petersa9bc1682003-01-11 03:39:11 +00004770}
Tim Peters2a799bf2002-12-16 20:18:38 +00004771
4772static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004773datetime_replace(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters12bf3392002-12-24 05:41:27 +00004774{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004775 PyObject *clone;
4776 PyObject *tuple;
4777 int y = GET_YEAR(self);
4778 int m = GET_MONTH(self);
4779 int d = GET_DAY(self);
4780 int hh = DATE_GET_HOUR(self);
4781 int mm = DATE_GET_MINUTE(self);
4782 int ss = DATE_GET_SECOND(self);
4783 int us = DATE_GET_MICROSECOND(self);
4784 PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
Tim Peters12bf3392002-12-24 05:41:27 +00004785
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004786 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiiiiO:replace",
4787 datetime_kws,
4788 &y, &m, &d, &hh, &mm, &ss, &us,
4789 &tzinfo))
4790 return NULL;
4791 tuple = Py_BuildValue("iiiiiiiO", y, m, d, hh, mm, ss, us, tzinfo);
4792 if (tuple == NULL)
4793 return NULL;
4794 clone = datetime_new(Py_TYPE(self), tuple, NULL);
4795 Py_DECREF(tuple);
4796 return clone;
Tim Peters12bf3392002-12-24 05:41:27 +00004797}
4798
4799static PyObject *
Alexander Belopolsky31227ca2012-06-22 13:23:21 -04004800local_timezone(PyDateTime_DateTime *utc_time)
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04004801{
4802 PyObject *result = NULL;
4803 struct tm *timep;
4804 time_t timestamp;
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04004805 PyObject *delta;
4806 PyObject *one_second;
4807 PyObject *seconds;
4808 PyObject *nameo = NULL;
4809 const char *zone = NULL;
4810
4811 delta = datetime_subtract((PyObject *)utc_time, PyDateTime_Epoch);
4812 if (delta == NULL)
4813 return NULL;
4814 one_second = new_delta(0, 1, 0, 0);
4815 if (one_second == NULL)
4816 goto error;
4817 seconds = divide_timedelta_timedelta((PyDateTime_Delta *)delta,
4818 (PyDateTime_Delta *)one_second);
4819 Py_DECREF(one_second);
4820 if (seconds == NULL)
4821 goto error;
4822 Py_DECREF(delta);
4823 timestamp = PyLong_AsLong(seconds);
4824 Py_DECREF(seconds);
4825 if (timestamp == -1 && PyErr_Occurred())
4826 return NULL;
4827 timep = localtime(&timestamp);
4828#ifdef HAVE_STRUCT_TM_TM_ZONE
Alexander Belopolsky93c9cd02012-06-22 16:04:19 -04004829 zone = timep->tm_zone;
4830 delta = new_delta(0, timep->tm_gmtoff, 0, 1);
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04004831#else /* HAVE_STRUCT_TM_TM_ZONE */
4832 {
4833 PyObject *local_time;
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04004834 local_time = new_datetime(timep->tm_year + 1900, timep->tm_mon + 1,
4835 timep->tm_mday, timep->tm_hour, timep->tm_min,
Alexander Belopolsky31227ca2012-06-22 13:23:21 -04004836 timep->tm_sec, DATE_GET_MICROSECOND(utc_time),
4837 utc_time->tzinfo);
4838 if (local_time == NULL)
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04004839 goto error;
Alexander Belopolsky93c9cd02012-06-22 16:04:19 -04004840 delta = datetime_subtract(local_time, (PyObject*)utc_time);
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04004841 /* XXX: before relying on tzname, we should compare delta
4842 to the offset implied by timezone/altzone */
4843 if (daylight && timep->tm_isdst >= 0)
4844 zone = tzname[timep->tm_isdst % 2];
4845 else
4846 zone = tzname[0];
4847 Py_DECREF(local_time);
4848 }
4849#endif /* HAVE_STRUCT_TM_TM_ZONE */
4850 if (zone != NULL) {
4851 nameo = PyUnicode_DecodeLocale(zone, "surrogateescape");
4852 if (nameo == NULL)
4853 goto error;
4854 }
4855 result = new_timezone(delta, nameo);
Christian Heimesb91ffaa2013-06-29 20:52:33 +02004856 Py_XDECREF(nameo);
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04004857 error:
4858 Py_DECREF(delta);
4859 return result;
4860}
4861
Alexander Belopolsky878054e2012-06-22 14:11:58 -04004862static PyDateTime_DateTime *
Tim Petersa9bc1682003-01-11 03:39:11 +00004863datetime_astimezone(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters80475bb2002-12-25 07:40:55 +00004864{
Alexander Belopolsky31227ca2012-06-22 13:23:21 -04004865 PyDateTime_DateTime *result;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004866 PyObject *offset;
4867 PyObject *temp;
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04004868 PyObject *tzinfo = Py_None;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004869 static char *keywords[] = {"tz", NULL};
Tim Peters80475bb2002-12-25 07:40:55 +00004870
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04004871 if (! PyArg_ParseTupleAndKeywords(args, kw, "|O:astimezone", keywords,
Raymond Hettinger5a2146a2014-07-25 14:59:48 -07004872 &tzinfo))
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04004873 return NULL;
4874
4875 if (check_tzinfo_subclass(tzinfo) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004876 return NULL;
Tim Peters80475bb2002-12-25 07:40:55 +00004877
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004878 if (!HASTZINFO(self) || self->tzinfo == Py_None)
4879 goto NeedAware;
Tim Peters521fc152002-12-31 17:36:56 +00004880
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004881 /* Conversion to self's own time zone is a NOP. */
4882 if (self->tzinfo == tzinfo) {
4883 Py_INCREF(self);
Alexander Belopolsky878054e2012-06-22 14:11:58 -04004884 return self;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004885 }
Tim Peters521fc152002-12-31 17:36:56 +00004886
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004887 /* Convert self to UTC. */
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004888 offset = datetime_utcoffset((PyObject *)self, NULL);
4889 if (offset == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004890 return NULL;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004891 if (offset == Py_None) {
4892 Py_DECREF(offset);
4893 NeedAware:
4894 PyErr_SetString(PyExc_ValueError, "astimezone() cannot be applied to "
4895 "a naive datetime");
4896 return NULL;
4897 }
Tim Petersf3615152003-01-01 21:51:37 +00004898
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004899 /* result = self - offset */
Alexander Belopolsky31227ca2012-06-22 13:23:21 -04004900 result = (PyDateTime_DateTime *)add_datetime_timedelta(self,
4901 (PyDateTime_Delta *)offset, -1);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004902 Py_DECREF(offset);
4903 if (result == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004904 return NULL;
Tim Peters52dcce22003-01-23 16:36:11 +00004905
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004906 /* Attach new tzinfo and let fromutc() do the rest. */
Alexander Belopolsky31227ca2012-06-22 13:23:21 -04004907 temp = result->tzinfo;
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04004908 if (tzinfo == Py_None) {
4909 tzinfo = local_timezone(result);
4910 if (tzinfo == NULL) {
4911 Py_DECREF(result);
4912 return NULL;
4913 }
4914 }
4915 else
4916 Py_INCREF(tzinfo);
Alexander Belopolsky31227ca2012-06-22 13:23:21 -04004917 result->tzinfo = tzinfo;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004918 Py_DECREF(temp);
Tim Peters52dcce22003-01-23 16:36:11 +00004919
Alexander Belopolsky31227ca2012-06-22 13:23:21 -04004920 temp = (PyObject *)result;
Alexander Belopolsky878054e2012-06-22 14:11:58 -04004921 result = (PyDateTime_DateTime *)
4922 _PyObject_CallMethodId(tzinfo, &PyId_fromutc, "O", temp);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004923 Py_DECREF(temp);
4924
Alexander Belopolsky878054e2012-06-22 14:11:58 -04004925 return result;
Tim Peters80475bb2002-12-25 07:40:55 +00004926}
4927
4928static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004929datetime_timetuple(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004930{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004931 int dstflag = -1;
Tim Peters2a799bf2002-12-16 20:18:38 +00004932
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004933 if (HASTZINFO(self) && self->tzinfo != Py_None) {
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004934 PyObject * dst;
Tim Peters2a799bf2002-12-16 20:18:38 +00004935
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004936 dst = call_dst(self->tzinfo, (PyObject *)self);
4937 if (dst == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004938 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004939
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004940 if (dst != Py_None)
4941 dstflag = delta_bool((PyDateTime_Delta *)dst);
4942 Py_DECREF(dst);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004943 }
4944 return build_struct_time(GET_YEAR(self),
4945 GET_MONTH(self),
4946 GET_DAY(self),
4947 DATE_GET_HOUR(self),
4948 DATE_GET_MINUTE(self),
4949 DATE_GET_SECOND(self),
4950 dstflag);
Tim Peters2a799bf2002-12-16 20:18:38 +00004951}
4952
4953static PyObject *
Alexander Belopolskya4415142012-06-08 12:33:09 -04004954datetime_timestamp(PyDateTime_DateTime *self)
4955{
4956 PyObject *result;
4957
4958 if (HASTZINFO(self) && self->tzinfo != Py_None) {
4959 PyObject *delta;
4960 delta = datetime_subtract((PyObject *)self, PyDateTime_Epoch);
4961 if (delta == NULL)
4962 return NULL;
4963 result = delta_total_seconds(delta);
4964 Py_DECREF(delta);
4965 }
4966 else {
4967 struct tm time;
4968 time_t timestamp;
4969 memset((void *) &time, '\0', sizeof(struct tm));
4970 time.tm_year = GET_YEAR(self) - 1900;
4971 time.tm_mon = GET_MONTH(self) - 1;
4972 time.tm_mday = GET_DAY(self);
4973 time.tm_hour = DATE_GET_HOUR(self);
4974 time.tm_min = DATE_GET_MINUTE(self);
4975 time.tm_sec = DATE_GET_SECOND(self);
4976 time.tm_wday = -1;
4977 time.tm_isdst = -1;
4978 timestamp = mktime(&time);
Victor Stinner93037492013-06-25 22:54:35 +02004979 if (timestamp == (time_t)(-1)
4980#ifndef _AIX
4981 /* Return value of -1 does not necessarily mean an error,
4982 * but tm_wday cannot remain set to -1 if mktime succeeded. */
4983 && time.tm_wday == -1
4984#else
4985 /* on AIX, tm_wday is always sets, even on error */
4986#endif
4987 )
4988 {
Alexander Belopolskya4415142012-06-08 12:33:09 -04004989 PyErr_SetString(PyExc_OverflowError,
4990 "timestamp out of range");
4991 return NULL;
4992 }
4993 result = PyFloat_FromDouble(timestamp + DATE_GET_MICROSECOND(self) / 1e6);
4994 }
4995 return result;
4996}
4997
4998static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004999datetime_getdate(PyDateTime_DateTime *self)
5000{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005001 return new_date(GET_YEAR(self),
5002 GET_MONTH(self),
5003 GET_DAY(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00005004}
5005
5006static PyObject *
5007datetime_gettime(PyDateTime_DateTime *self)
5008{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005009 return new_time(DATE_GET_HOUR(self),
5010 DATE_GET_MINUTE(self),
5011 DATE_GET_SECOND(self),
5012 DATE_GET_MICROSECOND(self),
5013 Py_None);
Tim Petersa9bc1682003-01-11 03:39:11 +00005014}
5015
5016static PyObject *
5017datetime_gettimetz(PyDateTime_DateTime *self)
5018{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005019 return new_time(DATE_GET_HOUR(self),
5020 DATE_GET_MINUTE(self),
5021 DATE_GET_SECOND(self),
5022 DATE_GET_MICROSECOND(self),
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005023 GET_DT_TZINFO(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00005024}
5025
5026static PyObject *
5027datetime_utctimetuple(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00005028{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005029 int y, m, d, hh, mm, ss;
5030 PyObject *tzinfo;
5031 PyDateTime_DateTime *utcself;
Tim Peters2a799bf2002-12-16 20:18:38 +00005032
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005033 tzinfo = GET_DT_TZINFO(self);
5034 if (tzinfo == Py_None) {
5035 utcself = self;
5036 Py_INCREF(utcself);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005037 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005038 else {
5039 PyObject *offset;
5040 offset = call_utcoffset(tzinfo, (PyObject *)self);
5041 if (offset == NULL)
Alexander Belopolsky75f94c22010-06-21 15:21:14 +00005042 return NULL;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005043 if (offset == Py_None) {
5044 Py_DECREF(offset);
5045 utcself = self;
5046 Py_INCREF(utcself);
5047 }
5048 else {
5049 utcself = (PyDateTime_DateTime *)add_datetime_timedelta(self,
5050 (PyDateTime_Delta *)offset, -1);
5051 Py_DECREF(offset);
5052 if (utcself == NULL)
5053 return NULL;
5054 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005055 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005056 y = GET_YEAR(utcself);
5057 m = GET_MONTH(utcself);
5058 d = GET_DAY(utcself);
5059 hh = DATE_GET_HOUR(utcself);
5060 mm = DATE_GET_MINUTE(utcself);
5061 ss = DATE_GET_SECOND(utcself);
5062
5063 Py_DECREF(utcself);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005064 return build_struct_time(y, m, d, hh, mm, ss, 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00005065}
5066
Tim Peters371935f2003-02-01 01:52:50 +00005067/* Pickle support, a simple use of __reduce__. */
Tim Peters33e0f382003-01-10 02:05:14 +00005068
Tim Petersa9bc1682003-01-11 03:39:11 +00005069/* Let basestate be the non-tzinfo data string.
Tim Peters2a799bf2002-12-16 20:18:38 +00005070 * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
5071 * So it's a tuple in any (non-error) case.
Tim Petersb57f8f02003-02-01 02:54:15 +00005072 * __getstate__ isn't exposed.
Tim Peters2a799bf2002-12-16 20:18:38 +00005073 */
5074static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00005075datetime_getstate(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00005076{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005077 PyObject *basestate;
5078 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00005079
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005080 basestate = PyBytes_FromStringAndSize((char *)self->data,
5081 _PyDateTime_DATETIME_DATASIZE);
5082 if (basestate != NULL) {
5083 if (! HASTZINFO(self) || self->tzinfo == Py_None)
5084 result = PyTuple_Pack(1, basestate);
5085 else
5086 result = PyTuple_Pack(2, basestate, self->tzinfo);
5087 Py_DECREF(basestate);
5088 }
5089 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00005090}
5091
5092static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00005093datetime_reduce(PyDateTime_DateTime *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00005094{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005095 return Py_BuildValue("(ON)", Py_TYPE(self), datetime_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00005096}
5097
Tim Petersa9bc1682003-01-11 03:39:11 +00005098static PyMethodDef datetime_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00005099
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005100 /* Class methods: */
Tim Peters2a799bf2002-12-16 20:18:38 +00005101
Larry Hastingsed4a1c52013-11-18 09:32:13 -08005102 DATETIME_DATETIME_NOW_METHODDEF
Tim Peters2a799bf2002-12-16 20:18:38 +00005103
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005104 {"utcnow", (PyCFunction)datetime_utcnow,
5105 METH_NOARGS | METH_CLASS,
5106 PyDoc_STR("Return a new datetime representing UTC day and time.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00005107
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005108 {"fromtimestamp", (PyCFunction)datetime_fromtimestamp,
5109 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
5110 PyDoc_STR("timestamp[, tz] -> tz's local time from POSIX timestamp.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00005111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005112 {"utcfromtimestamp", (PyCFunction)datetime_utcfromtimestamp,
5113 METH_VARARGS | METH_CLASS,
5114 PyDoc_STR("timestamp -> UTC datetime from a POSIX timestamp "
5115 "(like time.time()).")},
Tim Petersa9bc1682003-01-11 03:39:11 +00005116
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005117 {"strptime", (PyCFunction)datetime_strptime,
5118 METH_VARARGS | METH_CLASS,
5119 PyDoc_STR("string, format -> new datetime parsed from a string "
5120 "(like time.strptime()).")},
Skip Montanaro0af3ade2005-01-13 04:12:31 +00005121
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005122 {"combine", (PyCFunction)datetime_combine,
5123 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
5124 PyDoc_STR("date, time -> datetime with same date and time fields")},
Tim Petersa9bc1682003-01-11 03:39:11 +00005125
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005126 /* Instance methods: */
Guido van Rossum177e41a2003-01-30 22:06:23 +00005127
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005128 {"date", (PyCFunction)datetime_getdate, METH_NOARGS,
5129 PyDoc_STR("Return date object with same year, month and day.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00005130
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005131 {"time", (PyCFunction)datetime_gettime, METH_NOARGS,
5132 PyDoc_STR("Return time object with same time but with tzinfo=None.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00005133
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005134 {"timetz", (PyCFunction)datetime_gettimetz, METH_NOARGS,
5135 PyDoc_STR("Return time object with same time and tzinfo.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00005136
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005137 {"ctime", (PyCFunction)datetime_ctime, METH_NOARGS,
5138 PyDoc_STR("Return ctime() style string.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00005139
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005140 {"timetuple", (PyCFunction)datetime_timetuple, METH_NOARGS,
5141 PyDoc_STR("Return time tuple, compatible with time.localtime().")},
Tim Peters2a799bf2002-12-16 20:18:38 +00005142
Alexander Belopolskya4415142012-06-08 12:33:09 -04005143 {"timestamp", (PyCFunction)datetime_timestamp, METH_NOARGS,
5144 PyDoc_STR("Return POSIX timestamp as float.")},
5145
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005146 {"utctimetuple", (PyCFunction)datetime_utctimetuple, METH_NOARGS,
5147 PyDoc_STR("Return UTC time tuple, compatible with time.localtime().")},
Tim Peters2a799bf2002-12-16 20:18:38 +00005148
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005149 {"isoformat", (PyCFunction)datetime_isoformat, METH_VARARGS | METH_KEYWORDS,
5150 PyDoc_STR("[sep] -> string in ISO 8601 format, "
5151 "YYYY-MM-DDTHH:MM:SS[.mmmmmm][+HH:MM].\n\n"
5152 "sep is used to separate the year from the time, and "
5153 "defaults to 'T'.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00005154
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005155 {"utcoffset", (PyCFunction)datetime_utcoffset, METH_NOARGS,
5156 PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00005157
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005158 {"tzname", (PyCFunction)datetime_tzname, METH_NOARGS,
5159 PyDoc_STR("Return self.tzinfo.tzname(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00005160
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005161 {"dst", (PyCFunction)datetime_dst, METH_NOARGS,
5162 PyDoc_STR("Return self.tzinfo.dst(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00005163
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005164 {"replace", (PyCFunction)datetime_replace, METH_VARARGS | METH_KEYWORDS,
5165 PyDoc_STR("Return datetime with new specified fields.")},
Tim Peters12bf3392002-12-24 05:41:27 +00005166
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005167 {"astimezone", (PyCFunction)datetime_astimezone, METH_VARARGS | METH_KEYWORDS,
5168 PyDoc_STR("tz -> convert to local time in new timezone tz\n")},
Tim Peters80475bb2002-12-25 07:40:55 +00005169
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005170 {"__reduce__", (PyCFunction)datetime_reduce, METH_NOARGS,
5171 PyDoc_STR("__reduce__() -> (cls, state)")},
Guido van Rossum177e41a2003-01-30 22:06:23 +00005172
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005173 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00005174};
5175
Tim Petersa9bc1682003-01-11 03:39:11 +00005176static char datetime_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00005177PyDoc_STR("datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]])\n\
5178\n\
5179The year, month and day arguments are required. tzinfo may be None, or an\n\
Serhiy Storchaka95949422013-08-27 19:40:23 +03005180instance of a tzinfo subclass. The remaining arguments may be ints.\n");
Tim Peters2a799bf2002-12-16 20:18:38 +00005181
Tim Petersa9bc1682003-01-11 03:39:11 +00005182static PyNumberMethods datetime_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005183 datetime_add, /* nb_add */
5184 datetime_subtract, /* nb_subtract */
5185 0, /* nb_multiply */
5186 0, /* nb_remainder */
5187 0, /* nb_divmod */
5188 0, /* nb_power */
5189 0, /* nb_negative */
5190 0, /* nb_positive */
5191 0, /* nb_absolute */
5192 0, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00005193};
5194
Neal Norwitz227b5332006-03-22 09:28:35 +00005195static PyTypeObject PyDateTime_DateTimeType = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005196 PyVarObject_HEAD_INIT(NULL, 0)
5197 "datetime.datetime", /* tp_name */
5198 sizeof(PyDateTime_DateTime), /* tp_basicsize */
5199 0, /* tp_itemsize */
5200 (destructor)datetime_dealloc, /* tp_dealloc */
5201 0, /* tp_print */
5202 0, /* tp_getattr */
5203 0, /* tp_setattr */
5204 0, /* tp_reserved */
5205 (reprfunc)datetime_repr, /* tp_repr */
5206 &datetime_as_number, /* tp_as_number */
5207 0, /* tp_as_sequence */
5208 0, /* tp_as_mapping */
5209 (hashfunc)datetime_hash, /* tp_hash */
5210 0, /* tp_call */
5211 (reprfunc)datetime_str, /* tp_str */
5212 PyObject_GenericGetAttr, /* tp_getattro */
5213 0, /* tp_setattro */
5214 0, /* tp_as_buffer */
5215 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
5216 datetime_doc, /* tp_doc */
5217 0, /* tp_traverse */
5218 0, /* tp_clear */
5219 datetime_richcompare, /* tp_richcompare */
5220 0, /* tp_weaklistoffset */
5221 0, /* tp_iter */
5222 0, /* tp_iternext */
5223 datetime_methods, /* tp_methods */
5224 0, /* tp_members */
5225 datetime_getset, /* tp_getset */
5226 &PyDateTime_DateType, /* tp_base */
5227 0, /* tp_dict */
5228 0, /* tp_descr_get */
5229 0, /* tp_descr_set */
5230 0, /* tp_dictoffset */
5231 0, /* tp_init */
5232 datetime_alloc, /* tp_alloc */
5233 datetime_new, /* tp_new */
5234 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00005235};
5236
5237/* ---------------------------------------------------------------------------
5238 * Module methods and initialization.
5239 */
5240
5241static PyMethodDef module_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005242 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00005243};
5244
Tim Peters9ddf40b2004-06-20 22:41:32 +00005245/* C API. Clients get at this via PyDateTime_IMPORT, defined in
5246 * datetime.h.
5247 */
5248static PyDateTime_CAPI CAPI = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005249 &PyDateTime_DateType,
5250 &PyDateTime_DateTimeType,
5251 &PyDateTime_TimeType,
5252 &PyDateTime_DeltaType,
5253 &PyDateTime_TZInfoType,
5254 new_date_ex,
5255 new_datetime_ex,
5256 new_time_ex,
5257 new_delta_ex,
5258 datetime_fromtimestamp,
5259 date_fromtimestamp
Tim Peters9ddf40b2004-06-20 22:41:32 +00005260};
5261
5262
Martin v. Löwis1a214512008-06-11 05:26:20 +00005263
5264static struct PyModuleDef datetimemodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005265 PyModuleDef_HEAD_INIT,
Alexander Belopolskycf86e362010-07-23 19:25:47 +00005266 "_datetime",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005267 "Fast implementation of the datetime type.",
5268 -1,
5269 module_methods,
5270 NULL,
5271 NULL,
5272 NULL,
5273 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00005274};
5275
Tim Peters2a799bf2002-12-16 20:18:38 +00005276PyMODINIT_FUNC
Alexander Belopolskycf86e362010-07-23 19:25:47 +00005277PyInit__datetime(void)
Tim Peters2a799bf2002-12-16 20:18:38 +00005278{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005279 PyObject *m; /* a module object */
5280 PyObject *d; /* its dict */
5281 PyObject *x;
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00005282 PyObject *delta;
Tim Peters2a799bf2002-12-16 20:18:38 +00005283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005284 m = PyModule_Create(&datetimemodule);
5285 if (m == NULL)
5286 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00005287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005288 if (PyType_Ready(&PyDateTime_DateType) < 0)
5289 return NULL;
5290 if (PyType_Ready(&PyDateTime_DateTimeType) < 0)
5291 return NULL;
5292 if (PyType_Ready(&PyDateTime_DeltaType) < 0)
5293 return NULL;
5294 if (PyType_Ready(&PyDateTime_TimeType) < 0)
5295 return NULL;
5296 if (PyType_Ready(&PyDateTime_TZInfoType) < 0)
5297 return NULL;
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00005298 if (PyType_Ready(&PyDateTime_TimeZoneType) < 0)
5299 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00005300
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005301 /* timedelta values */
5302 d = PyDateTime_DeltaType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00005303
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005304 x = new_delta(0, 0, 1, 0);
5305 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
5306 return NULL;
5307 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005308
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005309 x = new_delta(-MAX_DELTA_DAYS, 0, 0, 0);
5310 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
5311 return NULL;
5312 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005313
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005314 x = new_delta(MAX_DELTA_DAYS, 24*3600-1, 1000000-1, 0);
5315 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
5316 return NULL;
5317 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005318
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005319 /* date values */
5320 d = PyDateTime_DateType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00005321
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005322 x = new_date(1, 1, 1);
5323 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
5324 return NULL;
5325 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005326
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005327 x = new_date(MAXYEAR, 12, 31);
5328 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
5329 return NULL;
5330 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005331
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005332 x = new_delta(1, 0, 0, 0);
5333 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
5334 return NULL;
5335 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005336
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005337 /* time values */
5338 d = PyDateTime_TimeType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00005339
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005340 x = new_time(0, 0, 0, 0, Py_None);
5341 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
5342 return NULL;
5343 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005344
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005345 x = new_time(23, 59, 59, 999999, Py_None);
5346 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
5347 return NULL;
5348 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005350 x = new_delta(0, 0, 1, 0);
5351 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
5352 return NULL;
5353 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005355 /* datetime values */
5356 d = PyDateTime_DateTimeType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00005357
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005358 x = new_datetime(1, 1, 1, 0, 0, 0, 0, Py_None);
5359 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
5360 return NULL;
5361 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005362
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005363 x = new_datetime(MAXYEAR, 12, 31, 23, 59, 59, 999999, Py_None);
5364 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
5365 return NULL;
5366 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005367
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005368 x = new_delta(0, 0, 1, 0);
5369 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
5370 return NULL;
5371 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005372
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00005373 /* timezone values */
5374 d = PyDateTime_TimeZoneType.tp_dict;
5375
5376 delta = new_delta(0, 0, 0, 0);
5377 if (delta == NULL)
5378 return NULL;
Alexander Belopolsky1bcbaab2010-10-14 17:03:51 +00005379 x = create_timezone(delta, NULL);
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00005380 Py_DECREF(delta);
5381 if (x == NULL || PyDict_SetItemString(d, "utc", x) < 0)
5382 return NULL;
Alexander Belopolskya11d8c02010-07-06 23:19:45 +00005383 PyDateTime_TimeZone_UTC = x;
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00005384
5385 delta = new_delta(-1, 60, 0, 1); /* -23:59 */
5386 if (delta == NULL)
5387 return NULL;
Alexander Belopolsky1bcbaab2010-10-14 17:03:51 +00005388 x = create_timezone(delta, NULL);
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00005389 Py_DECREF(delta);
5390 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
5391 return NULL;
5392 Py_DECREF(x);
5393
5394 delta = new_delta(0, (23 * 60 + 59) * 60, 0, 0); /* +23:59 */
5395 if (delta == NULL)
5396 return NULL;
Alexander Belopolsky1bcbaab2010-10-14 17:03:51 +00005397 x = create_timezone(delta, NULL);
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00005398 Py_DECREF(delta);
5399 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
5400 return NULL;
5401 Py_DECREF(x);
5402
Alexander Belopolskya4415142012-06-08 12:33:09 -04005403 /* Epoch */
5404 PyDateTime_Epoch = new_datetime(1970, 1, 1, 0, 0, 0, 0,
5405 PyDateTime_TimeZone_UTC);
5406 if (PyDateTime_Epoch == NULL)
5407 return NULL;
5408
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005409 /* module initialization */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +02005410 PyModule_AddIntMacro(m, MINYEAR);
5411 PyModule_AddIntMacro(m, MAXYEAR);
Tim Peters2a799bf2002-12-16 20:18:38 +00005412
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005413 Py_INCREF(&PyDateTime_DateType);
5414 PyModule_AddObject(m, "date", (PyObject *) &PyDateTime_DateType);
Tim Peters2a799bf2002-12-16 20:18:38 +00005415
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005416 Py_INCREF(&PyDateTime_DateTimeType);
5417 PyModule_AddObject(m, "datetime",
5418 (PyObject *)&PyDateTime_DateTimeType);
Tim Petersa9bc1682003-01-11 03:39:11 +00005419
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005420 Py_INCREF(&PyDateTime_TimeType);
5421 PyModule_AddObject(m, "time", (PyObject *) &PyDateTime_TimeType);
Tim Petersa9bc1682003-01-11 03:39:11 +00005422
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005423 Py_INCREF(&PyDateTime_DeltaType);
5424 PyModule_AddObject(m, "timedelta", (PyObject *) &PyDateTime_DeltaType);
Tim Peters2a799bf2002-12-16 20:18:38 +00005425
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005426 Py_INCREF(&PyDateTime_TZInfoType);
5427 PyModule_AddObject(m, "tzinfo", (PyObject *) &PyDateTime_TZInfoType);
Tim Peters2a799bf2002-12-16 20:18:38 +00005428
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00005429 Py_INCREF(&PyDateTime_TimeZoneType);
5430 PyModule_AddObject(m, "timezone", (PyObject *) &PyDateTime_TimeZoneType);
5431
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005432 x = PyCapsule_New(&CAPI, PyDateTime_CAPSULE_NAME, NULL);
5433 if (x == NULL)
5434 return NULL;
5435 PyModule_AddObject(m, "datetime_CAPI", x);
Tim Peters9ddf40b2004-06-20 22:41:32 +00005436
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005437 /* A 4-year cycle has an extra leap day over what we'd get from
5438 * pasting together 4 single years.
5439 */
5440 assert(DI4Y == 4 * 365 + 1);
5441 assert(DI4Y == days_before_year(4+1));
Tim Peters2a799bf2002-12-16 20:18:38 +00005442
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005443 /* Similarly, a 400-year cycle has an extra leap day over what we'd
5444 * get from pasting together 4 100-year cycles.
5445 */
5446 assert(DI400Y == 4 * DI100Y + 1);
5447 assert(DI400Y == days_before_year(400+1));
Tim Peters2a799bf2002-12-16 20:18:38 +00005448
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005449 /* OTOH, a 100-year cycle has one fewer leap day than we'd get from
5450 * pasting together 25 4-year cycles.
5451 */
5452 assert(DI100Y == 25 * DI4Y - 1);
5453 assert(DI100Y == days_before_year(100+1));
Tim Peters2a799bf2002-12-16 20:18:38 +00005454
Alexander Belopolsky790d2692013-08-04 14:51:35 -04005455 one = PyLong_FromLong(1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005456 us_per_ms = PyLong_FromLong(1000);
5457 us_per_second = PyLong_FromLong(1000000);
5458 us_per_minute = PyLong_FromLong(60000000);
5459 seconds_per_day = PyLong_FromLong(24 * 3600);
Alexander Belopolsky790d2692013-08-04 14:51:35 -04005460 if (one == NULL || us_per_ms == NULL || us_per_second == NULL ||
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005461 us_per_minute == NULL || seconds_per_day == NULL)
5462 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00005463
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005464 /* The rest are too big for 32-bit ints, but even
5465 * us_per_week fits in 40 bits, so doubles should be exact.
5466 */
5467 us_per_hour = PyLong_FromDouble(3600000000.0);
5468 us_per_day = PyLong_FromDouble(86400000000.0);
5469 us_per_week = PyLong_FromDouble(604800000000.0);
5470 if (us_per_hour == NULL || us_per_day == NULL || us_per_week == NULL)
5471 return NULL;
5472 return m;
Tim Peters2a799bf2002-12-16 20:18:38 +00005473}
Tim Petersf3615152003-01-01 21:51:37 +00005474
5475/* ---------------------------------------------------------------------------
Tim Petersa9bc1682003-01-11 03:39:11 +00005476Some time zone algebra. For a datetime x, let
Tim Petersf3615152003-01-01 21:51:37 +00005477 x.n = x stripped of its timezone -- its naive time.
5478 x.o = x.utcoffset(), and assuming that doesn't raise an exception or
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005479 return None
Tim Petersf3615152003-01-01 21:51:37 +00005480 x.d = x.dst(), and assuming that doesn't raise an exception or
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005481 return None
Tim Petersf3615152003-01-01 21:51:37 +00005482 x.s = x's standard offset, x.o - x.d
5483
5484Now some derived rules, where k is a duration (timedelta).
5485
54861. x.o = x.s + x.d
5487 This follows from the definition of x.s.
5488
Tim Petersc5dc4da2003-01-02 17:55:03 +000054892. If x and y have the same tzinfo member, x.s = y.s.
Tim Petersf3615152003-01-01 21:51:37 +00005490 This is actually a requirement, an assumption we need to make about
5491 sane tzinfo classes.
5492
54933. The naive UTC time corresponding to x is x.n - x.o.
5494 This is again a requirement for a sane tzinfo class.
5495
54964. (x+k).s = x.s
Tim Peters8bb5ad22003-01-24 02:44:45 +00005497 This follows from #2, and that datimetimetz+timedelta preserves tzinfo.
Tim Petersf3615152003-01-01 21:51:37 +00005498
Tim Petersc5dc4da2003-01-02 17:55:03 +000054995. (x+k).n = x.n + k
Tim Petersf3615152003-01-01 21:51:37 +00005500 Again follows from how arithmetic is defined.
5501
Tim Peters8bb5ad22003-01-24 02:44:45 +00005502Now we can explain tz.fromutc(x). Let's assume it's an interesting case
Tim Petersf3615152003-01-01 21:51:37 +00005503(meaning that the various tzinfo methods exist, and don't blow up or return
5504None when called).
5505
Tim Petersa9bc1682003-01-11 03:39:11 +00005506The function wants to return a datetime y with timezone tz, equivalent to x.
Tim Peters8bb5ad22003-01-24 02:44:45 +00005507x is already in UTC.
Tim Petersf3615152003-01-01 21:51:37 +00005508
5509By #3, we want
5510
Tim Peters8bb5ad22003-01-24 02:44:45 +00005511 y.n - y.o = x.n [1]
Tim Petersf3615152003-01-01 21:51:37 +00005512
5513The algorithm starts by attaching tz to x.n, and calling that y. So
5514x.n = y.n at the start. Then it wants to add a duration k to y, so that [1]
5515becomes true; in effect, we want to solve [2] for k:
5516
Tim Peters8bb5ad22003-01-24 02:44:45 +00005517 (y+k).n - (y+k).o = x.n [2]
Tim Petersf3615152003-01-01 21:51:37 +00005518
5519By #1, this is the same as
5520
Tim Peters8bb5ad22003-01-24 02:44:45 +00005521 (y+k).n - ((y+k).s + (y+k).d) = x.n [3]
Tim Petersf3615152003-01-01 21:51:37 +00005522
5523By #5, (y+k).n = y.n + k, which equals x.n + k because x.n=y.n at the start.
5524Substituting that into [3],
5525
Tim Peters8bb5ad22003-01-24 02:44:45 +00005526 x.n + k - (y+k).s - (y+k).d = x.n; the x.n terms cancel, leaving
5527 k - (y+k).s - (y+k).d = 0; rearranging,
5528 k = (y+k).s - (y+k).d; by #4, (y+k).s == y.s, so
5529 k = y.s - (y+k).d
Tim Petersf3615152003-01-01 21:51:37 +00005530
Tim Peters8bb5ad22003-01-24 02:44:45 +00005531On the RHS, (y+k).d can't be computed directly, but y.s can be, and we
5532approximate k by ignoring the (y+k).d term at first. Note that k can't be
5533very large, since all offset-returning methods return a duration of magnitude
5534less than 24 hours. For that reason, if y is firmly in std time, (y+k).d must
5535be 0, so ignoring it has no consequence then.
Tim Petersf3615152003-01-01 21:51:37 +00005536
5537In any case, the new value is
5538
Tim Peters8bb5ad22003-01-24 02:44:45 +00005539 z = y + y.s [4]
Tim Petersf3615152003-01-01 21:51:37 +00005540
Tim Peters8bb5ad22003-01-24 02:44:45 +00005541It's helpful to step back at look at [4] from a higher level: it's simply
5542mapping from UTC to tz's standard time.
Tim Petersc5dc4da2003-01-02 17:55:03 +00005543
5544At this point, if
5545
Tim Peters8bb5ad22003-01-24 02:44:45 +00005546 z.n - z.o = x.n [5]
Tim Petersc5dc4da2003-01-02 17:55:03 +00005547
5548we have an equivalent time, and are almost done. The insecurity here is
Tim Petersf3615152003-01-01 21:51:37 +00005549at the start of daylight time. Picture US Eastern for concreteness. The wall
5550time 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 +00005551sense then. The docs ask that an Eastern tzinfo class consider such a time to
5552be EDT (because it's "after 2"), which is a redundant spelling of 1:MM EST
5553on the day DST starts. We want to return the 1:MM EST spelling because that's
Tim Petersf3615152003-01-01 21:51:37 +00005554the only spelling that makes sense on the local wall clock.
5555
Tim Petersc5dc4da2003-01-02 17:55:03 +00005556In fact, if [5] holds at this point, we do have the standard-time spelling,
5557but that takes a bit of proof. We first prove a stronger result. What's the
5558difference between the LHS and RHS of [5]? Let
Tim Petersf3615152003-01-01 21:51:37 +00005559
Tim Peters8bb5ad22003-01-24 02:44:45 +00005560 diff = x.n - (z.n - z.o) [6]
Tim Petersf3615152003-01-01 21:51:37 +00005561
Tim Petersc5dc4da2003-01-02 17:55:03 +00005562Now
5563 z.n = by [4]
Tim Peters8bb5ad22003-01-24 02:44:45 +00005564 (y + y.s).n = by #5
5565 y.n + y.s = since y.n = x.n
5566 x.n + y.s = since z and y are have the same tzinfo member,
5567 y.s = z.s by #2
5568 x.n + z.s
Tim Petersf3615152003-01-01 21:51:37 +00005569
Tim Petersc5dc4da2003-01-02 17:55:03 +00005570Plugging that back into [6] gives
Tim Petersf3615152003-01-01 21:51:37 +00005571
Tim Petersc5dc4da2003-01-02 17:55:03 +00005572 diff =
Tim Peters8bb5ad22003-01-24 02:44:45 +00005573 x.n - ((x.n + z.s) - z.o) = expanding
5574 x.n - x.n - z.s + z.o = cancelling
5575 - z.s + z.o = by #2
Tim Petersc5dc4da2003-01-02 17:55:03 +00005576 z.d
Tim Petersf3615152003-01-01 21:51:37 +00005577
Tim Petersc5dc4da2003-01-02 17:55:03 +00005578So diff = z.d.
Tim Petersf3615152003-01-01 21:51:37 +00005579
Tim Petersc5dc4da2003-01-02 17:55:03 +00005580If [5] is true now, diff = 0, so z.d = 0 too, and we have the standard-time
Tim Peters8bb5ad22003-01-24 02:44:45 +00005581spelling we wanted in the endcase described above. We're done. Contrarily,
5582if z.d = 0, then we have a UTC equivalent, and are also done.
Tim Petersf3615152003-01-01 21:51:37 +00005583
Tim Petersc5dc4da2003-01-02 17:55:03 +00005584If [5] is not true now, diff = z.d != 0, and z.d is the offset we need to
5585add to z (in effect, z is in tz's standard time, and we need to shift the
Tim Peters8bb5ad22003-01-24 02:44:45 +00005586local clock into tz's daylight time).
Tim Petersf3615152003-01-01 21:51:37 +00005587
Tim Petersc5dc4da2003-01-02 17:55:03 +00005588Let
Tim Petersf3615152003-01-01 21:51:37 +00005589
Tim Peters4fede1a2003-01-04 00:26:59 +00005590 z' = z + z.d = z + diff [7]
Tim Petersc3bb26a2003-01-02 03:14:59 +00005591
Tim Peters4fede1a2003-01-04 00:26:59 +00005592and we can again ask whether
Tim Petersc3bb26a2003-01-02 03:14:59 +00005593
Tim Peters8bb5ad22003-01-24 02:44:45 +00005594 z'.n - z'.o = x.n [8]
Tim Petersc3bb26a2003-01-02 03:14:59 +00005595
Tim Peters8bb5ad22003-01-24 02:44:45 +00005596If so, we're done. If not, the tzinfo class is insane, according to the
5597assumptions we've made. This also requires a bit of proof. As before, let's
5598compute the difference between the LHS and RHS of [8] (and skipping some of
5599the justifications for the kinds of substitutions we've done several times
5600already):
Tim Peters4fede1a2003-01-04 00:26:59 +00005601
Tim Peters8bb5ad22003-01-24 02:44:45 +00005602 diff' = x.n - (z'.n - z'.o) = replacing z'.n via [7]
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005603 x.n - (z.n + diff - z'.o) = replacing diff via [6]
5604 x.n - (z.n + x.n - (z.n - z.o) - z'.o) =
5605 x.n - z.n - x.n + z.n - z.o + z'.o = cancel x.n
5606 - z.n + z.n - z.o + z'.o = cancel z.n
5607 - z.o + z'.o = #1 twice
5608 -z.s - z.d + z'.s + z'.d = z and z' have same tzinfo
5609 z'.d - z.d
Tim Peters4fede1a2003-01-04 00:26:59 +00005610
5611So 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 +00005612we've found the UTC-equivalent so are done. In fact, we stop with [7] and
5613return z', not bothering to compute z'.d.
Tim Peters4fede1a2003-01-04 00:26:59 +00005614
Tim Peters8bb5ad22003-01-24 02:44:45 +00005615How could z.d and z'd differ? z' = z + z.d [7], so merely moving z' by
5616a dst() offset, and starting *from* a time already in DST (we know z.d != 0),
5617would have to change the result dst() returns: we start in DST, and moving
5618a little further into it takes us out of DST.
Tim Peters4fede1a2003-01-04 00:26:59 +00005619
Tim Peters8bb5ad22003-01-24 02:44:45 +00005620There isn't a sane case where this can happen. The closest it gets is at
5621the end of DST, where there's an hour in UTC with no spelling in a hybrid
5622tzinfo class. In US Eastern, that's 5:MM UTC = 0:MM EST = 1:MM EDT. During
5623that hour, on an Eastern clock 1:MM is taken as being in standard time (6:MM
5624UTC) because the docs insist on that, but 0:MM is taken as being in daylight
5625time (4:MM UTC). There is no local time mapping to 5:MM UTC. The local
5626clock jumps from 1:59 back to 1:00 again, and repeats the 1:MM hour in
5627standard time. Since that's what the local clock *does*, we want to map both
5628UTC hours 5:MM and 6:MM to 1:MM Eastern. The result is ambiguous
Tim Peters4fede1a2003-01-04 00:26:59 +00005629in local time, but so it goes -- it's the way the local clock works.
5630
Tim Peters8bb5ad22003-01-24 02:44:45 +00005631When x = 5:MM UTC is the input to this algorithm, x.o=0, y.o=-5 and y.d=0,
5632so z=0:MM. z.d=60 (minutes) then, so [5] doesn't hold and we keep going.
5633z' = 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 +00005634(correctly) concludes that z' is not UTC-equivalent to x.
5635
5636Because we know z.d said z was in daylight time (else [5] would have held and
5637we would have stopped then), and we know z.d != z'.d (else [8] would have held
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +00005638and we would have stopped then), and there are only 2 possible values dst() can
Tim Peters4fede1a2003-01-04 00:26:59 +00005639return in Eastern, it follows that z'.d must be 0 (which it is in the example,
5640but the reasoning doesn't depend on the example -- it depends on there being
5641two possible dst() outcomes, one zero and the other non-zero). Therefore
Tim Peters8bb5ad22003-01-24 02:44:45 +00005642z' must be in standard time, and is the spelling we want in this case.
5643
5644Note again that z' is not UTC-equivalent as far as the hybrid tzinfo class is
5645concerned (because it takes z' as being in standard time rather than the
5646daylight time we intend here), but returning it gives the real-life "local
5647clock repeats an hour" behavior when mapping the "unspellable" UTC hour into
5648tz.
5649
5650When the input is 6:MM, z=1:MM and z.d=0, and we stop at once, again with
5651the 1:MM standard time spelling we want.
5652
5653So how can this break? One of the assumptions must be violated. Two
5654possibilities:
5655
56561) [2] effectively says that y.s is invariant across all y belong to a given
5657 time zone. This isn't true if, for political reasons or continental drift,
5658 a region decides to change its base offset from UTC.
5659
56602) There may be versions of "double daylight" time where the tail end of
5661 the analysis gives up a step too early. I haven't thought about that
5662 enough to say.
5663
5664In any case, it's clear that the default fromutc() is strong enough to handle
5665"almost all" time zones: so long as the standard offset is invariant, it
5666doesn't matter if daylight time transition points change from year to year, or
5667if daylight time is skipped in some years; it doesn't matter how large or
5668small dst() may get within its bounds; and it doesn't even matter if some
5669perverse time zone returns a negative dst()). So a breaking case must be
5670pretty bizarre, and a tzinfo subclass can override fromutc() if it is.
Tim Petersf3615152003-01-01 21:51:37 +00005671--------------------------------------------------------------------------- */