PageRenderTime 67ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/Modules/datetimemodule.c

http://unladen-swallow.googlecode.com/
C | 5082 lines | 3579 code | 588 blank | 915 comment | 811 complexity | b4ed2e757fdff99a36013356d213a16c MD5 | raw file
Possible License(s): 0BSD, BSD-3-Clause
  1. /* C implementation for the date/time type documented at
  2. * http://www.zope.org/Members/fdrake/DateTimeWiki/FrontPage
  3. */
  4. #define PY_SSIZE_T_CLEAN
  5. #include "Python.h"
  6. #include "modsupport.h"
  7. #include "structmember.h"
  8. #include <time.h>
  9. #include "timefuncs.h"
  10. /* Differentiate between building the core module and building extension
  11. * modules.
  12. */
  13. #ifndef Py_BUILD_CORE
  14. #define Py_BUILD_CORE
  15. #endif
  16. #include "datetime.h"
  17. #undef Py_BUILD_CORE
  18. /* We require that C int be at least 32 bits, and use int virtually
  19. * everywhere. In just a few cases we use a temp long, where a Python
  20. * API returns a C long. In such cases, we have to ensure that the
  21. * final result fits in a C int (this can be an issue on 64-bit boxes).
  22. */
  23. #if SIZEOF_INT < 4
  24. # error "datetime.c requires that C int have at least 32 bits"
  25. #endif
  26. #define MINYEAR 1
  27. #define MAXYEAR 9999
  28. /* Nine decimal digits is easy to communicate, and leaves enough room
  29. * so that two delta days can be added w/o fear of overflowing a signed
  30. * 32-bit int, and with plenty of room left over to absorb any possible
  31. * carries from adding seconds.
  32. */
  33. #define MAX_DELTA_DAYS 999999999
  34. /* Rename the long macros in datetime.h to more reasonable short names. */
  35. #define GET_YEAR PyDateTime_GET_YEAR
  36. #define GET_MONTH PyDateTime_GET_MONTH
  37. #define GET_DAY PyDateTime_GET_DAY
  38. #define DATE_GET_HOUR PyDateTime_DATE_GET_HOUR
  39. #define DATE_GET_MINUTE PyDateTime_DATE_GET_MINUTE
  40. #define DATE_GET_SECOND PyDateTime_DATE_GET_SECOND
  41. #define DATE_GET_MICROSECOND PyDateTime_DATE_GET_MICROSECOND
  42. /* Date accessors for date and datetime. */
  43. #define SET_YEAR(o, v) (((o)->data[0] = ((v) & 0xff00) >> 8), \
  44. ((o)->data[1] = ((v) & 0x00ff)))
  45. #define SET_MONTH(o, v) (PyDateTime_GET_MONTH(o) = (v))
  46. #define SET_DAY(o, v) (PyDateTime_GET_DAY(o) = (v))
  47. /* Date/Time accessors for datetime. */
  48. #define DATE_SET_HOUR(o, v) (PyDateTime_DATE_GET_HOUR(o) = (v))
  49. #define DATE_SET_MINUTE(o, v) (PyDateTime_DATE_GET_MINUTE(o) = (v))
  50. #define DATE_SET_SECOND(o, v) (PyDateTime_DATE_GET_SECOND(o) = (v))
  51. #define DATE_SET_MICROSECOND(o, v) \
  52. (((o)->data[7] = ((v) & 0xff0000) >> 16), \
  53. ((o)->data[8] = ((v) & 0x00ff00) >> 8), \
  54. ((o)->data[9] = ((v) & 0x0000ff)))
  55. /* Time accessors for time. */
  56. #define TIME_GET_HOUR PyDateTime_TIME_GET_HOUR
  57. #define TIME_GET_MINUTE PyDateTime_TIME_GET_MINUTE
  58. #define TIME_GET_SECOND PyDateTime_TIME_GET_SECOND
  59. #define TIME_GET_MICROSECOND PyDateTime_TIME_GET_MICROSECOND
  60. #define TIME_SET_HOUR(o, v) (PyDateTime_TIME_GET_HOUR(o) = (v))
  61. #define TIME_SET_MINUTE(o, v) (PyDateTime_TIME_GET_MINUTE(o) = (v))
  62. #define TIME_SET_SECOND(o, v) (PyDateTime_TIME_GET_SECOND(o) = (v))
  63. #define TIME_SET_MICROSECOND(o, v) \
  64. (((o)->data[3] = ((v) & 0xff0000) >> 16), \
  65. ((o)->data[4] = ((v) & 0x00ff00) >> 8), \
  66. ((o)->data[5] = ((v) & 0x0000ff)))
  67. /* Delta accessors for timedelta. */
  68. #define GET_TD_DAYS(o) (((PyDateTime_Delta *)(o))->days)
  69. #define GET_TD_SECONDS(o) (((PyDateTime_Delta *)(o))->seconds)
  70. #define GET_TD_MICROSECONDS(o) (((PyDateTime_Delta *)(o))->microseconds)
  71. #define SET_TD_DAYS(o, v) ((o)->days = (v))
  72. #define SET_TD_SECONDS(o, v) ((o)->seconds = (v))
  73. #define SET_TD_MICROSECONDS(o, v) ((o)->microseconds = (v))
  74. /* p is a pointer to a time or a datetime object; HASTZINFO(p) returns
  75. * p->hastzinfo.
  76. */
  77. #define HASTZINFO(p) (((_PyDateTime_BaseTZInfo *)(p))->hastzinfo)
  78. /* M is a char or int claiming to be a valid month. The macro is equivalent
  79. * to the two-sided Python test
  80. * 1 <= M <= 12
  81. */
  82. #define MONTH_IS_SANE(M) ((unsigned int)(M) - 1 < 12)
  83. /* Forward declarations. */
  84. static PyTypeObject PyDateTime_DateType;
  85. static PyTypeObject PyDateTime_DateTimeType;
  86. static PyTypeObject PyDateTime_DeltaType;
  87. static PyTypeObject PyDateTime_TimeType;
  88. static PyTypeObject PyDateTime_TZInfoType;
  89. /* ---------------------------------------------------------------------------
  90. * Math utilities.
  91. */
  92. /* k = i+j overflows iff k differs in sign from both inputs,
  93. * iff k^i has sign bit set and k^j has sign bit set,
  94. * iff (k^i)&(k^j) has sign bit set.
  95. */
  96. #define SIGNED_ADD_OVERFLOWED(RESULT, I, J) \
  97. ((((RESULT) ^ (I)) & ((RESULT) ^ (J))) < 0)
  98. /* Compute Python divmod(x, y), returning the quotient and storing the
  99. * remainder into *r. The quotient is the floor of x/y, and that's
  100. * the real point of this. C will probably truncate instead (C99
  101. * requires truncation; C89 left it implementation-defined).
  102. * Simplification: we *require* that y > 0 here. That's appropriate
  103. * for all the uses made of it. This simplifies the code and makes
  104. * the overflow case impossible (divmod(LONG_MIN, -1) is the only
  105. * overflow case).
  106. */
  107. static int
  108. divmod(int x, int y, int *r)
  109. {
  110. int quo;
  111. assert(y > 0);
  112. quo = x / y;
  113. *r = x - quo * y;
  114. if (*r < 0) {
  115. --quo;
  116. *r += y;
  117. }
  118. assert(0 <= *r && *r < y);
  119. return quo;
  120. }
  121. /* Round a double to the nearest long. |x| must be small enough to fit
  122. * in a C long; this is not checked.
  123. */
  124. static long
  125. round_to_long(double x)
  126. {
  127. if (x >= 0.0)
  128. x = floor(x + 0.5);
  129. else
  130. x = ceil(x - 0.5);
  131. return (long)x;
  132. }
  133. /* ---------------------------------------------------------------------------
  134. * General calendrical helper functions
  135. */
  136. /* For each month ordinal in 1..12, the number of days in that month,
  137. * and the number of days before that month in the same year. These
  138. * are correct for non-leap years only.
  139. */
  140. static int _days_in_month[] = {
  141. 0, /* unused; this vector uses 1-based indexing */
  142. 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
  143. };
  144. static int _days_before_month[] = {
  145. 0, /* unused; this vector uses 1-based indexing */
  146. 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
  147. };
  148. /* year -> 1 if leap year, else 0. */
  149. static int
  150. is_leap(int year)
  151. {
  152. /* Cast year to unsigned. The result is the same either way, but
  153. * C can generate faster code for unsigned mod than for signed
  154. * mod (especially for % 4 -- a good compiler should just grab
  155. * the last 2 bits when the LHS is unsigned).
  156. */
  157. const unsigned int ayear = (unsigned int)year;
  158. return ayear % 4 == 0 && (ayear % 100 != 0 || ayear % 400 == 0);
  159. }
  160. /* year, month -> number of days in that month in that year */
  161. static int
  162. days_in_month(int year, int month)
  163. {
  164. assert(month >= 1);
  165. assert(month <= 12);
  166. if (month == 2 && is_leap(year))
  167. return 29;
  168. else
  169. return _days_in_month[month];
  170. }
  171. /* year, month -> number of days in year preceeding first day of month */
  172. static int
  173. days_before_month(int year, int month)
  174. {
  175. int days;
  176. assert(month >= 1);
  177. assert(month <= 12);
  178. days = _days_before_month[month];
  179. if (month > 2 && is_leap(year))
  180. ++days;
  181. return days;
  182. }
  183. /* year -> number of days before January 1st of year. Remember that we
  184. * start with year 1, so days_before_year(1) == 0.
  185. */
  186. static int
  187. days_before_year(int year)
  188. {
  189. int y = year - 1;
  190. /* This is incorrect if year <= 0; we really want the floor
  191. * here. But so long as MINYEAR is 1, the smallest year this
  192. * can see is 0 (this can happen in some normalization endcases),
  193. * so we'll just special-case that.
  194. */
  195. assert (year >= 0);
  196. if (y >= 0)
  197. return y*365 + y/4 - y/100 + y/400;
  198. else {
  199. assert(y == -1);
  200. return -366;
  201. }
  202. }
  203. /* Number of days in 4, 100, and 400 year cycles. That these have
  204. * the correct values is asserted in the module init function.
  205. */
  206. #define DI4Y 1461 /* days_before_year(5); days in 4 years */
  207. #define DI100Y 36524 /* days_before_year(101); days in 100 years */
  208. #define DI400Y 146097 /* days_before_year(401); days in 400 years */
  209. /* ordinal -> year, month, day, considering 01-Jan-0001 as day 1. */
  210. static void
  211. ord_to_ymd(int ordinal, int *year, int *month, int *day)
  212. {
  213. int n, n1, n4, n100, n400, leapyear, preceding;
  214. /* ordinal is a 1-based index, starting at 1-Jan-1. The pattern of
  215. * leap years repeats exactly every 400 years. The basic strategy is
  216. * to find the closest 400-year boundary at or before ordinal, then
  217. * work with the offset from that boundary to ordinal. Life is much
  218. * clearer if we subtract 1 from ordinal first -- then the values
  219. * of ordinal at 400-year boundaries are exactly those divisible
  220. * by DI400Y:
  221. *
  222. * D M Y n n-1
  223. * -- --- ---- ---------- ----------------
  224. * 31 Dec -400 -DI400Y -DI400Y -1
  225. * 1 Jan -399 -DI400Y +1 -DI400Y 400-year boundary
  226. * ...
  227. * 30 Dec 000 -1 -2
  228. * 31 Dec 000 0 -1
  229. * 1 Jan 001 1 0 400-year boundary
  230. * 2 Jan 001 2 1
  231. * 3 Jan 001 3 2
  232. * ...
  233. * 31 Dec 400 DI400Y DI400Y -1
  234. * 1 Jan 401 DI400Y +1 DI400Y 400-year boundary
  235. */
  236. assert(ordinal >= 1);
  237. --ordinal;
  238. n400 = ordinal / DI400Y;
  239. n = ordinal % DI400Y;
  240. *year = n400 * 400 + 1;
  241. /* Now n is the (non-negative) offset, in days, from January 1 of
  242. * year, to the desired date. Now compute how many 100-year cycles
  243. * precede n.
  244. * Note that it's possible for n100 to equal 4! In that case 4 full
  245. * 100-year cycles precede the desired day, which implies the
  246. * desired day is December 31 at the end of a 400-year cycle.
  247. */
  248. n100 = n / DI100Y;
  249. n = n % DI100Y;
  250. /* Now compute how many 4-year cycles precede it. */
  251. n4 = n / DI4Y;
  252. n = n % DI4Y;
  253. /* And now how many single years. Again n1 can be 4, and again
  254. * meaning that the desired day is December 31 at the end of the
  255. * 4-year cycle.
  256. */
  257. n1 = n / 365;
  258. n = n % 365;
  259. *year += n100 * 100 + n4 * 4 + n1;
  260. if (n1 == 4 || n100 == 4) {
  261. assert(n == 0);
  262. *year -= 1;
  263. *month = 12;
  264. *day = 31;
  265. return;
  266. }
  267. /* Now the year is correct, and n is the offset from January 1. We
  268. * find the month via an estimate that's either exact or one too
  269. * large.
  270. */
  271. leapyear = n1 == 3 && (n4 != 24 || n100 == 3);
  272. assert(leapyear == is_leap(*year));
  273. *month = (n + 50) >> 5;
  274. preceding = (_days_before_month[*month] + (*month > 2 && leapyear));
  275. if (preceding > n) {
  276. /* estimate is too large */
  277. *month -= 1;
  278. preceding -= days_in_month(*year, *month);
  279. }
  280. n -= preceding;
  281. assert(0 <= n);
  282. assert(n < days_in_month(*year, *month));
  283. *day = n + 1;
  284. }
  285. /* year, month, day -> ordinal, considering 01-Jan-0001 as day 1. */
  286. static int
  287. ymd_to_ord(int year, int month, int day)
  288. {
  289. return days_before_year(year) + days_before_month(year, month) + day;
  290. }
  291. /* Day of week, where Monday==0, ..., Sunday==6. 1/1/1 was a Monday. */
  292. static int
  293. weekday(int year, int month, int day)
  294. {
  295. return (ymd_to_ord(year, month, day) + 6) % 7;
  296. }
  297. /* Ordinal of the Monday starting week 1 of the ISO year. Week 1 is the
  298. * first calendar week containing a Thursday.
  299. */
  300. static int
  301. iso_week1_monday(int year)
  302. {
  303. int first_day = ymd_to_ord(year, 1, 1); /* ord of 1/1 */
  304. /* 0 if 1/1 is a Monday, 1 if a Tue, etc. */
  305. int first_weekday = (first_day + 6) % 7;
  306. /* ordinal of closest Monday at or before 1/1 */
  307. int week1_monday = first_day - first_weekday;
  308. if (first_weekday > 3) /* if 1/1 was Fri, Sat, Sun */
  309. week1_monday += 7;
  310. return week1_monday;
  311. }
  312. /* ---------------------------------------------------------------------------
  313. * Range checkers.
  314. */
  315. /* Check that -MAX_DELTA_DAYS <= days <= MAX_DELTA_DAYS. If so, return 0.
  316. * If not, raise OverflowError and return -1.
  317. */
  318. static int
  319. check_delta_day_range(int days)
  320. {
  321. if (-MAX_DELTA_DAYS <= days && days <= MAX_DELTA_DAYS)
  322. return 0;
  323. PyErr_Format(PyExc_OverflowError,
  324. "days=%d; must have magnitude <= %d",
  325. days, MAX_DELTA_DAYS);
  326. return -1;
  327. }
  328. /* Check that date arguments are in range. Return 0 if they are. If they
  329. * aren't, raise ValueError and return -1.
  330. */
  331. static int
  332. check_date_args(int year, int month, int day)
  333. {
  334. if (year < MINYEAR || year > MAXYEAR) {
  335. PyErr_SetString(PyExc_ValueError,
  336. "year is out of range");
  337. return -1;
  338. }
  339. if (month < 1 || month > 12) {
  340. PyErr_SetString(PyExc_ValueError,
  341. "month must be in 1..12");
  342. return -1;
  343. }
  344. if (day < 1 || day > days_in_month(year, month)) {
  345. PyErr_SetString(PyExc_ValueError,
  346. "day is out of range for month");
  347. return -1;
  348. }
  349. return 0;
  350. }
  351. /* Check that time arguments are in range. Return 0 if they are. If they
  352. * aren't, raise ValueError and return -1.
  353. */
  354. static int
  355. check_time_args(int h, int m, int s, int us)
  356. {
  357. if (h < 0 || h > 23) {
  358. PyErr_SetString(PyExc_ValueError,
  359. "hour must be in 0..23");
  360. return -1;
  361. }
  362. if (m < 0 || m > 59) {
  363. PyErr_SetString(PyExc_ValueError,
  364. "minute must be in 0..59");
  365. return -1;
  366. }
  367. if (s < 0 || s > 59) {
  368. PyErr_SetString(PyExc_ValueError,
  369. "second must be in 0..59");
  370. return -1;
  371. }
  372. if (us < 0 || us > 999999) {
  373. PyErr_SetString(PyExc_ValueError,
  374. "microsecond must be in 0..999999");
  375. return -1;
  376. }
  377. return 0;
  378. }
  379. /* ---------------------------------------------------------------------------
  380. * Normalization utilities.
  381. */
  382. /* One step of a mixed-radix conversion. A "hi" unit is equivalent to
  383. * factor "lo" units. factor must be > 0. If *lo is less than 0, or
  384. * at least factor, enough of *lo is converted into "hi" units so that
  385. * 0 <= *lo < factor. The input values must be such that int overflow
  386. * is impossible.
  387. */
  388. static void
  389. normalize_pair(int *hi, int *lo, int factor)
  390. {
  391. assert(factor > 0);
  392. assert(lo != hi);
  393. if (*lo < 0 || *lo >= factor) {
  394. const int num_hi = divmod(*lo, factor, lo);
  395. const int new_hi = *hi + num_hi;
  396. assert(! SIGNED_ADD_OVERFLOWED(new_hi, *hi, num_hi));
  397. *hi = new_hi;
  398. }
  399. assert(0 <= *lo && *lo < factor);
  400. }
  401. /* Fiddle days (d), seconds (s), and microseconds (us) so that
  402. * 0 <= *s < 24*3600
  403. * 0 <= *us < 1000000
  404. * The input values must be such that the internals don't overflow.
  405. * The way this routine is used, we don't get close.
  406. */
  407. static void
  408. normalize_d_s_us(int *d, int *s, int *us)
  409. {
  410. if (*us < 0 || *us >= 1000000) {
  411. normalize_pair(s, us, 1000000);
  412. /* |s| can't be bigger than about
  413. * |original s| + |original us|/1000000 now.
  414. */
  415. }
  416. if (*s < 0 || *s >= 24*3600) {
  417. normalize_pair(d, s, 24*3600);
  418. /* |d| can't be bigger than about
  419. * |original d| +
  420. * (|original s| + |original us|/1000000) / (24*3600) now.
  421. */
  422. }
  423. assert(0 <= *s && *s < 24*3600);
  424. assert(0 <= *us && *us < 1000000);
  425. }
  426. /* Fiddle years (y), months (m), and days (d) so that
  427. * 1 <= *m <= 12
  428. * 1 <= *d <= days_in_month(*y, *m)
  429. * The input values must be such that the internals don't overflow.
  430. * The way this routine is used, we don't get close.
  431. */
  432. static void
  433. normalize_y_m_d(int *y, int *m, int *d)
  434. {
  435. int dim; /* # of days in month */
  436. /* This gets muddy: the proper range for day can't be determined
  437. * without knowing the correct month and year, but if day is, e.g.,
  438. * plus or minus a million, the current month and year values make
  439. * no sense (and may also be out of bounds themselves).
  440. * Saying 12 months == 1 year should be non-controversial.
  441. */
  442. if (*m < 1 || *m > 12) {
  443. --*m;
  444. normalize_pair(y, m, 12);
  445. ++*m;
  446. /* |y| can't be bigger than about
  447. * |original y| + |original m|/12 now.
  448. */
  449. }
  450. assert(1 <= *m && *m <= 12);
  451. /* Now only day can be out of bounds (year may also be out of bounds
  452. * for a datetime object, but we don't care about that here).
  453. * If day is out of bounds, what to do is arguable, but at least the
  454. * method here is principled and explainable.
  455. */
  456. dim = days_in_month(*y, *m);
  457. if (*d < 1 || *d > dim) {
  458. /* Move day-1 days from the first of the month. First try to
  459. * get off cheap if we're only one day out of range
  460. * (adjustments for timezone alone can't be worse than that).
  461. */
  462. if (*d == 0) {
  463. --*m;
  464. if (*m > 0)
  465. *d = days_in_month(*y, *m);
  466. else {
  467. --*y;
  468. *m = 12;
  469. *d = 31;
  470. }
  471. }
  472. else if (*d == dim + 1) {
  473. /* move forward a day */
  474. ++*m;
  475. *d = 1;
  476. if (*m > 12) {
  477. *m = 1;
  478. ++*y;
  479. }
  480. }
  481. else {
  482. int ordinal = ymd_to_ord(*y, *m, 1) +
  483. *d - 1;
  484. ord_to_ymd(ordinal, y, m, d);
  485. }
  486. }
  487. assert(*m > 0);
  488. assert(*d > 0);
  489. }
  490. /* Fiddle out-of-bounds months and days so that the result makes some kind
  491. * of sense. The parameters are both inputs and outputs. Returns < 0 on
  492. * failure, where failure means the adjusted year is out of bounds.
  493. */
  494. static int
  495. normalize_date(int *year, int *month, int *day)
  496. {
  497. int result;
  498. normalize_y_m_d(year, month, day);
  499. if (MINYEAR <= *year && *year <= MAXYEAR)
  500. result = 0;
  501. else {
  502. PyErr_SetString(PyExc_OverflowError,
  503. "date value out of range");
  504. result = -1;
  505. }
  506. return result;
  507. }
  508. /* Force all the datetime fields into range. The parameters are both
  509. * inputs and outputs. Returns < 0 on error.
  510. */
  511. static int
  512. normalize_datetime(int *year, int *month, int *day,
  513. int *hour, int *minute, int *second,
  514. int *microsecond)
  515. {
  516. normalize_pair(second, microsecond, 1000000);
  517. normalize_pair(minute, second, 60);
  518. normalize_pair(hour, minute, 60);
  519. normalize_pair(day, hour, 24);
  520. return normalize_date(year, month, day);
  521. }
  522. /* ---------------------------------------------------------------------------
  523. * Basic object allocation: tp_alloc implementations. These allocate
  524. * Python objects of the right size and type, and do the Python object-
  525. * initialization bit. If there's not enough memory, they return NULL after
  526. * setting MemoryError. All data members remain uninitialized trash.
  527. *
  528. * We abuse the tp_alloc "nitems" argument to communicate whether a tzinfo
  529. * member is needed. This is ugly, imprecise, and possibly insecure.
  530. * tp_basicsize for the time and datetime types is set to the size of the
  531. * struct that has room for the tzinfo member, so subclasses in Python will
  532. * allocate enough space for a tzinfo member whether or not one is actually
  533. * needed. That's the "ugly and imprecise" parts. The "possibly insecure"
  534. * part is that PyType_GenericAlloc() (which subclasses in Python end up
  535. * using) just happens today to effectively ignore the nitems argument
  536. * when tp_itemsize is 0, which it is for these type objects. If that
  537. * changes, perhaps the callers of tp_alloc slots in this file should
  538. * be changed to force a 0 nitems argument unless the type being allocated
  539. * is a base type implemented in this file (so that tp_alloc is time_alloc
  540. * or datetime_alloc below, which know about the nitems abuse).
  541. */
  542. static PyObject *
  543. time_alloc(PyTypeObject *type, Py_ssize_t aware)
  544. {
  545. PyObject *self;
  546. self = (PyObject *)
  547. PyObject_MALLOC(aware ?
  548. sizeof(PyDateTime_Time) :
  549. sizeof(_PyDateTime_BaseTime));
  550. if (self == NULL)
  551. return (PyObject *)PyErr_NoMemory();
  552. PyObject_INIT(self, type);
  553. return self;
  554. }
  555. static PyObject *
  556. datetime_alloc(PyTypeObject *type, Py_ssize_t aware)
  557. {
  558. PyObject *self;
  559. self = (PyObject *)
  560. PyObject_MALLOC(aware ?
  561. sizeof(PyDateTime_DateTime) :
  562. sizeof(_PyDateTime_BaseDateTime));
  563. if (self == NULL)
  564. return (PyObject *)PyErr_NoMemory();
  565. PyObject_INIT(self, type);
  566. return self;
  567. }
  568. /* ---------------------------------------------------------------------------
  569. * Helpers for setting object fields. These work on pointers to the
  570. * appropriate base class.
  571. */
  572. /* For date and datetime. */
  573. static void
  574. set_date_fields(PyDateTime_Date *self, int y, int m, int d)
  575. {
  576. self->hashcode = -1;
  577. SET_YEAR(self, y);
  578. SET_MONTH(self, m);
  579. SET_DAY(self, d);
  580. }
  581. /* ---------------------------------------------------------------------------
  582. * Create various objects, mostly without range checking.
  583. */
  584. /* Create a date instance with no range checking. */
  585. static PyObject *
  586. new_date_ex(int year, int month, int day, PyTypeObject *type)
  587. {
  588. PyDateTime_Date *self;
  589. self = (PyDateTime_Date *) (type->tp_alloc(type, 0));
  590. if (self != NULL)
  591. set_date_fields(self, year, month, day);
  592. return (PyObject *) self;
  593. }
  594. #define new_date(year, month, day) \
  595. new_date_ex(year, month, day, &PyDateTime_DateType)
  596. /* Create a datetime instance with no range checking. */
  597. static PyObject *
  598. new_datetime_ex(int year, int month, int day, int hour, int minute,
  599. int second, int usecond, PyObject *tzinfo, PyTypeObject *type)
  600. {
  601. PyDateTime_DateTime *self;
  602. char aware = tzinfo != Py_None;
  603. self = (PyDateTime_DateTime *) (type->tp_alloc(type, aware));
  604. if (self != NULL) {
  605. self->hastzinfo = aware;
  606. set_date_fields((PyDateTime_Date *)self, year, month, day);
  607. DATE_SET_HOUR(self, hour);
  608. DATE_SET_MINUTE(self, minute);
  609. DATE_SET_SECOND(self, second);
  610. DATE_SET_MICROSECOND(self, usecond);
  611. if (aware) {
  612. Py_INCREF(tzinfo);
  613. self->tzinfo = tzinfo;
  614. }
  615. }
  616. return (PyObject *)self;
  617. }
  618. #define new_datetime(y, m, d, hh, mm, ss, us, tzinfo) \
  619. new_datetime_ex(y, m, d, hh, mm, ss, us, tzinfo, \
  620. &PyDateTime_DateTimeType)
  621. /* Create a time instance with no range checking. */
  622. static PyObject *
  623. new_time_ex(int hour, int minute, int second, int usecond,
  624. PyObject *tzinfo, PyTypeObject *type)
  625. {
  626. PyDateTime_Time *self;
  627. char aware = tzinfo != Py_None;
  628. self = (PyDateTime_Time *) (type->tp_alloc(type, aware));
  629. if (self != NULL) {
  630. self->hastzinfo = aware;
  631. self->hashcode = -1;
  632. TIME_SET_HOUR(self, hour);
  633. TIME_SET_MINUTE(self, minute);
  634. TIME_SET_SECOND(self, second);
  635. TIME_SET_MICROSECOND(self, usecond);
  636. if (aware) {
  637. Py_INCREF(tzinfo);
  638. self->tzinfo = tzinfo;
  639. }
  640. }
  641. return (PyObject *)self;
  642. }
  643. #define new_time(hh, mm, ss, us, tzinfo) \
  644. new_time_ex(hh, mm, ss, us, tzinfo, &PyDateTime_TimeType)
  645. /* Create a timedelta instance. Normalize the members iff normalize is
  646. * true. Passing false is a speed optimization, if you know for sure
  647. * that seconds and microseconds are already in their proper ranges. In any
  648. * case, raises OverflowError and returns NULL if the normalized days is out
  649. * of range).
  650. */
  651. static PyObject *
  652. new_delta_ex(int days, int seconds, int microseconds, int normalize,
  653. PyTypeObject *type)
  654. {
  655. PyDateTime_Delta *self;
  656. if (normalize)
  657. normalize_d_s_us(&days, &seconds, &microseconds);
  658. assert(0 <= seconds && seconds < 24*3600);
  659. assert(0 <= microseconds && microseconds < 1000000);
  660. if (check_delta_day_range(days) < 0)
  661. return NULL;
  662. self = (PyDateTime_Delta *) (type->tp_alloc(type, 0));
  663. if (self != NULL) {
  664. self->hashcode = -1;
  665. SET_TD_DAYS(self, days);
  666. SET_TD_SECONDS(self, seconds);
  667. SET_TD_MICROSECONDS(self, microseconds);
  668. }
  669. return (PyObject *) self;
  670. }
  671. #define new_delta(d, s, us, normalize) \
  672. new_delta_ex(d, s, us, normalize, &PyDateTime_DeltaType)
  673. /* ---------------------------------------------------------------------------
  674. * tzinfo helpers.
  675. */
  676. /* Ensure that p is None or of a tzinfo subclass. Return 0 if OK; if not
  677. * raise TypeError and return -1.
  678. */
  679. static int
  680. check_tzinfo_subclass(PyObject *p)
  681. {
  682. if (p == Py_None || PyTZInfo_Check(p))
  683. return 0;
  684. PyErr_Format(PyExc_TypeError,
  685. "tzinfo argument must be None or of a tzinfo subclass, "
  686. "not type '%s'",
  687. Py_TYPE(p)->tp_name);
  688. return -1;
  689. }
  690. /* Return tzinfo.methname(tzinfoarg), without any checking of results.
  691. * If tzinfo is None, returns None.
  692. */
  693. static PyObject *
  694. call_tzinfo_method(PyObject *tzinfo, char *methname, PyObject *tzinfoarg)
  695. {
  696. PyObject *result;
  697. assert(tzinfo && methname && tzinfoarg);
  698. assert(check_tzinfo_subclass(tzinfo) >= 0);
  699. if (tzinfo == Py_None) {
  700. result = Py_None;
  701. Py_INCREF(result);
  702. }
  703. else
  704. result = PyObject_CallMethod(tzinfo, methname, "O", tzinfoarg);
  705. return result;
  706. }
  707. /* If self has a tzinfo member, return a BORROWED reference to it. Else
  708. * return NULL, which is NOT AN ERROR. There are no error returns here,
  709. * and the caller must not decref the result.
  710. */
  711. static PyObject *
  712. get_tzinfo_member(PyObject *self)
  713. {
  714. PyObject *tzinfo = NULL;
  715. if (PyDateTime_Check(self) && HASTZINFO(self))
  716. tzinfo = ((PyDateTime_DateTime *)self)->tzinfo;
  717. else if (PyTime_Check(self) && HASTZINFO(self))
  718. tzinfo = ((PyDateTime_Time *)self)->tzinfo;
  719. return tzinfo;
  720. }
  721. /* Call getattr(tzinfo, name)(tzinfoarg), and extract an int from the
  722. * result. tzinfo must be an instance of the tzinfo class. If the method
  723. * returns None, this returns 0 and sets *none to 1. If the method doesn't
  724. * return None or timedelta, TypeError is raised and this returns -1. If it
  725. * returnsa timedelta and the value is out of range or isn't a whole number
  726. * of minutes, ValueError is raised and this returns -1.
  727. * Else *none is set to 0 and the integer method result is returned.
  728. */
  729. static int
  730. call_utc_tzinfo_method(PyObject *tzinfo, char *name, PyObject *tzinfoarg,
  731. int *none)
  732. {
  733. PyObject *u;
  734. int result = -1;
  735. assert(tzinfo != NULL);
  736. assert(PyTZInfo_Check(tzinfo));
  737. assert(tzinfoarg != NULL);
  738. *none = 0;
  739. u = call_tzinfo_method(tzinfo, name, tzinfoarg);
  740. if (u == NULL)
  741. return -1;
  742. else if (u == Py_None) {
  743. result = 0;
  744. *none = 1;
  745. }
  746. else if (PyDelta_Check(u)) {
  747. const int days = GET_TD_DAYS(u);
  748. if (days < -1 || days > 0)
  749. result = 24*60; /* trigger ValueError below */
  750. else {
  751. /* next line can't overflow because we know days
  752. * is -1 or 0 now
  753. */
  754. int ss = days * 24 * 3600 + GET_TD_SECONDS(u);
  755. result = divmod(ss, 60, &ss);
  756. if (ss || GET_TD_MICROSECONDS(u)) {
  757. PyErr_Format(PyExc_ValueError,
  758. "tzinfo.%s() must return a "
  759. "whole number of minutes",
  760. name);
  761. result = -1;
  762. }
  763. }
  764. }
  765. else {
  766. PyErr_Format(PyExc_TypeError,
  767. "tzinfo.%s() must return None or "
  768. "timedelta, not '%s'",
  769. name, Py_TYPE(u)->tp_name);
  770. }
  771. Py_DECREF(u);
  772. if (result < -1439 || result > 1439) {
  773. PyErr_Format(PyExc_ValueError,
  774. "tzinfo.%s() returned %d; must be in "
  775. "-1439 .. 1439",
  776. name, result);
  777. result = -1;
  778. }
  779. return result;
  780. }
  781. /* Call tzinfo.utcoffset(tzinfoarg), and extract an integer from the
  782. * result. tzinfo must be an instance of the tzinfo class. If utcoffset()
  783. * returns None, call_utcoffset returns 0 and sets *none to 1. If uctoffset()
  784. * doesn't return None or timedelta, TypeError is raised and this returns -1.
  785. * If utcoffset() returns an invalid timedelta (out of range, or not a whole
  786. * # of minutes), ValueError is raised and this returns -1. Else *none is
  787. * set to 0 and the offset is returned (as int # of minutes east of UTC).
  788. */
  789. static int
  790. call_utcoffset(PyObject *tzinfo, PyObject *tzinfoarg, int *none)
  791. {
  792. return call_utc_tzinfo_method(tzinfo, "utcoffset", tzinfoarg, none);
  793. }
  794. /* Call tzinfo.name(tzinfoarg), and return the offset as a timedelta or None.
  795. */
  796. static PyObject *
  797. offset_as_timedelta(PyObject *tzinfo, char *name, PyObject *tzinfoarg) {
  798. PyObject *result;
  799. assert(tzinfo && name && tzinfoarg);
  800. if (tzinfo == Py_None) {
  801. result = Py_None;
  802. Py_INCREF(result);
  803. }
  804. else {
  805. int none;
  806. int offset = call_utc_tzinfo_method(tzinfo, name, tzinfoarg,
  807. &none);
  808. if (offset < 0 && PyErr_Occurred())
  809. return NULL;
  810. if (none) {
  811. result = Py_None;
  812. Py_INCREF(result);
  813. }
  814. else
  815. result = new_delta(0, offset * 60, 0, 1);
  816. }
  817. return result;
  818. }
  819. /* Call tzinfo.dst(tzinfoarg), and extract an integer from the
  820. * result. tzinfo must be an instance of the tzinfo class. If dst()
  821. * returns None, call_dst returns 0 and sets *none to 1. If dst()
  822. & doesn't return None or timedelta, TypeError is raised and this
  823. * returns -1. If dst() returns an invalid timedelta for a UTC offset,
  824. * ValueError is raised and this returns -1. Else *none is set to 0 and
  825. * the offset is returned (as an int # of minutes east of UTC).
  826. */
  827. static int
  828. call_dst(PyObject *tzinfo, PyObject *tzinfoarg, int *none)
  829. {
  830. return call_utc_tzinfo_method(tzinfo, "dst", tzinfoarg, none);
  831. }
  832. /* Call tzinfo.tzname(tzinfoarg), and return the result. tzinfo must be
  833. * an instance of the tzinfo class or None. If tzinfo isn't None, and
  834. * tzname() doesn't return None or a string, TypeError is raised and this
  835. * returns NULL.
  836. */
  837. static PyObject *
  838. call_tzname(PyObject *tzinfo, PyObject *tzinfoarg)
  839. {
  840. PyObject *result;
  841. assert(tzinfo != NULL);
  842. assert(check_tzinfo_subclass(tzinfo) >= 0);
  843. assert(tzinfoarg != NULL);
  844. if (tzinfo == Py_None) {
  845. result = Py_None;
  846. Py_INCREF(result);
  847. }
  848. else
  849. result = PyObject_CallMethod(tzinfo, "tzname", "O", tzinfoarg);
  850. if (result != NULL && result != Py_None && ! PyString_Check(result)) {
  851. PyErr_Format(PyExc_TypeError, "tzinfo.tzname() must "
  852. "return None or a string, not '%s'",
  853. Py_TYPE(result)->tp_name);
  854. Py_DECREF(result);
  855. result = NULL;
  856. }
  857. return result;
  858. }
  859. typedef enum {
  860. /* an exception has been set; the caller should pass it on */
  861. OFFSET_ERROR,
  862. /* type isn't date, datetime, or time subclass */
  863. OFFSET_UNKNOWN,
  864. /* date,
  865. * datetime with !hastzinfo
  866. * datetime with None tzinfo,
  867. * datetime where utcoffset() returns None
  868. * time with !hastzinfo
  869. * time with None tzinfo,
  870. * time where utcoffset() returns None
  871. */
  872. OFFSET_NAIVE,
  873. /* time or datetime where utcoffset() doesn't return None */
  874. OFFSET_AWARE
  875. } naivety;
  876. /* Classify an object as to whether it's naive or offset-aware. See
  877. * the "naivety" typedef for details. If the type is aware, *offset is set
  878. * to minutes east of UTC (as returned by the tzinfo.utcoffset() method).
  879. * If the type is offset-naive (or unknown, or error), *offset is set to 0.
  880. * tzinfoarg is the argument to pass to the tzinfo.utcoffset() method.
  881. */
  882. static naivety
  883. classify_utcoffset(PyObject *op, PyObject *tzinfoarg, int *offset)
  884. {
  885. int none;
  886. PyObject *tzinfo;
  887. assert(tzinfoarg != NULL);
  888. *offset = 0;
  889. tzinfo = get_tzinfo_member(op); /* NULL means no tzinfo, not error */
  890. if (tzinfo == Py_None)
  891. return OFFSET_NAIVE;
  892. if (tzinfo == NULL) {
  893. /* note that a datetime passes the PyDate_Check test */
  894. return (PyTime_Check(op) || PyDate_Check(op)) ?
  895. OFFSET_NAIVE : OFFSET_UNKNOWN;
  896. }
  897. *offset = call_utcoffset(tzinfo, tzinfoarg, &none);
  898. if (*offset == -1 && PyErr_Occurred())
  899. return OFFSET_ERROR;
  900. return none ? OFFSET_NAIVE : OFFSET_AWARE;
  901. }
  902. /* Classify two objects as to whether they're naive or offset-aware.
  903. * This isn't quite the same as calling classify_utcoffset() twice: for
  904. * binary operations (comparison and subtraction), we generally want to
  905. * ignore the tzinfo members if they're identical. This is by design,
  906. * so that results match "naive" expectations when mixing objects from a
  907. * single timezone. So in that case, this sets both offsets to 0 and
  908. * both naiveties to OFFSET_NAIVE.
  909. * The function returns 0 if everything's OK, and -1 on error.
  910. */
  911. static int
  912. classify_two_utcoffsets(PyObject *o1, int *offset1, naivety *n1,
  913. PyObject *tzinfoarg1,
  914. PyObject *o2, int *offset2, naivety *n2,
  915. PyObject *tzinfoarg2)
  916. {
  917. if (get_tzinfo_member(o1) == get_tzinfo_member(o2)) {
  918. *offset1 = *offset2 = 0;
  919. *n1 = *n2 = OFFSET_NAIVE;
  920. }
  921. else {
  922. *n1 = classify_utcoffset(o1, tzinfoarg1, offset1);
  923. if (*n1 == OFFSET_ERROR)
  924. return -1;
  925. *n2 = classify_utcoffset(o2, tzinfoarg2, offset2);
  926. if (*n2 == OFFSET_ERROR)
  927. return -1;
  928. }
  929. return 0;
  930. }
  931. /* repr is like "someclass(arg1, arg2)". If tzinfo isn't None,
  932. * stuff
  933. * ", tzinfo=" + repr(tzinfo)
  934. * before the closing ")".
  935. */
  936. static PyObject *
  937. append_keyword_tzinfo(PyObject *repr, PyObject *tzinfo)
  938. {
  939. PyObject *temp;
  940. assert(PyString_Check(repr));
  941. assert(tzinfo);
  942. if (tzinfo == Py_None)
  943. return repr;
  944. /* Get rid of the trailing ')'. */
  945. assert(PyString_AsString(repr)[PyString_Size(repr)-1] == ')');
  946. temp = PyString_FromStringAndSize(PyString_AsString(repr),
  947. PyString_Size(repr) - 1);
  948. Py_DECREF(repr);
  949. if (temp == NULL)
  950. return NULL;
  951. repr = temp;
  952. /* Append ", tzinfo=". */
  953. PyString_ConcatAndDel(&repr, PyString_FromString(", tzinfo="));
  954. /* Append repr(tzinfo). */
  955. PyString_ConcatAndDel(&repr, PyObject_Repr(tzinfo));
  956. /* Add a closing paren. */
  957. PyString_ConcatAndDel(&repr, PyString_FromString(")"));
  958. return repr;
  959. }
  960. /* ---------------------------------------------------------------------------
  961. * String format helpers.
  962. */
  963. static PyObject *
  964. format_ctime(PyDateTime_Date *date, int hours, int minutes, int seconds)
  965. {
  966. static const char *DayNames[] = {
  967. "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"
  968. };
  969. static const char *MonthNames[] = {
  970. "Jan", "Feb", "Mar", "Apr", "May", "Jun",
  971. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
  972. };
  973. char buffer[128];
  974. int wday = weekday(GET_YEAR(date), GET_MONTH(date), GET_DAY(date));
  975. PyOS_snprintf(buffer, sizeof(buffer), "%s %s %2d %02d:%02d:%02d %04d",
  976. DayNames[wday], MonthNames[GET_MONTH(date) - 1],
  977. GET_DAY(date), hours, minutes, seconds,
  978. GET_YEAR(date));
  979. return PyString_FromString(buffer);
  980. }
  981. /* Add an hours & minutes UTC offset string to buf. buf has no more than
  982. * buflen bytes remaining. The UTC offset is gotten by calling
  983. * tzinfo.uctoffset(tzinfoarg). If that returns None, \0 is stored into
  984. * *buf, and that's all. Else the returned value is checked for sanity (an
  985. * integer in range), and if that's OK it's converted to an hours & minutes
  986. * string of the form
  987. * sign HH sep MM
  988. * Returns 0 if everything is OK. If the return value from utcoffset() is
  989. * bogus, an appropriate exception is set and -1 is returned.
  990. */
  991. static int
  992. format_utcoffset(char *buf, size_t buflen, const char *sep,
  993. PyObject *tzinfo, PyObject *tzinfoarg)
  994. {
  995. int offset;
  996. int hours;
  997. int minutes;
  998. char sign;
  999. int none;
  1000. assert(buflen >= 1);
  1001. offset = call_utcoffset(tzinfo, tzinfoarg, &none);
  1002. if (offset == -1 && PyErr_Occurred())
  1003. return -1;
  1004. if (none) {
  1005. *buf = '\0';
  1006. return 0;
  1007. }
  1008. sign = '+';
  1009. if (offset < 0) {
  1010. sign = '-';
  1011. offset = - offset;
  1012. }
  1013. hours = divmod(offset, 60, &minutes);
  1014. PyOS_snprintf(buf, buflen, "%c%02d%s%02d", sign, hours, sep, minutes);
  1015. return 0;
  1016. }
  1017. static PyObject *
  1018. make_freplacement(PyObject *object)
  1019. {
  1020. char freplacement[64];
  1021. if (PyTime_Check(object))
  1022. sprintf(freplacement, "%06d", TIME_GET_MICROSECOND(object));
  1023. else if (PyDateTime_Check(object))
  1024. sprintf(freplacement, "%06d", DATE_GET_MICROSECOND(object));
  1025. else
  1026. sprintf(freplacement, "%06d", 0);
  1027. return PyString_FromStringAndSize(freplacement, strlen(freplacement));
  1028. }
  1029. /* I sure don't want to reproduce the strftime code from the time module,
  1030. * so this imports the module and calls it. All the hair is due to
  1031. * giving special meanings to the %z, %Z and %f format codes via a
  1032. * preprocessing step on the format string.
  1033. * tzinfoarg is the argument to pass to the object's tzinfo method, if
  1034. * needed.
  1035. */
  1036. static PyObject *
  1037. wrap_strftime(PyObject *object, const char *format, size_t format_len,
  1038. PyObject *timetuple, PyObject *tzinfoarg)
  1039. {
  1040. PyObject *result = NULL; /* guilty until proved innocent */
  1041. PyObject *zreplacement = NULL; /* py string, replacement for %z */
  1042. PyObject *Zreplacement = NULL; /* py string, replacement for %Z */
  1043. PyObject *freplacement = NULL; /* py string, replacement for %f */
  1044. const char *pin; /* pointer to next char in input format */
  1045. char ch; /* next char in input format */
  1046. PyObject *newfmt = NULL; /* py string, the output format */
  1047. char *pnew; /* pointer to available byte in output format */
  1048. size_t totalnew; /* number bytes total in output format buffer,
  1049. exclusive of trailing \0 */
  1050. size_t usednew; /* number bytes used so far in output format buffer */
  1051. const char *ptoappend; /* ptr to string to append to output buffer */
  1052. size_t ntoappend; /* # of bytes to append to output buffer */
  1053. assert(object && format && timetuple);
  1054. /* Give up if the year is before 1900.
  1055. * Python strftime() plays games with the year, and different
  1056. * games depending on whether envar PYTHON2K is set. This makes
  1057. * years before 1900 a nightmare, even if the platform strftime
  1058. * supports them (and not all do).
  1059. * We could get a lot farther here by avoiding Python's strftime
  1060. * wrapper and calling the C strftime() directly, but that isn't
  1061. * an option in the Python implementation of this module.
  1062. */
  1063. {
  1064. long year;
  1065. PyObject *pyyear = PySequence_GetItem(timetuple, 0);
  1066. if (pyyear == NULL) return NULL;
  1067. assert(PyInt_Check(pyyear));
  1068. year = PyInt_AsLong(pyyear);
  1069. Py_DECREF(pyyear);
  1070. if (year < 1900) {
  1071. PyErr_Format(PyExc_ValueError, "year=%ld is before "
  1072. "1900; the datetime strftime() "
  1073. "methods require year >= 1900",
  1074. year);
  1075. return NULL;
  1076. }
  1077. }
  1078. /* Scan the input format, looking for %z/%Z/%f escapes, building
  1079. * a new format. Since computing the replacements for those codes
  1080. * is expensive, don't unless they're actually used.
  1081. */
  1082. if (format_len > INT_MAX - 1) {
  1083. PyErr_NoMemory();
  1084. goto Done;
  1085. }
  1086. totalnew = format_len + 1; /* realistic if no %z/%Z/%f */
  1087. newfmt = PyString_FromStringAndSize(NULL, totalnew);
  1088. if (newfmt == NULL) goto Done;
  1089. pnew = PyString_AsString(newfmt);
  1090. usednew = 0;
  1091. pin = format;
  1092. while ((ch = *pin++) != '\0') {
  1093. if (ch != '%') {
  1094. ptoappend = pin - 1;
  1095. ntoappend = 1;
  1096. }
  1097. else if ((ch = *pin++) == '\0') {
  1098. /* There's a lone trailing %; doesn't make sense. */
  1099. PyErr_SetString(PyExc_ValueError, "strftime format "
  1100. "ends with raw %");
  1101. goto Done;
  1102. }
  1103. /* A % has been seen and ch is the character after it. */
  1104. else if (ch == 'z') {
  1105. if (zreplacement == NULL) {
  1106. /* format utcoffset */
  1107. char buf[100];
  1108. PyObject *tzinfo = get_tzinfo_member(object);
  1109. zreplacement = PyString_FromString("");
  1110. if (zreplacement == NULL) goto Done;
  1111. if (tzinfo != Py_None && tzinfo != NULL) {
  1112. assert(tzinfoarg != NULL);
  1113. if (format_utcoffset(buf,
  1114. sizeof(buf),
  1115. "",
  1116. tzinfo,
  1117. tzinfoarg) < 0)
  1118. goto Done;
  1119. Py_DECREF(zreplacement);
  1120. zreplacement = PyString_FromString(buf);
  1121. if (zreplacement == NULL) goto Done;
  1122. }
  1123. }
  1124. assert(zreplacement != NULL);
  1125. ptoappend = PyString_AS_STRING(zreplacement);
  1126. ntoappend = PyString_GET_SIZE(zreplacement);
  1127. }
  1128. else if (ch == 'Z') {
  1129. /* format tzname */
  1130. if (Zreplacement == NULL) {
  1131. PyObject *tzinfo = get_tzinfo_member(object);
  1132. Zreplacement = PyString_FromString("");
  1133. if (Zreplacement == NULL) goto Done;
  1134. if (tzinfo != Py_None && tzinfo != NULL) {
  1135. PyObject *temp;
  1136. assert(tzinfoarg != NULL);
  1137. temp = call_tzname(tzinfo, tzinfoarg);
  1138. if (temp == NULL) goto Done;
  1139. if (temp != Py_None) {
  1140. assert(PyString_Check(temp));
  1141. /* Since the tzname is getting
  1142. * stuffed into the format, we
  1143. * have to double any % signs
  1144. * so that strftime doesn't
  1145. * treat them as format codes.
  1146. */
  1147. Py_DECREF(Zreplacement);
  1148. Zreplacement = PyObject_CallMethod(
  1149. temp, "replace",
  1150. "ss", "%", "%%");
  1151. Py_DECREF(temp);
  1152. if (Zreplacement == NULL)
  1153. goto Done;
  1154. if (!PyString_Check(Zreplacement)) {
  1155. PyErr_SetString(PyExc_TypeError, "tzname.replace() did not return a string");
  1156. goto Done;
  1157. }
  1158. }
  1159. else
  1160. Py_DECREF(temp);
  1161. }
  1162. }
  1163. assert(Zreplacement != NULL);
  1164. ptoappend = PyString_AS_STRING(Zreplacement);
  1165. ntoappend = PyString_GET_SIZE(Zreplacement);
  1166. }
  1167. else if (ch == 'f') {
  1168. /* format microseconds */
  1169. if (freplacement == NULL) {
  1170. freplacement = make_freplacement(object);
  1171. if (freplacement == NULL)
  1172. goto Done;
  1173. }
  1174. assert(freplacement != NULL);
  1175. assert(PyString_Check(freplacement));
  1176. ptoappend = PyString_AS_STRING(freplacement);
  1177. ntoappend = PyString_GET_SIZE(freplacement);
  1178. }
  1179. else {
  1180. /* percent followed by neither z nor Z */
  1181. ptoappend = pin - 2;
  1182. ntoappend = 2;
  1183. }
  1184. /* Append the ntoappend chars starting at ptoappend to
  1185. * the new format.
  1186. */
  1187. assert(ptoappend != NULL);
  1188. assert(ntoappend >= 0);
  1189. if (ntoappend == 0)
  1190. continue;
  1191. while (usednew + ntoappend > totalnew) {
  1192. size_t bigger = totalnew << 1;
  1193. if ((bigger >> 1) != totalnew) { /* overflow */
  1194. PyErr_NoMemory();
  1195. goto Done;
  1196. }
  1197. if (_PyString_Resize(&newfmt, bigger) < 0)
  1198. goto Done;
  1199. totalnew = bigger;
  1200. pnew = PyString_AsString(newfmt) + usednew;
  1201. }
  1202. memcpy(pnew, ptoappend, ntoappend);
  1203. pnew += ntoappend;
  1204. usednew += ntoappend;
  1205. assert(usednew <= totalnew);
  1206. } /* end while() */
  1207. if (_PyString_Resize(&newfmt, usednew) < 0)
  1208. goto Done;
  1209. {
  1210. PyObject *time = PyImport_ImportModuleNoBlock("time");
  1211. if (time == NULL)
  1212. goto Done;
  1213. result = PyObject_CallMethod(time, "strftime", "OO",
  1214. newfmt, timetuple);
  1215. Py_DECREF(time);
  1216. }
  1217. Done:
  1218. Py_XDECREF(freplacement);
  1219. Py_XDECREF(zreplacement);
  1220. Py_XDECREF(Zreplacement);
  1221. Py_XDECREF(newfmt);
  1222. return result;
  1223. }
  1224. static char *
  1225. isoformat_date(PyDateTime_Date *dt, char buffer[], int bufflen)
  1226. {
  1227. int x;
  1228. x = PyOS_snprintf(buffer, bufflen,
  1229. "%04d-%02d-%02d",
  1230. GET_YEAR(dt), GET_MONTH(dt), GET_DAY(dt));
  1231. return buffer + x;
  1232. }
  1233. static void
  1234. isoformat_time(PyDateTime_DateTime *dt, char buffer[], int bufflen)
  1235. {
  1236. int us = DATE_GET_MICROSECOND(dt);
  1237. PyOS_snprintf(buffer, bufflen,
  1238. "%02d:%02d:%02d", /* 8 characters */
  1239. DATE_GET_HOUR(dt),
  1240. DATE_GET_MINUTE(dt),
  1241. DATE_GET_SECOND(dt));
  1242. if (us)
  1243. PyOS_snprintf(buffer + 8, bufflen - 8, ".%06d", us);
  1244. }
  1245. /* ---------------------------------------------------------------------------
  1246. * Wrap functions from the time module. These aren't directly available
  1247. * from C. Perhaps they should be.
  1248. */
  1249. /* Call time.time() and return its result (a Python float). */
  1250. static PyObject *
  1251. time_time(void)
  1252. {
  1253. PyObject *result = NULL;
  1254. PyObject *time = PyImport_ImportModuleNoBlock("time");
  1255. if (time != NULL) {
  1256. result = PyObject_CallMethod(time, "time", "()");
  1257. Py_DECREF(time);
  1258. }
  1259. return result;
  1260. }
  1261. /* Build a time.struct_time. The weekday and day number are automatically
  1262. * computed from the y,m,d args.
  1263. */
  1264. static PyObject *
  1265. build_struct_time(int y, int m, int d, int hh, int mm, int ss, int dstflag)
  1266. {
  1267. PyObject *time;
  1268. PyObject *result = NULL;
  1269. time = PyImport_ImportModuleNoBlock("time");
  1270. if (time != NULL) {
  1271. result = PyObject_CallMethod(time, "struct_time",
  1272. "((iiiiiiiii))",
  1273. y, m, d,
  1274. hh, mm, ss,
  1275. weekday(y, m, d),
  1276. days_before_month(y, m) + d,
  1277. dstflag);
  1278. Py_DECREF(time);
  1279. }
  1280. return result;
  1281. }
  1282. /* ---------------------------------------------------------------------------
  1283. * Miscellaneous helpers.
  1284. */
  1285. /* For obscure reasons, we need to use tp_richcompare instead of tp_compare.
  1286. * The comparisons here all most naturally compute a cmp()-like result.
  1287. * This little helper turns that into a bool result for rich comparisons.
  1288. */
  1289. static PyObject *
  1290. diff_to_bool(int diff, int op)
  1291. {
  1292. PyObject *result;
  1293. int istrue;
  1294. switch (op) {
  1295. case Py_EQ: istrue = diff == 0; break;
  1296. case Py_NE: istrue = diff != 0; break;
  1297. case Py_LE: istrue = diff <= 0; break;
  1298. case Py_GE: istrue = diff >= 0; break;
  1299. case Py_LT: istrue = diff < 0; break;
  1300. case Py_GT: istrue = diff > 0; break;
  1301. default:
  1302. assert(! "op unknown");
  1303. istrue = 0; /* To shut up compiler */
  1304. }
  1305. result = istrue ? Py_True : Py_False;
  1306. Py_INCREF(result);
  1307. return result;
  1308. }
  1309. /* Raises a "can't compare" TypeError and returns NULL. */
  1310. static PyObject *
  1311. cmperror(PyObject *a, PyObject *b)
  1312. {
  1313. PyErr_Format(PyExc_TypeError,
  1314. "can't compare %s to %s",
  1315. Py_TYPE(a)->tp_name, Py_TYPE(b)->tp_name);
  1316. return NULL;
  1317. }
  1318. /* ---------------------------------------------------------------------------
  1319. * Cached Python objects; these are set by the module init function.
  1320. */
  1321. /* Conversion factors. */
  1322. static PyObject *us_per_us = NULL; /* 1 */
  1323. static PyObject *us_per_ms = NULL; /* 1000 */
  1324. static PyObject *us_per_second = NULL; /* 1000000 */
  1325. static PyObject *us_per_minute = NULL; /* 1e6 * 60 as Python int */
  1326. static PyObject *us_per_hour = NULL; /* 1e6 * 3600 as Python long */
  1327. static PyObject *us_per_day = NULL; /* 1e6 * 3600 * 24 as Python long */
  1328. static PyObject *us_per_week = NULL; /* 1e6*3600*24*7 as Python long */
  1329. static PyObject *seconds_per_day = NULL; /* 3600*24 as Python int */
  1330. /* ---------------------------------------------------------------------------
  1331. * Class implementations.
  1332. */
  1333. /*
  1334. * PyDateTime_Delta implementation.
  1335. */
  1336. /* Convert a timedelta to a number of us,
  1337. * (24*3600*self.days + self.seconds)*1000000 + self.microseconds
  1338. * as a Python int or long.
  1339. * Doing mixed-radix arithmetic by hand instead is excruciating in C,
  1340. * due to ubiquitous overflow possibilities.
  1341. */
  1342. static PyObject *
  1343. delta_to_microseconds(PyDateTime_Delta *self)
  1344. {
  1345. PyObject *x1 = NULL;
  1346. PyObject *x2 = NULL;
  1347. PyObject *x3 = NULL;
  1348. PyObject *result = NULL;
  1349. x1 = PyInt_FromLong(GET_TD_DAYS(self));
  1350. if (x1 == NULL)
  1351. goto Done;
  1352. x2 = PyNumber_Multiply(x1, seconds_per_day); /* days in seconds */
  1353. if (x2 == NULL)
  1354. goto Done;
  1355. Py_DECREF(x1);
  1356. x1 = NULL;
  1357. /* x2 has days in seconds */
  1358. x1 = PyInt_FromLong(GET_TD_SECONDS(self)); /* seconds */
  1359. if (x1 == NULL)
  1360. goto Done;
  1361. x3 = PyNumber_Add(x1, x2); /* days and seconds in seconds */
  1362. if (x3 == NULL)
  1363. goto Done;
  1364. Py_DECREF(x1);
  1365. Py_DECREF(x2);
  1366. x1 = x2 = NULL;
  1367. /* x3 has days+seconds in seconds */
  1368. x1 = PyNumber_Multiply(x3, us_per_second); /* us */
  1369. if (x1 == NULL)
  1370. goto Done;
  1371. Py_DECREF(x3);
  1372. x3 = NULL;
  1373. /* x1 has days+seconds in us */
  1374. x2 = PyInt_FromLong(GET_TD_MICROSECONDS(self));
  1375. if (x2 == NULL)
  1376. goto Done;
  1377. result = PyNumber_Add(x1, x2);
  1378. Done:
  1379. Py_XDECREF(x1);
  1380. Py_XDECREF(x2);
  1381. Py_XDECREF(x3);
  1382. return result;
  1383. }
  1384. /* Convert a number of us (as a Python int or long) to a timedelta.
  1385. */
  1386. static PyObject *
  1387. microseconds_to_delta_ex(PyObject *pyus, PyTypeObject *type)
  1388. {
  1389. int us;
  1390. int s;
  1391. int d;
  1392. long temp;
  1393. PyObject *tuple = NULL;
  1394. PyObject *num = NULL;
  1395. PyObject *result = NULL;
  1396. tuple = PyNumber_Divmod(pyus, us_per_second);
  1397. if (tuple == NULL)
  1398. goto Done;
  1399. num = PyTuple_GetItem(tuple, 1); /* us */
  1400. if (num == NULL)
  1401. goto Done;
  1402. temp = PyLong_AsLong(num);
  1403. num = NULL;
  1404. if (temp == -1 && PyErr_Occurred())
  1405. goto Done;
  1406. assert(0 <= temp && temp < 1000000);
  1407. us = (int)temp;
  1408. if (us < 0) {
  1409. /* The divisor was positive, so this must be an error. */
  1410. assert(PyErr_Occurred());
  1411. goto Done;
  1412. }
  1413. num = PyTuple_GetItem(tuple, 0); /* leftover seconds */
  1414. if (num == NULL)
  1415. goto Done;
  1416. Py_INCREF(num);
  1417. Py_DECREF(tuple);
  1418. tuple = PyNumber_Divmod(num, seconds_per_day);
  1419. if (tuple == NULL)
  1420. goto Done;
  1421. Py_DECREF(num);
  1422. num = PyTuple_GetItem(tuple, 1); /* seconds */
  1423. if (num == NULL)
  1424. goto Done;
  1425. temp = PyLong_AsLong(num);
  1426. num = NULL;
  1427. if (temp == -1 && PyErr_Occurred())
  1428. goto Done;
  1429. assert(0 <= temp && temp < 24*3600);
  1430. s = (int)temp;
  1431. if (s < 0) {
  1432. /* The divisor was positive, so this must be an error. */
  1433. assert(PyErr_Occurred());
  1434. goto Done;
  1435. }
  1436. num = PyTuple_GetItem(tuple, 0); /* leftover days */
  1437. if (num == NULL)
  1438. goto Done;
  1439. Py_INCREF(num);
  1440. temp = PyLong_AsLong(num);
  1441. if (temp == -1 && PyErr_Occurred())
  1442. goto Done;
  1443. d = (int)temp;
  1444. if ((long)d != temp) {
  1445. PyErr_SetString(PyExc_OverflowError, "normalized days too "
  1446. "large to fit in a C int");
  1447. goto Done;
  1448. }
  1449. result = new_delta_ex(d, s, us, 0, type);
  1450. Done:
  1451. Py_XDECREF(tuple);
  1452. Py_XDECREF(num);
  1453. return result;
  1454. }
  1455. #define microseconds_to_delta(pymicros) \
  1456. microseconds_to_delta_ex(pymicros, &PyDateTime_DeltaType)
  1457. static PyObject *
  1458. multiply_int_timedelta(PyObject *intobj, PyDateTime_Delta *delta)
  1459. {
  1460. PyObject *pyus_in;
  1461. PyObject *pyus_out;
  1462. PyObject *result;
  1463. pyus_in = delta_to_microseconds(delta);
  1464. if (pyus_in == NULL)
  1465. return NULL;
  1466. pyus_out = PyNumber_Multiply(pyus_in, intobj);
  1467. Py_DECREF(pyus_in);
  1468. if (pyus_out == NULL)
  1469. return NULL;
  1470. result = microseconds_to_delta(pyus_out);
  1471. Py_DECREF(pyus_out);
  1472. return result;
  1473. }
  1474. static PyObject *
  1475. divide_timedelta_int(PyDateTime_Delta *delta, PyObject *intobj)
  1476. {
  1477. PyObject *pyus_in;
  1478. PyObject *pyus_out;
  1479. PyObject *result;
  1480. pyus_in = delta_to_microseconds(delta);
  1481. if (pyus_in == NULL)
  1482. return NULL;
  1483. pyus_out = PyNumber_FloorDivide(pyus_in, intobj);
  1484. Py_DECREF(pyus_in);
  1485. if (pyus_out == NULL)
  1486. return NULL;
  1487. result = microseconds_to_delta(pyus_out);
  1488. Py_DECREF(pyus_out);
  1489. return result;
  1490. }
  1491. static PyObject *
  1492. delta_add(PyObject *left, PyObject *right)
  1493. {
  1494. PyObject *result = Py_NotImplemented;
  1495. if (PyDelta_Check(left) && PyDelta_Check(right)) {
  1496. /* delta + delta */
  1497. /* The C-level additions can't overflow because of the
  1498. * invariant bounds.
  1499. */
  1500. int days = GET_TD_DAYS(left) + GET_TD_DAYS(right);
  1501. int seconds = GET_TD_SECONDS(left) + GET_TD_SECONDS(right);
  1502. int microseconds = GET_TD_MICROSECONDS(left) +
  1503. GET_TD_MICROSECONDS(right);
  1504. result = new_delta(days, seconds, microseconds, 1);
  1505. }
  1506. if (result == Py_NotImplemented)
  1507. Py_INCREF(result);
  1508. return result;
  1509. }
  1510. static PyObject *
  1511. delta_negative(PyDateTime_Delta *self)
  1512. {
  1513. return new_delta(-GET_TD_DAYS(self),
  1514. -GET_TD_SECONDS(self),
  1515. -GET_TD_MICROSECONDS(self),
  1516. 1);
  1517. }
  1518. static PyObject *
  1519. delta_positive(PyDateTime_Delta *self)
  1520. {
  1521. /* Could optimize this (by returning self) if this isn't a
  1522. * subclass -- but who uses unary + ? Approximately nobody.
  1523. */
  1524. return new_delta(GET_TD_DAYS(self),
  1525. GET_TD_SECONDS(self),
  1526. GET_TD_MICROSECONDS(self),
  1527. 0);
  1528. }
  1529. static PyObject *
  1530. delta_abs(PyDateTime_Delta *self)
  1531. {
  1532. PyObject *result;
  1533. assert(GET_TD_MICROSECONDS(self) >= 0);
  1534. assert(GET_TD_SECONDS(self) >= 0);
  1535. if (GET_TD_DAYS(self) < 0)
  1536. result = delta_negative(self);
  1537. else
  1538. result = delta_positive(self);
  1539. return result;
  1540. }
  1541. static PyObject *
  1542. delta_subtract(PyObject *left, PyObject *right)
  1543. {
  1544. PyObject *result = Py_NotImplemented;
  1545. if (PyDelta_Check(left) && PyDelta_Check(right)) {
  1546. /* delta - delta */
  1547. PyObject *minus_right = PyNumber_Negative(right);
  1548. if (minus_right) {
  1549. result = delta_add(left, minus_right);
  1550. Py_DECREF(minus_right);
  1551. }
  1552. else
  1553. result = NULL;
  1554. }
  1555. if (result == Py_NotImplemented)
  1556. Py_INCREF(result);
  1557. return result;
  1558. }
  1559. /* This is more natural as a tp_compare, but doesn't work then: for whatever
  1560. * reason, Python's try_3way_compare ignores tp_compare unless
  1561. * PyInstance_Check returns true, but these aren't old-style classes.
  1562. */
  1563. static PyObject *
  1564. delta_richcompare(PyDateTime_Delta *self, PyObject *other, int op)
  1565. {
  1566. int diff = 42; /* nonsense */
  1567. if (PyDelta_Check(other)) {
  1568. diff = GET_TD_DAYS(self) - GET_TD_DAYS(other);
  1569. if (diff == 0) {
  1570. diff = GET_TD_SECONDS(self) - GET_TD_SECONDS(other);
  1571. if (diff == 0)
  1572. diff = GET_TD_MICROSECONDS(self) -
  1573. GET_TD_MICROSECONDS(other);
  1574. }
  1575. }
  1576. else if (op == Py_EQ || op == Py_NE)
  1577. diff = 1; /* any non-zero value will do */
  1578. else /* stop this from falling back to address comparison */
  1579. return cmperror((PyObject *)self, other);
  1580. return diff_to_bool(diff, op);
  1581. }
  1582. static PyObject *delta_getstate(PyDateTime_Delta *self);
  1583. static long
  1584. delta_hash(PyDateTime_Delta *self)
  1585. {
  1586. if (self->hashcode == -1) {
  1587. PyObject *temp = delta_getstate(self);
  1588. if (temp != NULL) {
  1589. self->hashcode = PyObject_Hash(temp);
  1590. Py_DECREF(temp);
  1591. }
  1592. }
  1593. return self->hashcode;
  1594. }
  1595. static PyObject *
  1596. delta_multiply(PyObject *left, PyObject *right)
  1597. {
  1598. PyObject *result = Py_NotImplemented;
  1599. if (PyDelta_Check(left)) {
  1600. /* delta * ??? */
  1601. if (PyInt_Check(right) || PyLong_Check(right))
  1602. result = multiply_int_timedelta(right,
  1603. (PyDateTime_Delta *) left);
  1604. }
  1605. else if (PyInt_Check(left) || PyLong_Check(left))
  1606. result = multiply_int_timedelta(left,
  1607. (PyDateTime_Delta *) right);
  1608. if (result == Py_NotImplemented)
  1609. Py_INCREF(result);
  1610. return result;
  1611. }
  1612. static PyObject *
  1613. delta_divide(PyObject *left, PyObject *right)
  1614. {
  1615. PyObject *result = Py_NotImplemented;
  1616. if (PyDelta_Check(left)) {
  1617. /* delta * ??? */
  1618. if (PyInt_Check(right) || PyLong_Check(right))
  1619. result = divide_timedelta_int(
  1620. (PyDateTime_Delta *)left,
  1621. right);
  1622. }
  1623. if (result == Py_NotImplemented)
  1624. Py_INCREF(result);
  1625. return result;
  1626. }
  1627. /* Fold in the value of the tag ("seconds", "weeks", etc) component of a
  1628. * timedelta constructor. sofar is the # of microseconds accounted for
  1629. * so far, and there are factor microseconds per current unit, the number
  1630. * of which is given by num. num * factor is added to sofar in a
  1631. * numerically careful way, and that's the result. Any fractional
  1632. * microseconds left over (this can happen if num is a float type) are
  1633. * added into *leftover.
  1634. * Note that there are many ways this can give an error (NULL) return.
  1635. */
  1636. static PyObject *
  1637. accum(const char* tag, PyObject *sofar, PyObject *num, PyObject *factor,
  1638. double *leftover)
  1639. {
  1640. PyObject *prod;
  1641. PyObject *sum;
  1642. assert(num != NULL);
  1643. if (PyInt_Check(num) || PyLong_Check(num)) {
  1644. prod = PyNumber_Multiply(num, factor);
  1645. if (prod == NULL)
  1646. return NULL;
  1647. sum = PyNumber_Add(sofar, prod);
  1648. Py_DECREF(prod);
  1649. return sum;
  1650. }
  1651. if (PyFloat_Check(num)) {
  1652. double dnum;
  1653. double fracpart;
  1654. double intpart;
  1655. PyObject *x;
  1656. PyObject *y;
  1657. /* The Plan: decompose num into an integer part and a
  1658. * fractional part, num = intpart + fracpart.
  1659. * Then num * factor ==
  1660. * intpart * factor + fracpart * factor
  1661. * and the LHS can be computed exactly in long arithmetic.
  1662. * The RHS is again broken into an int part and frac part.
  1663. * and the frac part is added into *leftover.
  1664. */
  1665. dnum = PyFloat_AsDouble(num);
  1666. if (dnum == -1.0 && PyErr_Occurred())
  1667. return NULL;
  1668. fracpart = modf(dnum, &intpart);
  1669. x = PyLong_FromDouble(intpart);
  1670. if (x == NULL)
  1671. return NULL;
  1672. prod = PyNumber_Multiply(x, factor);
  1673. Py_DECREF(x);
  1674. if (prod == NULL)
  1675. return NULL;
  1676. sum = PyNumber_Add(sofar, prod);
  1677. Py_DECREF(prod);
  1678. if (sum == NULL)
  1679. return NULL;
  1680. if (fracpart == 0.0)
  1681. return sum;
  1682. /* So far we've lost no information. Dealing with the
  1683. * fractional part requires float arithmetic, and may
  1684. * lose a little info.
  1685. */
  1686. assert(PyInt_Check(factor) || PyLong_Check(factor));
  1687. if (PyInt_Check(factor))
  1688. dnum = (double)PyInt_AsLong(factor);
  1689. else
  1690. dnum = PyLong_AsDouble(factor);
  1691. dnum *= fracpart;
  1692. fracpart = modf(dnum, &intpart);
  1693. x = PyLong_FromDouble(intpart);
  1694. if (x == NULL) {
  1695. Py_DECREF(sum);
  1696. return NULL;
  1697. }
  1698. y = PyNumber_Add(sum, x);
  1699. Py_DECREF(sum);
  1700. Py_DECREF(x);
  1701. *leftover += fracpart;
  1702. return y;
  1703. }
  1704. PyErr_Format(PyExc_TypeError,
  1705. "unsupported type for timedelta %s component: %s",
  1706. tag, Py_TYPE(num)->tp_name);
  1707. return NULL;
  1708. }
  1709. static PyObject *
  1710. delta_new(PyTypeObject *type, PyObject *args, PyObject *kw)
  1711. {
  1712. PyObject *self = NULL;
  1713. /* Argument objects. */
  1714. PyObject *day = NULL;
  1715. PyObject *second = NULL;
  1716. PyObject *us = NULL;
  1717. PyObject *ms = NULL;
  1718. PyObject *minute = NULL;
  1719. PyObject *hour = NULL;
  1720. PyObject *week = NULL;
  1721. PyObject *x = NULL; /* running sum of microseconds */
  1722. PyObject *y = NULL; /* temp sum of microseconds */
  1723. double leftover_us = 0.0;
  1724. static char *keywords[] = {
  1725. "days", "seconds", "microseconds", "milliseconds",
  1726. "minutes", "hours", "weeks", NULL
  1727. };
  1728. if (PyArg_ParseTupleAndKeywords(args, kw, "|OOOOOOO:__new__",
  1729. keywords,
  1730. &day, &second, &us,
  1731. &ms, &minute, &hour, &week) == 0)
  1732. goto Done;
  1733. x = PyInt_FromLong(0);
  1734. if (x == NULL)
  1735. goto Done;
  1736. #define CLEANUP \
  1737. Py_DECREF(x); \
  1738. x = y; \
  1739. if (x == NULL) \
  1740. goto Done
  1741. if (us) {
  1742. y = accum("microseconds", x, us, us_per_us, &leftover_us);
  1743. CLEANUP;
  1744. }
  1745. if (ms) {
  1746. y = accum("milliseconds", x, ms, us_per_ms, &leftover_us);
  1747. CLEANUP;
  1748. }
  1749. if (second) {
  1750. y = accum("seconds", x, second, us_per_second, &leftover_us);
  1751. CLEANUP;
  1752. }
  1753. if (minute) {
  1754. y = accum("minutes", x, minute, us_per_minute, &leftover_us);
  1755. CLEANUP;
  1756. }
  1757. if (hour) {
  1758. y = accum("hours", x, hour, us_per_hour, &leftover_us);
  1759. CLEANUP;
  1760. }
  1761. if (day) {
  1762. y = accum("days", x, day, us_per_day, &leftover_us);
  1763. CLEANUP;
  1764. }
  1765. if (week) {
  1766. y = accum("weeks", x, week, us_per_week, &leftover_us);
  1767. CLEANUP;
  1768. }
  1769. if (leftover_us) {
  1770. /* Round to nearest whole # of us, and add into x. */
  1771. PyObject *temp = PyLong_FromLong(round_to_long(leftover_us));
  1772. if (temp == NULL) {
  1773. Py_DECREF(x);
  1774. goto Done;
  1775. }
  1776. y = PyNumber_Add(x, temp);
  1777. Py_DECREF(temp);
  1778. CLEANUP;
  1779. }
  1780. self = microseconds_to_delta_ex(x, type);
  1781. Py_DECREF(x);
  1782. Done:
  1783. return self;
  1784. #undef CLEANUP
  1785. }
  1786. static int
  1787. delta_nonzero(PyDateTime_Delta *self)
  1788. {
  1789. return (GET_TD_DAYS(self) != 0
  1790. || GET_TD_SECONDS(self) != 0
  1791. || GET_TD_MICROSECONDS(self) != 0);
  1792. }
  1793. static PyObject *
  1794. delta_repr(PyDateTime_Delta *self)
  1795. {
  1796. if (GET_TD_MICROSECONDS(self) != 0)
  1797. return PyString_FromFormat("%s(%d, %d, %d)",
  1798. Py_TYPE(self)->tp_name,
  1799. GET_TD_DAYS(self),
  1800. GET_TD_SECONDS(self),
  1801. GET_TD_MICROSECONDS(self));
  1802. if (GET_TD_SECONDS(self) != 0)
  1803. return PyString_FromFormat("%s(%d, %d)",
  1804. Py_TYPE(self)->tp_name,
  1805. GET_TD_DAYS(self),
  1806. GET_TD_SECONDS(self));
  1807. return PyString_FromFormat("%s(%d)",
  1808. Py_TYPE(self)->tp_name,
  1809. GET_TD_DAYS(self));
  1810. }
  1811. static PyObject *
  1812. delta_str(PyDateTime_Delta *self)
  1813. {
  1814. int days = GET_TD_DAYS(self);
  1815. int seconds = GET_TD_SECONDS(self);
  1816. int us = GET_TD_MICROSECONDS(self);
  1817. int hours;
  1818. int minutes;
  1819. char buf[100];
  1820. char *pbuf = buf;
  1821. size_t buflen = sizeof(buf);
  1822. int n;
  1823. minutes = divmod(seconds, 60, &seconds);
  1824. hours = divmod(minutes, 60, &minutes);
  1825. if (days) {
  1826. n = PyOS_snprintf(pbuf, buflen, "%d day%s, ", days,
  1827. (days == 1 || days == -1) ? "" : "s");
  1828. if (n < 0 || (size_t)n >= buflen)
  1829. goto Fail;
  1830. pbuf += n;
  1831. buflen -= (size_t)n;
  1832. }
  1833. n = PyOS_snprintf(pbuf, buflen, "%d:%02d:%02d",
  1834. hours, minutes, seconds);
  1835. if (n < 0 || (size_t)n >= buflen)
  1836. goto Fail;
  1837. pbuf += n;
  1838. buflen -= (size_t)n;
  1839. if (us) {
  1840. n = PyOS_snprintf(pbuf, buflen, ".%06d", us);
  1841. if (n < 0 || (size_t)n >= buflen)
  1842. goto Fail;
  1843. pbuf += n;
  1844. }
  1845. return PyString_FromStringAndSize(buf, pbuf - buf);
  1846. Fail:
  1847. PyErr_SetString(PyExc_SystemError, "goofy result from PyOS_snprintf");
  1848. return NULL;
  1849. }
  1850. /* Pickle support, a simple use of __reduce__. */
  1851. /* __getstate__ isn't exposed */
  1852. static PyObject *
  1853. delta_getstate(PyDateTime_Delta *self)
  1854. {
  1855. return Py_BuildValue("iii", GET_TD_DAYS(self),
  1856. GET_TD_SECONDS(self),
  1857. GET_TD_MICROSECONDS(self));
  1858. }
  1859. static PyObject *
  1860. delta_reduce(PyDateTime_Delta* self)
  1861. {
  1862. return Py_BuildValue("ON", Py_TYPE(self), delta_getstate(self));
  1863. }
  1864. #define OFFSET(field) offsetof(PyDateTime_Delta, field)
  1865. static PyMemberDef delta_members[] = {
  1866. {"days", T_INT, OFFSET(days), READONLY,
  1867. PyDoc_STR("Number of days.")},
  1868. {"seconds", T_INT, OFFSET(seconds), READONLY,
  1869. PyDoc_STR("Number of seconds (>= 0 and less than 1 day).")},
  1870. {"microseconds", T_INT, OFFSET(microseconds), READONLY,
  1871. PyDoc_STR("Number of microseconds (>= 0 and less than 1 second).")},
  1872. {NULL}
  1873. };
  1874. static PyMethodDef delta_methods[] = {
  1875. {"__reduce__", (PyCFunction)delta_reduce, METH_NOARGS,
  1876. PyDoc_STR("__reduce__() -> (cls, state)")},
  1877. {NULL, NULL},
  1878. };
  1879. static char delta_doc[] =
  1880. PyDoc_STR("Difference between two datetime values.");
  1881. static PyNumberMethods delta_as_number = {
  1882. delta_add, /* nb_add */
  1883. delta_subtract, /* nb_subtract */
  1884. delta_multiply, /* nb_multiply */
  1885. delta_divide, /* nb_divide */
  1886. 0, /* nb_remainder */
  1887. 0, /* nb_divmod */
  1888. 0, /* nb_power */
  1889. (unaryfunc)delta_negative, /* nb_negative */
  1890. (unaryfunc)delta_positive, /* nb_positive */
  1891. (unaryfunc)delta_abs, /* nb_absolute */
  1892. (inquiry)delta_nonzero, /* nb_nonzero */
  1893. 0, /*nb_invert*/
  1894. 0, /*nb_lshift*/
  1895. 0, /*nb_rshift*/
  1896. 0, /*nb_and*/
  1897. 0, /*nb_xor*/
  1898. 0, /*nb_or*/
  1899. 0, /*nb_coerce*/
  1900. 0, /*nb_int*/
  1901. 0, /*nb_long*/
  1902. 0, /*nb_float*/
  1903. 0, /*nb_oct*/
  1904. 0, /*nb_hex*/
  1905. 0, /*nb_inplace_add*/
  1906. 0, /*nb_inplace_subtract*/
  1907. 0, /*nb_inplace_multiply*/
  1908. 0, /*nb_inplace_divide*/
  1909. 0, /*nb_inplace_remainder*/
  1910. 0, /*nb_inplace_power*/
  1911. 0, /*nb_inplace_lshift*/
  1912. 0, /*nb_inplace_rshift*/
  1913. 0, /*nb_inplace_and*/
  1914. 0, /*nb_inplace_xor*/
  1915. 0, /*nb_inplace_or*/
  1916. delta_divide, /* nb_floor_divide */
  1917. 0, /* nb_true_divide */
  1918. 0, /* nb_inplace_floor_divide */
  1919. 0, /* nb_inplace_true_divide */
  1920. };
  1921. static PyTypeObject PyDateTime_DeltaType = {
  1922. PyVarObject_HEAD_INIT(NULL, 0)
  1923. "datetime.timedelta", /* tp_name */
  1924. sizeof(PyDateTime_Delta), /* tp_basicsize */
  1925. 0, /* tp_itemsize */
  1926. 0, /* tp_dealloc */
  1927. 0, /* tp_print */
  1928. 0, /* tp_getattr */
  1929. 0, /* tp_setattr */
  1930. 0, /* tp_compare */
  1931. (reprfunc)delta_repr, /* tp_repr */
  1932. &delta_as_number, /* tp_as_number */
  1933. 0, /* tp_as_sequence */
  1934. 0, /* tp_as_mapping */
  1935. (hashfunc)delta_hash, /* tp_hash */
  1936. 0, /* tp_call */
  1937. (reprfunc)delta_str, /* tp_str */
  1938. PyObject_GenericGetAttr, /* tp_getattro */
  1939. 0, /* tp_setattro */
  1940. 0, /* tp_as_buffer */
  1941. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
  1942. Py_TPFLAGS_BASETYPE, /* tp_flags */
  1943. delta_doc, /* tp_doc */
  1944. 0, /* tp_traverse */
  1945. 0, /* tp_clear */
  1946. (richcmpfunc)delta_richcompare, /* tp_richcompare */
  1947. 0, /* tp_weaklistoffset */
  1948. 0, /* tp_iter */
  1949. 0, /* tp_iternext */
  1950. delta_methods, /* tp_methods */
  1951. delta_members, /* tp_members */
  1952. 0, /* tp_getset */
  1953. 0, /* tp_base */
  1954. 0, /* tp_dict */
  1955. 0, /* tp_descr_get */
  1956. 0, /* tp_descr_set */
  1957. 0, /* tp_dictoffset */
  1958. 0, /* tp_init */
  1959. 0, /* tp_alloc */
  1960. delta_new, /* tp_new */
  1961. 0, /* tp_free */
  1962. };
  1963. /*
  1964. * PyDateTime_Date implementation.
  1965. */
  1966. /* Accessor properties. */
  1967. static PyObject *
  1968. date_year(PyDateTime_Date *self, void *unused)
  1969. {
  1970. return PyInt_FromLong(GET_YEAR(self));
  1971. }
  1972. static PyObject *
  1973. date_month(PyDateTime_Date *self, void *unused)
  1974. {
  1975. return PyInt_FromLong(GET_MONTH(self));
  1976. }
  1977. static PyObject *
  1978. date_day(PyDateTime_Date *self, void *unused)
  1979. {
  1980. return PyInt_FromLong(GET_DAY(self));
  1981. }
  1982. static PyGetSetDef date_getset[] = {
  1983. {"year", (getter)date_year},
  1984. {"month", (getter)date_month},
  1985. {"day", (getter)date_day},
  1986. {NULL}
  1987. };
  1988. /* Constructors. */
  1989. static char *date_kws[] = {"year", "month", "day", NULL};
  1990. static PyObject *
  1991. date_new(PyTypeObject *type, PyObject *args, PyObject *kw)
  1992. {
  1993. PyObject *self = NULL;
  1994. PyObject *state;
  1995. int year;
  1996. int month;
  1997. int day;
  1998. /* Check for invocation from pickle with __getstate__ state */
  1999. if (PyTuple_GET_SIZE(args) == 1 &&
  2000. PyString_Check(state = PyTuple_GET_ITEM(args, 0)) &&
  2001. PyString_GET_SIZE(state) == _PyDateTime_DATE_DATASIZE &&
  2002. MONTH_IS_SANE(PyString_AS_STRING(state)[2]))
  2003. {
  2004. PyDateTime_Date *me;
  2005. me = (PyDateTime_Date *) (type->tp_alloc(type, 0));
  2006. if (me != NULL) {
  2007. char *pdata = PyString_AS_STRING(state);
  2008. memcpy(me->data, pdata, _PyDateTime_DATE_DATASIZE);
  2009. me->hashcode = -1;
  2010. }
  2011. return (PyObject *)me;
  2012. }
  2013. if (PyArg_ParseTupleAndKeywords(args, kw, "iii", date_kws,
  2014. &year, &month, &day)) {
  2015. if (check_date_args(year, month, day) < 0)
  2016. return NULL;
  2017. self = new_date_ex(year, month, day, type);
  2018. }
  2019. return self;
  2020. }
  2021. /* Return new date from localtime(t). */
  2022. static PyObject *
  2023. date_local_from_time_t(PyObject *cls, double ts)
  2024. {
  2025. struct tm *tm;
  2026. time_t t;
  2027. PyObject *result = NULL;
  2028. t = _PyTime_DoubleToTimet(ts);
  2029. if (t == (time_t)-1 && PyErr_Occurred())
  2030. return NULL;
  2031. tm = localtime(&t);
  2032. if (tm)
  2033. result = PyObject_CallFunction(cls, "iii",
  2034. tm->tm_year + 1900,
  2035. tm->tm_mon + 1,
  2036. tm->tm_mday);
  2037. else
  2038. PyErr_SetString(PyExc_ValueError,
  2039. "timestamp out of range for "
  2040. "platform localtime() function");
  2041. return result;
  2042. }
  2043. /* Return new date from current time.
  2044. * We say this is equivalent to fromtimestamp(time.time()), and the
  2045. * only way to be sure of that is to *call* time.time(). That's not
  2046. * generally the same as calling C's time.
  2047. */
  2048. static PyObject *
  2049. date_today(PyObject *cls, PyObject *dummy)
  2050. {
  2051. PyObject *time;
  2052. PyObject *result;
  2053. time = time_time();
  2054. if (time == NULL)
  2055. return NULL;
  2056. /* Note well: today() is a class method, so this may not call
  2057. * date.fromtimestamp. For example, it may call
  2058. * datetime.fromtimestamp. That's why we need all the accuracy
  2059. * time.time() delivers; if someone were gonzo about optimization,
  2060. * date.today() could get away with plain C time().
  2061. */
  2062. result = PyObject_CallMethod(cls, "fromtimestamp", "O", time);
  2063. Py_DECREF(time);
  2064. return result;
  2065. }
  2066. /* Return new date from given timestamp (Python timestamp -- a double). */
  2067. static PyObject *
  2068. date_fromtimestamp(PyObject *cls, PyObject *args)
  2069. {
  2070. double timestamp;
  2071. PyObject *result = NULL;
  2072. if (PyArg_ParseTuple(args, "d:fromtimestamp", &timestamp))
  2073. result = date_local_from_time_t(cls, timestamp);
  2074. return result;
  2075. }
  2076. /* Return new date from proleptic Gregorian ordinal. Raises ValueError if
  2077. * the ordinal is out of range.
  2078. */
  2079. static PyObject *
  2080. date_fromordinal(PyObject *cls, PyObject *args)
  2081. {
  2082. PyObject *result = NULL;
  2083. int ordinal;
  2084. if (PyArg_ParseTuple(args, "i:fromordinal", &ordinal)) {
  2085. int year;
  2086. int month;
  2087. int day;
  2088. if (ordinal < 1)
  2089. PyErr_SetString(PyExc_ValueError, "ordinal must be "
  2090. ">= 1");
  2091. else {
  2092. ord_to_ymd(ordinal, &year, &month, &day);
  2093. result = PyObject_CallFunction(cls, "iii",
  2094. year, month, day);
  2095. }
  2096. }
  2097. return result;
  2098. }
  2099. /*
  2100. * Date arithmetic.
  2101. */
  2102. /* date + timedelta -> date. If arg negate is true, subtract the timedelta
  2103. * instead.
  2104. */
  2105. static PyObject *
  2106. add_date_timedelta(PyDateTime_Date *date, PyDateTime_Delta *delta, int negate)
  2107. {
  2108. PyObject *result = NULL;
  2109. int year = GET_YEAR(date);
  2110. int month = GET_MONTH(date);
  2111. int deltadays = GET_TD_DAYS(delta);
  2112. /* C-level overflow is impossible because |deltadays| < 1e9. */
  2113. int day = GET_DAY(date) + (negate ? -deltadays : deltadays);
  2114. if (normalize_date(&year, &month, &day) >= 0)
  2115. result = new_date(year, month, day);
  2116. return result;
  2117. }
  2118. static PyObject *
  2119. date_add(PyObject *left, PyObject *right)
  2120. {
  2121. if (PyDateTime_Check(left) || PyDateTime_Check(right)) {
  2122. Py_INCREF(Py_NotImplemented);
  2123. return Py_NotImplemented;
  2124. }
  2125. if (PyDate_Check(left)) {
  2126. /* date + ??? */
  2127. if (PyDelta_Check(right))
  2128. /* date + delta */
  2129. return add_date_timedelta((PyDateTime_Date *) left,
  2130. (PyDateTime_Delta *) right,
  2131. 0);
  2132. }
  2133. else {
  2134. /* ??? + date
  2135. * 'right' must be one of us, or we wouldn't have been called
  2136. */
  2137. if (PyDelta_Check(left))
  2138. /* delta + date */
  2139. return add_date_timedelta((PyDateTime_Date *) right,
  2140. (PyDateTime_Delta *) left,
  2141. 0);
  2142. }
  2143. Py_INCREF(Py_NotImplemented);
  2144. return Py_NotImplemented;
  2145. }
  2146. static PyObject *
  2147. date_subtract(PyObject *left, PyObject *right)
  2148. {
  2149. if (PyDateTime_Check(left) || PyDateTime_Check(right)) {
  2150. Py_INCREF(Py_NotImplemented);
  2151. return Py_NotImplemented;
  2152. }
  2153. if (PyDate_Check(left)) {
  2154. if (PyDate_Check(right)) {
  2155. /* date - date */
  2156. int left_ord = ymd_to_ord(GET_YEAR(left),
  2157. GET_MONTH(left),
  2158. GET_DAY(left));
  2159. int right_ord = ymd_to_ord(GET_YEAR(right),
  2160. GET_MONTH(right),
  2161. GET_DAY(right));
  2162. return new_delta(left_ord - right_ord, 0, 0, 0);
  2163. }
  2164. if (PyDelta_Check(right)) {
  2165. /* date - delta */
  2166. return add_date_timedelta((PyDateTime_Date *) left,
  2167. (PyDateTime_Delta *) right,
  2168. 1);
  2169. }
  2170. }
  2171. Py_INCREF(Py_NotImplemented);
  2172. return Py_NotImplemented;
  2173. }
  2174. /* Various ways to turn a date into a string. */
  2175. static PyObject *
  2176. date_repr(PyDateTime_Date *self)
  2177. {
  2178. char buffer[1028];
  2179. const char *type_name;
  2180. type_name = Py_TYPE(self)->tp_name;
  2181. PyOS_snprintf(buffer, sizeof(buffer), "%s(%d, %d, %d)",
  2182. type_name,
  2183. GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
  2184. return PyString_FromString(buffer);
  2185. }
  2186. static PyObject *
  2187. date_isoformat(PyDateTime_Date *self)
  2188. {
  2189. char buffer[128];
  2190. isoformat_date(self, buffer, sizeof(buffer));
  2191. return PyString_FromString(buffer);
  2192. }
  2193. /* str() calls the appropriate isoformat() method. */
  2194. static PyObject *
  2195. date_str(PyDateTime_Date *self)
  2196. {
  2197. return PyObject_CallMethod((PyObject *)self, "isoformat", "()");
  2198. }
  2199. static PyObject *
  2200. date_ctime(PyDateTime_Date *self)
  2201. {
  2202. return format_ctime(self, 0, 0, 0);
  2203. }
  2204. static PyObject *
  2205. date_strftime(PyDateTime_Date *self, PyObject *args, PyObject *kw)
  2206. {
  2207. /* This method can be inherited, and needs to call the
  2208. * timetuple() method appropriate to self's class.
  2209. */
  2210. PyObject *result;
  2211. PyObject *tuple;
  2212. const char *format;
  2213. Py_ssize_t format_len;
  2214. static char *keywords[] = {"format", NULL};
  2215. if (! PyArg_ParseTupleAndKeywords(args, kw, "s#:strftime", keywords,
  2216. &format, &format_len))
  2217. return NULL;
  2218. tuple = PyObject_CallMethod((PyObject *)self, "timetuple", "()");
  2219. if (tuple == NULL)
  2220. return NULL;
  2221. result = wrap_strftime((PyObject *)self, format, format_len, tuple,
  2222. (PyObject *)self);
  2223. Py_DECREF(tuple);
  2224. return result;
  2225. }
  2226. static PyObject *
  2227. date_format(PyDateTime_Date *self, PyObject *args)
  2228. {
  2229. PyObject *format;
  2230. if (!PyArg_ParseTuple(args, "O:__format__", &format))
  2231. return NULL;
  2232. /* Check for str or unicode */
  2233. if (PyString_Check(format)) {
  2234. /* If format is zero length, return str(self) */
  2235. if (PyString_GET_SIZE(format) == 0)
  2236. return PyObject_Str((PyObject *)self);
  2237. } else if (PyUnicode_Check(format)) {
  2238. /* If format is zero length, return str(self) */
  2239. if (PyUnicode_GET_SIZE(format) == 0)
  2240. return PyObject_Unicode((PyObject *)self);
  2241. } else {
  2242. PyErr_Format(PyExc_ValueError,
  2243. "__format__ expects str or unicode, not %.200s",
  2244. Py_TYPE(format)->tp_name);
  2245. return NULL;
  2246. }
  2247. return PyObject_CallMethod((PyObject *)self, "strftime", "O", format);
  2248. }
  2249. /* ISO methods. */
  2250. static PyObject *
  2251. date_isoweekday(PyDateTime_Date *self)
  2252. {
  2253. int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
  2254. return PyInt_FromLong(dow + 1);
  2255. }
  2256. static PyObject *
  2257. date_isocalendar(PyDateTime_Date *self)
  2258. {
  2259. int year = GET_YEAR(self);
  2260. int week1_monday = iso_week1_monday(year);
  2261. int today = ymd_to_ord(year, GET_MONTH(self), GET_DAY(self));
  2262. int week;
  2263. int day;
  2264. week = divmod(today - week1_monday, 7, &day);
  2265. if (week < 0) {
  2266. --year;
  2267. week1_monday = iso_week1_monday(year);
  2268. week = divmod(today - week1_monday, 7, &day);
  2269. }
  2270. else if (week >= 52 && today >= iso_week1_monday(year + 1)) {
  2271. ++year;
  2272. week = 0;
  2273. }
  2274. return Py_BuildValue("iii", year, week + 1, day + 1);
  2275. }
  2276. /* Miscellaneous methods. */
  2277. /* This is more natural as a tp_compare, but doesn't work then: for whatever
  2278. * reason, Python's try_3way_compare ignores tp_compare unless
  2279. * PyInstance_Check returns true, but these aren't old-style classes.
  2280. */
  2281. static PyObject *
  2282. date_richcompare(PyDateTime_Date *self, PyObject *other, int op)
  2283. {
  2284. int diff = 42; /* nonsense */
  2285. if (PyDate_Check(other))
  2286. diff = memcmp(self->data, ((PyDateTime_Date *)other)->data,
  2287. _PyDateTime_DATE_DATASIZE);
  2288. else if (PyObject_HasAttrString(other, "timetuple")) {
  2289. /* A hook for other kinds of date objects. */
  2290. Py_INCREF(Py_NotImplemented);
  2291. return Py_NotImplemented;
  2292. }
  2293. else if (op == Py_EQ || op == Py_NE)
  2294. diff = 1; /* any non-zero value will do */
  2295. else /* stop this from falling back to address comparison */
  2296. return cmperror((PyObject *)self, other);
  2297. return diff_to_bool(diff, op);
  2298. }
  2299. static PyObject *
  2300. date_timetuple(PyDateTime_Date *self)
  2301. {
  2302. return build_struct_time(GET_YEAR(self),
  2303. GET_MONTH(self),
  2304. GET_DAY(self),
  2305. 0, 0, 0, -1);
  2306. }
  2307. static PyObject *
  2308. date_replace(PyDateTime_Date *self, PyObject *args, PyObject *kw)
  2309. {
  2310. PyObject *clone;
  2311. PyObject *tuple;
  2312. int year = GET_YEAR(self);
  2313. int month = GET_MONTH(self);
  2314. int day = GET_DAY(self);
  2315. if (! PyArg_ParseTupleAndKeywords(args, kw, "|iii:replace", date_kws,
  2316. &year, &month, &day))
  2317. return NULL;
  2318. tuple = Py_BuildValue("iii", year, month, day);
  2319. if (tuple == NULL)
  2320. return NULL;
  2321. clone = date_new(Py_TYPE(self), tuple, NULL);
  2322. Py_DECREF(tuple);
  2323. return clone;
  2324. }
  2325. static PyObject *date_getstate(PyDateTime_Date *self);
  2326. static long
  2327. date_hash(PyDateTime_Date *self)
  2328. {
  2329. if (self->hashcode == -1) {
  2330. PyObject *temp = date_getstate(self);
  2331. if (temp != NULL) {
  2332. self->hashcode = PyObject_Hash(temp);
  2333. Py_DECREF(temp);
  2334. }
  2335. }
  2336. return self->hashcode;
  2337. }
  2338. static PyObject *
  2339. date_toordinal(PyDateTime_Date *self)
  2340. {
  2341. return PyInt_FromLong(ymd_to_ord(GET_YEAR(self), GET_MONTH(self),
  2342. GET_DAY(self)));
  2343. }
  2344. static PyObject *
  2345. date_weekday(PyDateTime_Date *self)
  2346. {
  2347. int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
  2348. return PyInt_FromLong(dow);
  2349. }
  2350. /* Pickle support, a simple use of __reduce__. */
  2351. /* __getstate__ isn't exposed */
  2352. static PyObject *
  2353. date_getstate(PyDateTime_Date *self)
  2354. {
  2355. return Py_BuildValue(
  2356. "(N)",
  2357. PyString_FromStringAndSize((char *)self->data,
  2358. _PyDateTime_DATE_DATASIZE));
  2359. }
  2360. static PyObject *
  2361. date_reduce(PyDateTime_Date *self, PyObject *arg)
  2362. {
  2363. return Py_BuildValue("(ON)", Py_TYPE(self), date_getstate(self));
  2364. }
  2365. static PyMethodDef date_methods[] = {
  2366. /* Class methods: */
  2367. {"fromtimestamp", (PyCFunction)date_fromtimestamp, METH_VARARGS |
  2368. METH_CLASS,
  2369. PyDoc_STR("timestamp -> local date from a POSIX timestamp (like "
  2370. "time.time()).")},
  2371. {"fromordinal", (PyCFunction)date_fromordinal, METH_VARARGS |
  2372. METH_CLASS,
  2373. PyDoc_STR("int -> date corresponding to a proleptic Gregorian "
  2374. "ordinal.")},
  2375. {"today", (PyCFunction)date_today, METH_NOARGS | METH_CLASS,
  2376. PyDoc_STR("Current date or datetime: same as "
  2377. "self.__class__.fromtimestamp(time.time()).")},
  2378. /* Instance methods: */
  2379. {"ctime", (PyCFunction)date_ctime, METH_NOARGS,
  2380. PyDoc_STR("Return ctime() style string.")},
  2381. {"strftime", (PyCFunction)date_strftime, METH_VARARGS | METH_KEYWORDS,
  2382. PyDoc_STR("format -> strftime() style string.")},
  2383. {"__format__", (PyCFunction)date_format, METH_VARARGS,
  2384. PyDoc_STR("Formats self with strftime.")},
  2385. {"timetuple", (PyCFunction)date_timetuple, METH_NOARGS,
  2386. PyDoc_STR("Return time tuple, compatible with time.localtime().")},
  2387. {"isocalendar", (PyCFunction)date_isocalendar, METH_NOARGS,
  2388. PyDoc_STR("Return a 3-tuple containing ISO year, week number, and "
  2389. "weekday.")},
  2390. {"isoformat", (PyCFunction)date_isoformat, METH_NOARGS,
  2391. PyDoc_STR("Return string in ISO 8601 format, YYYY-MM-DD.")},
  2392. {"isoweekday", (PyCFunction)date_isoweekday, METH_NOARGS,
  2393. PyDoc_STR("Return the day of the week represented by the date.\n"
  2394. "Monday == 1 ... Sunday == 7")},
  2395. {"toordinal", (PyCFunction)date_toordinal, METH_NOARGS,
  2396. PyDoc_STR("Return proleptic Gregorian ordinal. January 1 of year "
  2397. "1 is day 1.")},
  2398. {"weekday", (PyCFunction)date_weekday, METH_NOARGS,
  2399. PyDoc_STR("Return the day of the week represented by the date.\n"
  2400. "Monday == 0 ... Sunday == 6")},
  2401. {"replace", (PyCFunction)date_replace, METH_VARARGS | METH_KEYWORDS,
  2402. PyDoc_STR("Return date with new specified fields.")},
  2403. {"__reduce__", (PyCFunction)date_reduce, METH_NOARGS,
  2404. PyDoc_STR("__reduce__() -> (cls, state)")},
  2405. {NULL, NULL}
  2406. };
  2407. static char date_doc[] =
  2408. PyDoc_STR("date(year, month, day) --> date object");
  2409. static PyNumberMethods date_as_number = {
  2410. date_add, /* nb_add */
  2411. date_subtract, /* nb_subtract */
  2412. 0, /* nb_multiply */
  2413. 0, /* nb_divide */
  2414. 0, /* nb_remainder */
  2415. 0, /* nb_divmod */
  2416. 0, /* nb_power */
  2417. 0, /* nb_negative */
  2418. 0, /* nb_positive */
  2419. 0, /* nb_absolute */
  2420. 0, /* nb_nonzero */
  2421. };
  2422. static PyTypeObject PyDateTime_DateType = {
  2423. PyVarObject_HEAD_INIT(NULL, 0)
  2424. "datetime.date", /* tp_name */
  2425. sizeof(PyDateTime_Date), /* tp_basicsize */
  2426. 0, /* tp_itemsize */
  2427. 0, /* tp_dealloc */
  2428. 0, /* tp_print */
  2429. 0, /* tp_getattr */
  2430. 0, /* tp_setattr */
  2431. 0, /* tp_compare */
  2432. (reprfunc)date_repr, /* tp_repr */
  2433. &date_as_number, /* tp_as_number */
  2434. 0, /* tp_as_sequence */
  2435. 0, /* tp_as_mapping */
  2436. (hashfunc)date_hash, /* tp_hash */
  2437. 0, /* tp_call */
  2438. (reprfunc)date_str, /* tp_str */
  2439. PyObject_GenericGetAttr, /* tp_getattro */
  2440. 0, /* tp_setattro */
  2441. 0, /* tp_as_buffer */
  2442. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
  2443. Py_TPFLAGS_BASETYPE, /* tp_flags */
  2444. date_doc, /* tp_doc */
  2445. 0, /* tp_traverse */
  2446. 0, /* tp_clear */
  2447. (richcmpfunc)date_richcompare, /* tp_richcompare */
  2448. 0, /* tp_weaklistoffset */
  2449. 0, /* tp_iter */
  2450. 0, /* tp_iternext */
  2451. date_methods, /* tp_methods */
  2452. 0, /* tp_members */
  2453. date_getset, /* tp_getset */
  2454. 0, /* tp_base */
  2455. 0, /* tp_dict */
  2456. 0, /* tp_descr_get */
  2457. 0, /* tp_descr_set */
  2458. 0, /* tp_dictoffset */
  2459. 0, /* tp_init */
  2460. 0, /* tp_alloc */
  2461. date_new, /* tp_new */
  2462. 0, /* tp_free */
  2463. };
  2464. /*
  2465. * PyDateTime_TZInfo implementation.
  2466. */
  2467. /* This is a pure abstract base class, so doesn't do anything beyond
  2468. * raising NotImplemented exceptions. Real tzinfo classes need
  2469. * to derive from this. This is mostly for clarity, and for efficiency in
  2470. * datetime and time constructors (their tzinfo arguments need to
  2471. * be subclasses of this tzinfo class, which is easy and quick to check).
  2472. *
  2473. * Note: For reasons having to do with pickling of subclasses, we have
  2474. * to allow tzinfo objects to be instantiated. This wasn't an issue
  2475. * in the Python implementation (__init__() could raise NotImplementedError
  2476. * there without ill effect), but doing so in the C implementation hit a
  2477. * brick wall.
  2478. */
  2479. static PyObject *
  2480. tzinfo_nogo(const char* methodname)
  2481. {
  2482. PyErr_Format(PyExc_NotImplementedError,
  2483. "a tzinfo subclass must implement %s()",
  2484. methodname);
  2485. return NULL;
  2486. }
  2487. /* Methods. A subclass must implement these. */
  2488. static PyObject *
  2489. tzinfo_tzname(PyDateTime_TZInfo *self, PyObject *dt)
  2490. {
  2491. return tzinfo_nogo("tzname");
  2492. }
  2493. static PyObject *
  2494. tzinfo_utcoffset(PyDateTime_TZInfo *self, PyObject *dt)
  2495. {
  2496. return tzinfo_nogo("utcoffset");
  2497. }
  2498. static PyObject *
  2499. tzinfo_dst(PyDateTime_TZInfo *self, PyObject *dt)
  2500. {
  2501. return tzinfo_nogo("dst");
  2502. }
  2503. static PyObject *
  2504. tzinfo_fromutc(PyDateTime_TZInfo *self, PyDateTime_DateTime *dt)
  2505. {
  2506. int y, m, d, hh, mm, ss, us;
  2507. PyObject *result;
  2508. int off, dst;
  2509. int none;
  2510. int delta;
  2511. if (! PyDateTime_Check(dt)) {
  2512. PyErr_SetString(PyExc_TypeError,
  2513. "fromutc: argument must be a datetime");
  2514. return NULL;
  2515. }
  2516. if (! HASTZINFO(dt) || dt->tzinfo != (PyObject *)self) {
  2517. PyErr_SetString(PyExc_ValueError, "fromutc: dt.tzinfo "
  2518. "is not self");
  2519. return NULL;
  2520. }
  2521. off = call_utcoffset(dt->tzinfo, (PyObject *)dt, &none);
  2522. if (off == -1 && PyErr_Occurred())
  2523. return NULL;
  2524. if (none) {
  2525. PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
  2526. "utcoffset() result required");
  2527. return NULL;
  2528. }
  2529. dst = call_dst(dt->tzinfo, (PyObject *)dt, &none);
  2530. if (dst == -1 && PyErr_Occurred())
  2531. return NULL;
  2532. if (none) {
  2533. PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
  2534. "dst() result required");
  2535. return NULL;
  2536. }
  2537. y = GET_YEAR(dt);
  2538. m = GET_MONTH(dt);
  2539. d = GET_DAY(dt);
  2540. hh = DATE_GET_HOUR(dt);
  2541. mm = DATE_GET_MINUTE(dt);
  2542. ss = DATE_GET_SECOND(dt);
  2543. us = DATE_GET_MICROSECOND(dt);
  2544. delta = off - dst;
  2545. mm += delta;
  2546. if ((mm < 0 || mm >= 60) &&
  2547. normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
  2548. return NULL;
  2549. result = new_datetime(y, m, d, hh, mm, ss, us, dt->tzinfo);
  2550. if (result == NULL)
  2551. return result;
  2552. dst = call_dst(dt->tzinfo, result, &none);
  2553. if (dst == -1 && PyErr_Occurred())
  2554. goto Fail;
  2555. if (none)
  2556. goto Inconsistent;
  2557. if (dst == 0)
  2558. return result;
  2559. mm += dst;
  2560. if ((mm < 0 || mm >= 60) &&
  2561. normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
  2562. goto Fail;
  2563. Py_DECREF(result);
  2564. result = new_datetime(y, m, d, hh, mm, ss, us, dt->tzinfo);
  2565. return result;
  2566. Inconsistent:
  2567. PyErr_SetString(PyExc_ValueError, "fromutc: tz.dst() gave"
  2568. "inconsistent results; cannot convert");
  2569. /* fall thru to failure */
  2570. Fail:
  2571. Py_DECREF(result);
  2572. return NULL;
  2573. }
  2574. /*
  2575. * Pickle support. This is solely so that tzinfo subclasses can use
  2576. * pickling -- tzinfo itself is supposed to be uninstantiable.
  2577. */
  2578. static PyObject *
  2579. tzinfo_reduce(PyObject *self)
  2580. {
  2581. PyObject *args, *state, *tmp;
  2582. PyObject *getinitargs, *getstate;
  2583. tmp = PyTuple_New(0);
  2584. if (tmp == NULL)
  2585. return NULL;
  2586. getinitargs = PyObject_GetAttrString(self, "__getinitargs__");
  2587. if (getinitargs != NULL) {
  2588. args = PyObject_CallObject(getinitargs, tmp);
  2589. Py_DECREF(getinitargs);
  2590. if (args == NULL) {
  2591. Py_DECREF(tmp);
  2592. return NULL;
  2593. }
  2594. }
  2595. else {
  2596. PyErr_Clear();
  2597. args = tmp;
  2598. Py_INCREF(args);
  2599. }
  2600. getstate = PyObject_GetAttrString(self, "__getstate__");
  2601. if (getstate != NULL) {
  2602. state = PyObject_CallObject(getstate, tmp);
  2603. Py_DECREF(getstate);
  2604. if (state == NULL) {
  2605. Py_DECREF(args);
  2606. Py_DECREF(tmp);
  2607. return NULL;
  2608. }
  2609. }
  2610. else {
  2611. PyObject **dictptr;
  2612. PyErr_Clear();
  2613. state = Py_None;
  2614. dictptr = _PyObject_GetDictPtr(self);
  2615. if (dictptr && *dictptr && PyDict_Size(*dictptr))
  2616. state = *dictptr;
  2617. Py_INCREF(state);
  2618. }
  2619. Py_DECREF(tmp);
  2620. if (state == Py_None) {
  2621. Py_DECREF(state);
  2622. return Py_BuildValue("(ON)", Py_TYPE(self), args);
  2623. }
  2624. else
  2625. return Py_BuildValue("(ONN)", Py_TYPE(self), args, state);
  2626. }
  2627. static PyMethodDef tzinfo_methods[] = {
  2628. {"tzname", (PyCFunction)tzinfo_tzname, METH_O,
  2629. PyDoc_STR("datetime -> string name of time zone.")},
  2630. {"utcoffset", (PyCFunction)tzinfo_utcoffset, METH_O,
  2631. PyDoc_STR("datetime -> minutes east of UTC (negative for "
  2632. "west of UTC).")},
  2633. {"dst", (PyCFunction)tzinfo_dst, METH_O,
  2634. PyDoc_STR("datetime -> DST offset in minutes east of UTC.")},
  2635. {"fromutc", (PyCFunction)tzinfo_fromutc, METH_O,
  2636. PyDoc_STR("datetime in UTC -> datetime in local time.")},
  2637. {"__reduce__", (PyCFunction)tzinfo_reduce, METH_NOARGS,
  2638. PyDoc_STR("-> (cls, state)")},
  2639. {NULL, NULL}
  2640. };
  2641. static char tzinfo_doc[] =
  2642. PyDoc_STR("Abstract base class for time zone info objects.");
  2643. statichere PyTypeObject PyDateTime_TZInfoType = {
  2644. PyObject_HEAD_INIT(NULL)
  2645. 0, /* ob_size */
  2646. "datetime.tzinfo", /* tp_name */
  2647. sizeof(PyDateTime_TZInfo), /* tp_basicsize */
  2648. 0, /* tp_itemsize */
  2649. 0, /* tp_dealloc */
  2650. 0, /* tp_print */
  2651. 0, /* tp_getattr */
  2652. 0, /* tp_setattr */
  2653. 0, /* tp_compare */
  2654. 0, /* tp_repr */
  2655. 0, /* tp_as_number */
  2656. 0, /* tp_as_sequence */
  2657. 0, /* tp_as_mapping */
  2658. 0, /* tp_hash */
  2659. 0, /* tp_call */
  2660. 0, /* tp_str */
  2661. PyObject_GenericGetAttr, /* tp_getattro */
  2662. 0, /* tp_setattro */
  2663. 0, /* tp_as_buffer */
  2664. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
  2665. Py_TPFLAGS_BASETYPE, /* tp_flags */
  2666. tzinfo_doc, /* tp_doc */
  2667. 0, /* tp_traverse */
  2668. 0, /* tp_clear */
  2669. 0, /* tp_richcompare */
  2670. 0, /* tp_weaklistoffset */
  2671. 0, /* tp_iter */
  2672. 0, /* tp_iternext */
  2673. tzinfo_methods, /* tp_methods */
  2674. 0, /* tp_members */
  2675. 0, /* tp_getset */
  2676. 0, /* tp_base */
  2677. 0, /* tp_dict */
  2678. 0, /* tp_descr_get */
  2679. 0, /* tp_descr_set */
  2680. 0, /* tp_dictoffset */
  2681. 0, /* tp_init */
  2682. 0, /* tp_alloc */
  2683. PyType_GenericNew, /* tp_new */
  2684. 0, /* tp_free */
  2685. };
  2686. /*
  2687. * PyDateTime_Time implementation.
  2688. */
  2689. /* Accessor properties.
  2690. */
  2691. static PyObject *
  2692. time_hour(PyDateTime_Time *self, void *unused)
  2693. {
  2694. return PyInt_FromLong(TIME_GET_HOUR(self));
  2695. }
  2696. static PyObject *
  2697. time_minute(PyDateTime_Time *self, void *unused)
  2698. {
  2699. return PyInt_FromLong(TIME_GET_MINUTE(self));
  2700. }
  2701. /* The name time_second conflicted with some platform header file. */
  2702. static PyObject *
  2703. py_time_second(PyDateTime_Time *self, void *unused)
  2704. {
  2705. return PyInt_FromLong(TIME_GET_SECOND(self));
  2706. }
  2707. static PyObject *
  2708. time_microsecond(PyDateTime_Time *self, void *unused)
  2709. {
  2710. return PyInt_FromLong(TIME_GET_MICROSECOND(self));
  2711. }
  2712. static PyObject *
  2713. time_tzinfo(PyDateTime_Time *self, void *unused)
  2714. {
  2715. PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
  2716. Py_INCREF(result);
  2717. return result;
  2718. }
  2719. static PyGetSetDef time_getset[] = {
  2720. {"hour", (getter)time_hour},
  2721. {"minute", (getter)time_minute},
  2722. {"second", (getter)py_time_second},
  2723. {"microsecond", (getter)time_microsecond},
  2724. {"tzinfo", (getter)time_tzinfo},
  2725. {NULL}
  2726. };
  2727. /*
  2728. * Constructors.
  2729. */
  2730. static char *time_kws[] = {"hour", "minute", "second", "microsecond",
  2731. "tzinfo", NULL};
  2732. static PyObject *
  2733. time_new(PyTypeObject *type, PyObject *args, PyObject *kw)
  2734. {
  2735. PyObject *self = NULL;
  2736. PyObject *state;
  2737. int hour = 0;
  2738. int minute = 0;
  2739. int second = 0;
  2740. int usecond = 0;
  2741. PyObject *tzinfo = Py_None;
  2742. /* Check for invocation from pickle with __getstate__ state */
  2743. if (PyTuple_GET_SIZE(args) >= 1 &&
  2744. PyTuple_GET_SIZE(args) <= 2 &&
  2745. PyString_Check(state = PyTuple_GET_ITEM(args, 0)) &&
  2746. PyString_GET_SIZE(state) == _PyDateTime_TIME_DATASIZE &&
  2747. ((unsigned char) (PyString_AS_STRING(state)[0])) < 24)
  2748. {
  2749. PyDateTime_Time *me;
  2750. char aware;
  2751. if (PyTuple_GET_SIZE(args) == 2) {
  2752. tzinfo = PyTuple_GET_ITEM(args, 1);
  2753. if (check_tzinfo_subclass(tzinfo) < 0) {
  2754. PyErr_SetString(PyExc_TypeError, "bad "
  2755. "tzinfo state arg");
  2756. return NULL;
  2757. }
  2758. }
  2759. aware = (char)(tzinfo != Py_None);
  2760. me = (PyDateTime_Time *) (type->tp_alloc(type, aware));
  2761. if (me != NULL) {
  2762. char *pdata = PyString_AS_STRING(state);
  2763. memcpy(me->data, pdata, _PyDateTime_TIME_DATASIZE);
  2764. me->hashcode = -1;
  2765. me->hastzinfo = aware;
  2766. if (aware) {
  2767. Py_INCREF(tzinfo);
  2768. me->tzinfo = tzinfo;
  2769. }
  2770. }
  2771. return (PyObject *)me;
  2772. }
  2773. if (PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO", time_kws,
  2774. &hour, &minute, &second, &usecond,
  2775. &tzinfo)) {
  2776. if (check_time_args(hour, minute, second, usecond) < 0)
  2777. return NULL;
  2778. if (check_tzinfo_subclass(tzinfo) < 0)
  2779. return NULL;
  2780. self = new_time_ex(hour, minute, second, usecond, tzinfo,
  2781. type);
  2782. }
  2783. return self;
  2784. }
  2785. /*
  2786. * Destructor.
  2787. */
  2788. static void
  2789. time_dealloc(PyDateTime_Time *self)
  2790. {
  2791. if (HASTZINFO(self)) {
  2792. Py_XDECREF(self->tzinfo);
  2793. }
  2794. Py_TYPE(self)->tp_free((PyObject *)self);
  2795. }
  2796. /*
  2797. * Indirect access to tzinfo methods.
  2798. */
  2799. /* These are all METH_NOARGS, so don't need to check the arglist. */
  2800. static PyObject *
  2801. time_utcoffset(PyDateTime_Time *self, PyObject *unused) {
  2802. return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
  2803. "utcoffset", Py_None);
  2804. }
  2805. static PyObject *
  2806. time_dst(PyDateTime_Time *self, PyObject *unused) {
  2807. return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
  2808. "dst", Py_None);
  2809. }
  2810. static PyObject *
  2811. time_tzname(PyDateTime_Time *self, PyObject *unused) {
  2812. return call_tzname(HASTZINFO(self) ? self->tzinfo : Py_None,
  2813. Py_None);
  2814. }
  2815. /*
  2816. * Various ways to turn a time into a string.
  2817. */
  2818. static PyObject *
  2819. time_repr(PyDateTime_Time *self)
  2820. {
  2821. char buffer[100];
  2822. const char *type_name = Py_TYPE(self)->tp_name;
  2823. int h = TIME_GET_HOUR(self);
  2824. int m = TIME_GET_MINUTE(self);
  2825. int s = TIME_GET_SECOND(self);
  2826. int us = TIME_GET_MICROSECOND(self);
  2827. PyObject *result = NULL;
  2828. if (us)
  2829. PyOS_snprintf(buffer, sizeof(buffer),
  2830. "%s(%d, %d, %d, %d)", type_name, h, m, s, us);
  2831. else if (s)
  2832. PyOS_snprintf(buffer, sizeof(buffer),
  2833. "%s(%d, %d, %d)", type_name, h, m, s);
  2834. else
  2835. PyOS_snprintf(buffer, sizeof(buffer),
  2836. "%s(%d, %d)", type_name, h, m);
  2837. result = PyString_FromString(buffer);
  2838. if (result != NULL && HASTZINFO(self))
  2839. result = append_keyword_tzinfo(result, self->tzinfo);
  2840. return result;
  2841. }
  2842. static PyObject *
  2843. time_str(PyDateTime_Time *self)
  2844. {
  2845. return PyObject_CallMethod((PyObject *)self, "isoformat", "()");
  2846. }
  2847. static PyObject *
  2848. time_isoformat(PyDateTime_Time *self, PyObject *unused)
  2849. {
  2850. char buf[100];
  2851. PyObject *result;
  2852. /* Reuse the time format code from the datetime type. */
  2853. PyDateTime_DateTime datetime;
  2854. PyDateTime_DateTime *pdatetime = &datetime;
  2855. /* Copy over just the time bytes. */
  2856. memcpy(pdatetime->data + _PyDateTime_DATE_DATASIZE,
  2857. self->data,
  2858. _PyDateTime_TIME_DATASIZE);
  2859. isoformat_time(pdatetime, buf, sizeof(buf));
  2860. result = PyString_FromString(buf);
  2861. if (result == NULL || ! HASTZINFO(self) || self->tzinfo == Py_None)
  2862. return result;
  2863. /* We need to append the UTC offset. */
  2864. if (format_utcoffset(buf, sizeof(buf), ":", self->tzinfo,
  2865. Py_None) < 0) {
  2866. Py_DECREF(result);
  2867. return NULL;
  2868. }
  2869. PyString_ConcatAndDel(&result, PyString_FromString(buf));
  2870. return result;
  2871. }
  2872. static PyObject *
  2873. time_strftime(PyDateTime_Time *self, PyObject *args, PyObject *kw)
  2874. {
  2875. PyObject *result;
  2876. PyObject *tuple;
  2877. const char *format;
  2878. Py_ssize_t format_len;
  2879. static char *keywords[] = {"format", NULL};
  2880. if (! PyArg_ParseTupleAndKeywords(args, kw, "s#:strftime", keywords,
  2881. &format, &format_len))
  2882. return NULL;
  2883. /* Python's strftime does insane things with the year part of the
  2884. * timetuple. The year is forced to (the otherwise nonsensical)
  2885. * 1900 to worm around that.
  2886. */
  2887. tuple = Py_BuildValue("iiiiiiiii",
  2888. 1900, 1, 1, /* year, month, day */
  2889. TIME_GET_HOUR(self),
  2890. TIME_GET_MINUTE(self),
  2891. TIME_GET_SECOND(self),
  2892. 0, 1, -1); /* weekday, daynum, dst */
  2893. if (tuple == NULL)
  2894. return NULL;
  2895. assert(PyTuple_Size(tuple) == 9);
  2896. result = wrap_strftime((PyObject *)self, format, format_len, tuple,
  2897. Py_None);
  2898. Py_DECREF(tuple);
  2899. return result;
  2900. }
  2901. /*
  2902. * Miscellaneous methods.
  2903. */
  2904. /* This is more natural as a tp_compare, but doesn't work then: for whatever
  2905. * reason, Python's try_3way_compare ignores tp_compare unless
  2906. * PyInstance_Check returns true, but these aren't old-style classes.
  2907. */
  2908. static PyObject *
  2909. time_richcompare(PyDateTime_Time *self, PyObject *other, int op)
  2910. {
  2911. int diff;
  2912. naivety n1, n2;
  2913. int offset1, offset2;
  2914. if (! PyTime_Check(other)) {
  2915. if (op == Py_EQ || op == Py_NE) {
  2916. PyObject *result = op == Py_EQ ? Py_False : Py_True;
  2917. Py_INCREF(result);
  2918. return result;
  2919. }
  2920. /* Stop this from falling back to address comparison. */
  2921. return cmperror((PyObject *)self, other);
  2922. }
  2923. if (classify_two_utcoffsets((PyObject *)self, &offset1, &n1, Py_None,
  2924. other, &offset2, &n2, Py_None) < 0)
  2925. return NULL;
  2926. assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
  2927. /* If they're both naive, or both aware and have the same offsets,
  2928. * we get off cheap. Note that if they're both naive, offset1 ==
  2929. * offset2 == 0 at this point.
  2930. */
  2931. if (n1 == n2 && offset1 == offset2) {
  2932. diff = memcmp(self->data, ((PyDateTime_Time *)other)->data,
  2933. _PyDateTime_TIME_DATASIZE);
  2934. return diff_to_bool(diff, op);
  2935. }
  2936. if (n1 == OFFSET_AWARE && n2 == OFFSET_AWARE) {
  2937. assert(offset1 != offset2); /* else last "if" handled it */
  2938. /* Convert everything except microseconds to seconds. These
  2939. * can't overflow (no more than the # of seconds in 2 days).
  2940. */
  2941. offset1 = TIME_GET_HOUR(self) * 3600 +
  2942. (TIME_GET_MINUTE(self) - offset1) * 60 +
  2943. TIME_GET_SECOND(self);
  2944. offset2 = TIME_GET_HOUR(other) * 3600 +
  2945. (TIME_GET_MINUTE(other) - offset2) * 60 +
  2946. TIME_GET_SECOND(other);
  2947. diff = offset1 - offset2;
  2948. if (diff == 0)
  2949. diff = TIME_GET_MICROSECOND(self) -
  2950. TIME_GET_MICROSECOND(other);
  2951. return diff_to_bool(diff, op);
  2952. }
  2953. assert(n1 != n2);
  2954. PyErr_SetString(PyExc_TypeError,
  2955. "can't compare offset-naive and "
  2956. "offset-aware times");
  2957. return NULL;
  2958. }
  2959. static long
  2960. time_hash(PyDateTime_Time *self)
  2961. {
  2962. if (self->hashcode == -1) {
  2963. naivety n;
  2964. int offset;
  2965. PyObject *temp;
  2966. n = classify_utcoffset((PyObject *)self, Py_None, &offset);
  2967. assert(n != OFFSET_UNKNOWN);
  2968. if (n == OFFSET_ERROR)
  2969. return -1;
  2970. /* Reduce this to a hash of another object. */
  2971. if (offset == 0)
  2972. temp = PyString_FromStringAndSize((char *)self->data,
  2973. _PyDateTime_TIME_DATASIZE);
  2974. else {
  2975. int hour;
  2976. int minute;
  2977. assert(n == OFFSET_AWARE);
  2978. assert(HASTZINFO(self));
  2979. hour = divmod(TIME_GET_HOUR(self) * 60 +
  2980. TIME_GET_MINUTE(self) - offset,
  2981. 60,
  2982. &minute);
  2983. if (0 <= hour && hour < 24)
  2984. temp = new_time(hour, minute,
  2985. TIME_GET_SECOND(self),
  2986. TIME_GET_MICROSECOND(self),
  2987. Py_None);
  2988. else
  2989. temp = Py_BuildValue("iiii",
  2990. hour, minute,
  2991. TIME_GET_SECOND(self),
  2992. TIME_GET_MICROSECOND(self));
  2993. }
  2994. if (temp != NULL) {
  2995. self->hashcode = PyObject_Hash(temp);
  2996. Py_DECREF(temp);
  2997. }
  2998. }
  2999. return self->hashcode;
  3000. }
  3001. static PyObject *
  3002. time_replace(PyDateTime_Time *self, PyObject *args, PyObject *kw)
  3003. {
  3004. PyObject *clone;
  3005. PyObject *tuple;
  3006. int hh = TIME_GET_HOUR(self);
  3007. int mm = TIME_GET_MINUTE(self);
  3008. int ss = TIME_GET_SECOND(self);
  3009. int us = TIME_GET_MICROSECOND(self);
  3010. PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
  3011. if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO:replace",
  3012. time_kws,
  3013. &hh, &mm, &ss, &us, &tzinfo))
  3014. return NULL;
  3015. tuple = Py_BuildValue("iiiiO", hh, mm, ss, us, tzinfo);
  3016. if (tuple == NULL)
  3017. return NULL;
  3018. clone = time_new(Py_TYPE(self), tuple, NULL);
  3019. Py_DECREF(tuple);
  3020. return clone;
  3021. }
  3022. static int
  3023. time_nonzero(PyDateTime_Time *self)
  3024. {
  3025. int offset;
  3026. int none;
  3027. if (TIME_GET_SECOND(self) || TIME_GET_MICROSECOND(self)) {
  3028. /* Since utcoffset is in whole minutes, nothing can
  3029. * alter the conclusion that this is nonzero.
  3030. */
  3031. return 1;
  3032. }
  3033. offset = 0;
  3034. if (HASTZINFO(self) && self->tzinfo != Py_None) {
  3035. offset = call_utcoffset(self->tzinfo, Py_None, &none);
  3036. if (offset == -1 && PyErr_Occurred())
  3037. return -1;
  3038. }
  3039. return (TIME_GET_MINUTE(self) - offset + TIME_GET_HOUR(self)*60) != 0;
  3040. }
  3041. /* Pickle support, a simple use of __reduce__. */
  3042. /* Let basestate be the non-tzinfo data string.
  3043. * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
  3044. * So it's a tuple in any (non-error) case.
  3045. * __getstate__ isn't exposed.
  3046. */
  3047. static PyObject *
  3048. time_getstate(PyDateTime_Time *self)
  3049. {
  3050. PyObject *basestate;
  3051. PyObject *result = NULL;
  3052. basestate = PyString_FromStringAndSize((char *)self->data,
  3053. _PyDateTime_TIME_DATASIZE);
  3054. if (basestate != NULL) {
  3055. if (! HASTZINFO(self) || self->tzinfo == Py_None)
  3056. result = PyTuple_Pack(1, basestate);
  3057. else
  3058. result = PyTuple_Pack(2, basestate, self->tzinfo);
  3059. Py_DECREF(basestate);
  3060. }
  3061. return result;
  3062. }
  3063. static PyObject *
  3064. time_reduce(PyDateTime_Time *self, PyObject *arg)
  3065. {
  3066. return Py_BuildValue("(ON)", Py_TYPE(self), time_getstate(self));
  3067. }
  3068. static PyMethodDef time_methods[] = {
  3069. {"isoformat", (PyCFunction)time_isoformat, METH_NOARGS,
  3070. PyDoc_STR("Return string in ISO 8601 format, HH:MM:SS[.mmmmmm]"
  3071. "[+HH:MM].")},
  3072. {"strftime", (PyCFunction)time_strftime, METH_VARARGS | METH_KEYWORDS,
  3073. PyDoc_STR("format -> strftime() style string.")},
  3074. {"__format__", (PyCFunction)date_format, METH_VARARGS,
  3075. PyDoc_STR("Formats self with strftime.")},
  3076. {"utcoffset", (PyCFunction)time_utcoffset, METH_NOARGS,
  3077. PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
  3078. {"tzname", (PyCFunction)time_tzname, METH_NOARGS,
  3079. PyDoc_STR("Return self.tzinfo.tzname(self).")},
  3080. {"dst", (PyCFunction)time_dst, METH_NOARGS,
  3081. PyDoc_STR("Return self.tzinfo.dst(self).")},
  3082. {"replace", (PyCFunction)time_replace, METH_VARARGS | METH_KEYWORDS,
  3083. PyDoc_STR("Return time with new specified fields.")},
  3084. {"__reduce__", (PyCFunction)time_reduce, METH_NOARGS,
  3085. PyDoc_STR("__reduce__() -> (cls, state)")},
  3086. {NULL, NULL}
  3087. };
  3088. static char time_doc[] =
  3089. PyDoc_STR("time([hour[, minute[, second[, microsecond[, tzinfo]]]]]) --> a time object\n\
  3090. \n\
  3091. All arguments are optional. tzinfo may be None, or an instance of\n\
  3092. a tzinfo subclass. The remaining arguments may be ints or longs.\n");
  3093. static PyNumberMethods time_as_number = {
  3094. 0, /* nb_add */
  3095. 0, /* nb_subtract */
  3096. 0, /* nb_multiply */
  3097. 0, /* nb_divide */
  3098. 0, /* nb_remainder */
  3099. 0, /* nb_divmod */
  3100. 0, /* nb_power */
  3101. 0, /* nb_negative */
  3102. 0, /* nb_positive */
  3103. 0, /* nb_absolute */
  3104. (inquiry)time_nonzero, /* nb_nonzero */
  3105. };
  3106. statichere PyTypeObject PyDateTime_TimeType = {
  3107. PyObject_HEAD_INIT(NULL)
  3108. 0, /* ob_size */
  3109. "datetime.time", /* tp_name */
  3110. sizeof(PyDateTime_Time), /* tp_basicsize */
  3111. 0, /* tp_itemsize */
  3112. (destructor)time_dealloc, /* tp_dealloc */
  3113. 0, /* tp_print */
  3114. 0, /* tp_getattr */
  3115. 0, /* tp_setattr */
  3116. 0, /* tp_compare */
  3117. (reprfunc)time_repr, /* tp_repr */
  3118. &time_as_number, /* tp_as_number */
  3119. 0, /* tp_as_sequence */
  3120. 0, /* tp_as_mapping */
  3121. (hashfunc)time_hash, /* tp_hash */
  3122. 0, /* tp_call */
  3123. (reprfunc)time_str, /* tp_str */
  3124. PyObject_GenericGetAttr, /* tp_getattro */
  3125. 0, /* tp_setattro */
  3126. 0, /* tp_as_buffer */
  3127. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
  3128. Py_TPFLAGS_BASETYPE, /* tp_flags */
  3129. time_doc, /* tp_doc */
  3130. 0, /* tp_traverse */
  3131. 0, /* tp_clear */
  3132. (richcmpfunc)time_richcompare, /* tp_richcompare */
  3133. 0, /* tp_weaklistoffset */
  3134. 0, /* tp_iter */
  3135. 0, /* tp_iternext */
  3136. time_methods, /* tp_methods */
  3137. 0, /* tp_members */
  3138. time_getset, /* tp_getset */
  3139. 0, /* tp_base */
  3140. 0, /* tp_dict */
  3141. 0, /* tp_descr_get */
  3142. 0, /* tp_descr_set */
  3143. 0, /* tp_dictoffset */
  3144. 0, /* tp_init */
  3145. time_alloc, /* tp_alloc */
  3146. time_new, /* tp_new */
  3147. 0, /* tp_free */
  3148. };
  3149. /*
  3150. * PyDateTime_DateTime implementation.
  3151. */
  3152. /* Accessor properties. Properties for day, month, and year are inherited
  3153. * from date.
  3154. */
  3155. static PyObject *
  3156. datetime_hour(PyDateTime_DateTime *self, void *unused)
  3157. {
  3158. return PyInt_FromLong(DATE_GET_HOUR(self));
  3159. }
  3160. static PyObject *
  3161. datetime_minute(PyDateTime_DateTime *self, void *unused)
  3162. {
  3163. return PyInt_FromLong(DATE_GET_MINUTE(self));
  3164. }
  3165. static PyObject *
  3166. datetime_second(PyDateTime_DateTime *self, void *unused)
  3167. {
  3168. return PyInt_FromLong(DATE_GET_SECOND(self));
  3169. }
  3170. static PyObject *
  3171. datetime_microsecond(PyDateTime_DateTime *self, void *unused)
  3172. {
  3173. return PyInt_FromLong(DATE_GET_MICROSECOND(self));
  3174. }
  3175. static PyObject *
  3176. datetime_tzinfo(PyDateTime_DateTime *self, void *unused)
  3177. {
  3178. PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
  3179. Py_INCREF(result);
  3180. return result;
  3181. }
  3182. static PyGetSetDef datetime_getset[] = {
  3183. {"hour", (getter)datetime_hour},
  3184. {"minute", (getter)datetime_minute},
  3185. {"second", (getter)datetime_second},
  3186. {"microsecond", (getter)datetime_microsecond},
  3187. {"tzinfo", (getter)datetime_tzinfo},
  3188. {NULL}
  3189. };
  3190. /*
  3191. * Constructors.
  3192. */
  3193. static char *datetime_kws[] = {
  3194. "year", "month", "day", "hour", "minute", "second",
  3195. "microsecond", "tzinfo", NULL
  3196. };
  3197. static PyObject *
  3198. datetime_new(PyTypeObject *type, PyObject *args, PyObject *kw)
  3199. {
  3200. PyObject *self = NULL;
  3201. PyObject *state;
  3202. int year;
  3203. int month;
  3204. int day;
  3205. int hour = 0;
  3206. int minute = 0;
  3207. int second = 0;
  3208. int usecond = 0;
  3209. PyObject *tzinfo = Py_None;
  3210. /* Check for invocation from pickle with __getstate__ state */
  3211. if (PyTuple_GET_SIZE(args) >= 1 &&
  3212. PyTuple_GET_SIZE(args) <= 2 &&
  3213. PyString_Check(state = PyTuple_GET_ITEM(args, 0)) &&
  3214. PyString_GET_SIZE(state) == _PyDateTime_DATETIME_DATASIZE &&
  3215. MONTH_IS_SANE(PyString_AS_STRING(state)[2]))
  3216. {
  3217. PyDateTime_DateTime *me;
  3218. char aware;
  3219. if (PyTuple_GET_SIZE(args) == 2) {
  3220. tzinfo = PyTuple_GET_ITEM(args, 1);
  3221. if (check_tzinfo_subclass(tzinfo) < 0) {
  3222. PyErr_SetString(PyExc_TypeError, "bad "
  3223. "tzinfo state arg");
  3224. return NULL;
  3225. }
  3226. }
  3227. aware = (char)(tzinfo != Py_None);
  3228. me = (PyDateTime_DateTime *) (type->tp_alloc(type , aware));
  3229. if (me != NULL) {
  3230. char *pdata = PyString_AS_STRING(state);
  3231. memcpy(me->data, pdata, _PyDateTime_DATETIME_DATASIZE);
  3232. me->hashcode = -1;
  3233. me->hastzinfo = aware;
  3234. if (aware) {
  3235. Py_INCREF(tzinfo);
  3236. me->tzinfo = tzinfo;
  3237. }
  3238. }
  3239. return (PyObject *)me;
  3240. }
  3241. if (PyArg_ParseTupleAndKeywords(args, kw, "iii|iiiiO", datetime_kws,
  3242. &year, &month, &day, &hour, &minute,
  3243. &second, &usecond, &tzinfo)) {
  3244. if (check_date_args(year, month, day) < 0)
  3245. return NULL;
  3246. if (check_time_args(hour, minute, second, usecond) < 0)
  3247. return NULL;
  3248. if (check_tzinfo_subclass(tzinfo) < 0)
  3249. return NULL;
  3250. self = new_datetime_ex(year, month, day,
  3251. hour, minute, second, usecond,
  3252. tzinfo, type);
  3253. }
  3254. return self;
  3255. }
  3256. /* TM_FUNC is the shared type of localtime() and gmtime(). */
  3257. typedef struct tm *(*TM_FUNC)(const time_t *timer);
  3258. /* Internal helper.
  3259. * Build datetime from a time_t and a distinct count of microseconds.
  3260. * Pass localtime or gmtime for f, to control the interpretation of timet.
  3261. */
  3262. static PyObject *
  3263. datetime_from_timet_and_us(PyObject *cls, TM_FUNC f, time_t timet, int us,
  3264. PyObject *tzinfo)
  3265. {
  3266. struct tm *tm;
  3267. PyObject *result = NULL;
  3268. tm = f(&timet);
  3269. if (tm) {
  3270. /* The platform localtime/gmtime may insert leap seconds,
  3271. * indicated by tm->tm_sec > 59. We don't care about them,
  3272. * except to the extent that passing them on to the datetime
  3273. * constructor would raise ValueError for a reason that
  3274. * made no sense to the user.
  3275. */
  3276. if (tm->tm_sec > 59)
  3277. tm->tm_sec = 59;
  3278. result = PyObject_CallFunction(cls, "iiiiiiiO",
  3279. tm->tm_year + 1900,
  3280. tm->tm_mon + 1,
  3281. tm->tm_mday,
  3282. tm->tm_hour,
  3283. tm->tm_min,
  3284. tm->tm_sec,
  3285. us,
  3286. tzinfo);
  3287. }
  3288. else
  3289. PyErr_SetString(PyExc_ValueError,
  3290. "timestamp out of range for "
  3291. "platform localtime()/gmtime() function");
  3292. return result;
  3293. }
  3294. /* Internal helper.
  3295. * Build datetime from a Python timestamp. Pass localtime or gmtime for f,
  3296. * to control the interpretation of the timestamp. Since a double doesn't
  3297. * have enough bits to cover a datetime's full range of precision, it's
  3298. * better to call datetime_from_timet_and_us provided you have a way
  3299. * to get that much precision (e.g., C time() isn't good enough).
  3300. */
  3301. static PyObject *
  3302. datetime_from_timestamp(PyObject *cls, TM_FUNC f, double timestamp,
  3303. PyObject *tzinfo)
  3304. {
  3305. time_t timet;
  3306. double fraction;
  3307. int us;
  3308. timet = _PyTime_DoubleToTimet(timestamp);
  3309. if (timet == (time_t)-1 && PyErr_Occurred())
  3310. return NULL;
  3311. fraction = timestamp - (double)timet;
  3312. us = (int)round_to_long(fraction * 1e6);
  3313. if (us < 0) {
  3314. /* Truncation towards zero is not what we wanted
  3315. for negative numbers (Python's mod semantics) */
  3316. timet -= 1;
  3317. us += 1000000;
  3318. }
  3319. /* If timestamp is less than one microsecond smaller than a
  3320. * full second, round up. Otherwise, ValueErrors are raised
  3321. * for some floats. */
  3322. if (us == 1000000) {
  3323. timet += 1;
  3324. us = 0;
  3325. }
  3326. return datetime_from_timet_and_us(cls, f, timet, us, tzinfo);
  3327. }
  3328. /* Internal helper.
  3329. * Build most accurate possible datetime for current time. Pass localtime or
  3330. * gmtime for f as appropriate.
  3331. */
  3332. static PyObject *
  3333. datetime_best_possible(PyObject *cls, TM_FUNC f, PyObject *tzinfo)
  3334. {
  3335. #ifdef HAVE_GETTIMEOFDAY
  3336. struct timeval t;
  3337. #ifdef GETTIMEOFDAY_NO_TZ
  3338. gettimeofday(&t);
  3339. #else
  3340. gettimeofday(&t, (struct timezone *)NULL);
  3341. #endif
  3342. return datetime_from_timet_and_us(cls, f, t.tv_sec, (int)t.tv_usec,
  3343. tzinfo);
  3344. #else /* ! HAVE_GETTIMEOFDAY */
  3345. /* No flavor of gettimeofday exists on this platform. Python's
  3346. * time.time() does a lot of other platform tricks to get the
  3347. * best time it can on the platform, and we're not going to do
  3348. * better than that (if we could, the better code would belong
  3349. * in time.time()!) We're limited by the precision of a double,
  3350. * though.
  3351. */
  3352. PyObject *time;
  3353. double dtime;
  3354. time = time_time();
  3355. if (time == NULL)
  3356. return NULL;
  3357. dtime = PyFloat_AsDouble(time);
  3358. Py_DECREF(time);
  3359. if (dtime == -1.0 && PyErr_Occurred())
  3360. return NULL;
  3361. return datetime_from_timestamp(cls, f, dtime, tzinfo);
  3362. #endif /* ! HAVE_GETTIMEOFDAY */
  3363. }
  3364. /* Return best possible local time -- this isn't constrained by the
  3365. * precision of a timestamp.
  3366. */
  3367. static PyObject *
  3368. datetime_now(PyObject *cls, PyObject *args, PyObject *kw)
  3369. {
  3370. PyObject *self;
  3371. PyObject *tzinfo = Py_None;
  3372. static char *keywords[] = {"tz", NULL};
  3373. if (! PyArg_ParseTupleAndKeywords(args, kw, "|O:now", keywords,
  3374. &tzinfo))
  3375. return NULL;
  3376. if (check_tzinfo_subclass(tzinfo) < 0)
  3377. return NULL;
  3378. self = datetime_best_possible(cls,
  3379. tzinfo == Py_None ? localtime : gmtime,
  3380. tzinfo);
  3381. if (self != NULL && tzinfo != Py_None) {
  3382. /* Convert UTC to tzinfo's zone. */
  3383. PyObject *temp = self;
  3384. self = PyObject_CallMethod(tzinfo, "fromutc", "O", self);
  3385. Py_DECREF(temp);
  3386. }
  3387. return self;
  3388. }
  3389. /* Return best possible UTC time -- this isn't constrained by the
  3390. * precision of a timestamp.
  3391. */
  3392. static PyObject *
  3393. datetime_utcnow(PyObject *cls, PyObject *dummy)
  3394. {
  3395. return datetime_best_possible(cls, gmtime, Py_None);
  3396. }
  3397. /* Return new local datetime from timestamp (Python timestamp -- a double). */
  3398. static PyObject *
  3399. datetime_fromtimestamp(PyObject *cls, PyObject *args, PyObject *kw)
  3400. {
  3401. PyObject *self;
  3402. double timestamp;
  3403. PyObject *tzinfo = Py_None;
  3404. static char *keywords[] = {"timestamp", "tz", NULL};
  3405. if (! PyArg_ParseTupleAndKeywords(args, kw, "d|O:fromtimestamp",
  3406. keywords, &timestamp, &tzinfo))
  3407. return NULL;
  3408. if (check_tzinfo_subclass(tzinfo) < 0)
  3409. return NULL;
  3410. self = datetime_from_timestamp(cls,
  3411. tzinfo == Py_None ? localtime : gmtime,
  3412. timestamp,
  3413. tzinfo);
  3414. if (self != NULL && tzinfo != Py_None) {
  3415. /* Convert UTC to tzinfo's zone. */
  3416. PyObject *temp = self;
  3417. self = PyObject_CallMethod(tzinfo, "fromutc", "O", self);
  3418. Py_DECREF(temp);
  3419. }
  3420. return self;
  3421. }
  3422. /* Return new UTC datetime from timestamp (Python timestamp -- a double). */
  3423. static PyObject *
  3424. datetime_utcfromtimestamp(PyObject *cls, PyObject *args)
  3425. {
  3426. double timestamp;
  3427. PyObject *result = NULL;
  3428. if (PyArg_ParseTuple(args, "d:utcfromtimestamp", &timestamp))
  3429. result = datetime_from_timestamp(cls, gmtime, timestamp,
  3430. Py_None);
  3431. return result;
  3432. }
  3433. /* Return new datetime from time.strptime(). */
  3434. static PyObject *
  3435. datetime_strptime(PyObject *cls, PyObject *args)
  3436. {
  3437. static PyObject *module = NULL;
  3438. PyObject *result = NULL, *obj, *st = NULL, *frac = NULL;
  3439. const char *string, *format;
  3440. if (!PyArg_ParseTuple(args, "ss:strptime", &string, &format))
  3441. return NULL;
  3442. if (module == NULL &&
  3443. (module = PyImport_ImportModuleNoBlock("_strptime")) == NULL)
  3444. return NULL;
  3445. /* _strptime._strptime returns a two-element tuple. The first
  3446. element is a time.struct_time object. The second is the
  3447. microseconds (which are not defined for time.struct_time). */
  3448. obj = PyObject_CallMethod(module, "_strptime", "ss", string, format);
  3449. if (obj != NULL) {
  3450. int i, good_timetuple = 1;
  3451. long int ia[7];
  3452. if (PySequence_Check(obj) && PySequence_Size(obj) == 2) {
  3453. st = PySequence_GetItem(obj, 0);
  3454. frac = PySequence_GetItem(obj, 1);
  3455. if (st == NULL || frac == NULL)
  3456. good_timetuple = 0;
  3457. /* copy y/m/d/h/m/s values out of the
  3458. time.struct_time */
  3459. if (good_timetuple &&
  3460. PySequence_Check(st) &&
  3461. PySequence_Size(st) >= 6) {
  3462. for (i=0; i < 6; i++) {
  3463. PyObject *p = PySequence_GetItem(st, i);
  3464. if (p == NULL) {
  3465. good_timetuple = 0;
  3466. break;
  3467. }
  3468. if (PyInt_Check(p))
  3469. ia[i] = PyInt_AsLong(p);
  3470. else
  3471. good_timetuple = 0;
  3472. Py_DECREF(p);
  3473. }
  3474. }
  3475. else
  3476. good_timetuple = 0;
  3477. /* follow that up with a little dose of microseconds */
  3478. if (PyInt_Check(frac))
  3479. ia[6] = PyInt_AsLong(frac);
  3480. else
  3481. good_timetuple = 0;
  3482. }
  3483. else
  3484. good_timetuple = 0;
  3485. if (good_timetuple)
  3486. result = PyObject_CallFunction(cls, "iiiiiii",
  3487. ia[0], ia[1], ia[2],
  3488. ia[3], ia[4], ia[5],
  3489. ia[6]);
  3490. else
  3491. PyErr_SetString(PyExc_ValueError,
  3492. "unexpected value from _strptime._strptime");
  3493. }
  3494. Py_XDECREF(obj);
  3495. Py_XDECREF(st);
  3496. Py_XDECREF(frac);
  3497. return result;
  3498. }
  3499. /* Return new datetime from date/datetime and time arguments. */
  3500. static PyObject *
  3501. datetime_combine(PyObject *cls, PyObject *args, PyObject *kw)
  3502. {
  3503. static char *keywords[] = {"date", "time", NULL};
  3504. PyObject *date;
  3505. PyObject *time;
  3506. PyObject *result = NULL;
  3507. if (PyArg_ParseTupleAndKeywords(args, kw, "O!O!:combine", keywords,
  3508. &PyDateTime_DateType, &date,
  3509. &PyDateTime_TimeType, &time)) {
  3510. PyObject *tzinfo = Py_None;
  3511. if (HASTZINFO(time))
  3512. tzinfo = ((PyDateTime_Time *)time)->tzinfo;
  3513. result = PyObject_CallFunction(cls, "iiiiiiiO",
  3514. GET_YEAR(date),
  3515. GET_MONTH(date),
  3516. GET_DAY(date),
  3517. TIME_GET_HOUR(time),
  3518. TIME_GET_MINUTE(time),
  3519. TIME_GET_SECOND(time),
  3520. TIME_GET_MICROSECOND(time),
  3521. tzinfo);
  3522. }
  3523. return result;
  3524. }
  3525. /*
  3526. * Destructor.
  3527. */
  3528. static void
  3529. datetime_dealloc(PyDateTime_DateTime *self)
  3530. {
  3531. if (HASTZINFO(self)) {
  3532. Py_XDECREF(self->tzinfo);
  3533. }
  3534. Py_TYPE(self)->tp_free((PyObject *)self);
  3535. }
  3536. /*
  3537. * Indirect access to tzinfo methods.
  3538. */
  3539. /* These are all METH_NOARGS, so don't need to check the arglist. */
  3540. static PyObject *
  3541. datetime_utcoffset(PyDateTime_DateTime *self, PyObject *unused) {
  3542. return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
  3543. "utcoffset", (PyObject *)self);
  3544. }
  3545. static PyObject *
  3546. datetime_dst(PyDateTime_DateTime *self, PyObject *unused) {
  3547. return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
  3548. "dst", (PyObject *)self);
  3549. }
  3550. static PyObject *
  3551. datetime_tzname(PyDateTime_DateTime *self, PyObject *unused) {
  3552. return call_tzname(HASTZINFO(self) ? self->tzinfo : Py_None,
  3553. (PyObject *)self);
  3554. }
  3555. /*
  3556. * datetime arithmetic.
  3557. */
  3558. /* factor must be 1 (to add) or -1 (to subtract). The result inherits
  3559. * the tzinfo state of date.
  3560. */
  3561. static PyObject *
  3562. add_datetime_timedelta(PyDateTime_DateTime *date, PyDateTime_Delta *delta,
  3563. int factor)
  3564. {
  3565. /* Note that the C-level additions can't overflow, because of
  3566. * invariant bounds on the member values.
  3567. */
  3568. int year = GET_YEAR(date);
  3569. int month = GET_MONTH(date);
  3570. int day = GET_DAY(date) + GET_TD_DAYS(delta) * factor;
  3571. int hour = DATE_GET_HOUR(date);
  3572. int minute = DATE_GET_MINUTE(date);
  3573. int second = DATE_GET_SECOND(date) + GET_TD_SECONDS(delta) * factor;
  3574. int microsecond = DATE_GET_MICROSECOND(date) +
  3575. GET_TD_MICROSECONDS(delta) * factor;
  3576. assert(factor == 1 || factor == -1);
  3577. if (normalize_datetime(&year, &month, &day,
  3578. &hour, &minute, &second, &microsecond) < 0)
  3579. return NULL;
  3580. else
  3581. return new_datetime(year, month, day,
  3582. hour, minute, second, microsecond,
  3583. HASTZINFO(date) ? date->tzinfo : Py_None);
  3584. }
  3585. static PyObject *
  3586. datetime_add(PyObject *left, PyObject *right)
  3587. {
  3588. if (PyDateTime_Check(left)) {
  3589. /* datetime + ??? */
  3590. if (PyDelta_Check(right))
  3591. /* datetime + delta */
  3592. return add_datetime_timedelta(
  3593. (PyDateTime_DateTime *)left,
  3594. (PyDateTime_Delta *)right,
  3595. 1);
  3596. }
  3597. else if (PyDelta_Check(left)) {
  3598. /* delta + datetime */
  3599. return add_datetime_timedelta((PyDateTime_DateTime *) right,
  3600. (PyDateTime_Delta *) left,
  3601. 1);
  3602. }
  3603. Py_INCREF(Py_NotImplemented);
  3604. return Py_NotImplemented;
  3605. }
  3606. static PyObject *
  3607. datetime_subtract(PyObject *left, PyObject *right)
  3608. {
  3609. PyObject *result = Py_NotImplemented;
  3610. if (PyDateTime_Check(left)) {
  3611. /* datetime - ??? */
  3612. if (PyDateTime_Check(right)) {
  3613. /* datetime - datetime */
  3614. naivety n1, n2;
  3615. int offset1, offset2;
  3616. int delta_d, delta_s, delta_us;
  3617. if (classify_two_utcoffsets(left, &offset1, &n1, left,
  3618. right, &offset2, &n2,
  3619. right) < 0)
  3620. return NULL;
  3621. assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
  3622. if (n1 != n2) {
  3623. PyErr_SetString(PyExc_TypeError,
  3624. "can't subtract offset-naive and "
  3625. "offset-aware datetimes");
  3626. return NULL;
  3627. }
  3628. delta_d = ymd_to_ord(GET_YEAR(left),
  3629. GET_MONTH(left),
  3630. GET_DAY(left)) -
  3631. ymd_to_ord(GET_YEAR(right),
  3632. GET_MONTH(right),
  3633. GET_DAY(right));
  3634. /* These can't overflow, since the values are
  3635. * normalized. At most this gives the number of
  3636. * seconds in one day.
  3637. */
  3638. delta_s = (DATE_GET_HOUR(left) -
  3639. DATE_GET_HOUR(right)) * 3600 +
  3640. (DATE_GET_MINUTE(left) -
  3641. DATE_GET_MINUTE(right)) * 60 +
  3642. (DATE_GET_SECOND(left) -
  3643. DATE_GET_SECOND(right));
  3644. delta_us = DATE_GET_MICROSECOND(left) -
  3645. DATE_GET_MICROSECOND(right);
  3646. /* (left - offset1) - (right - offset2) =
  3647. * (left - right) + (offset2 - offset1)
  3648. */
  3649. delta_s += (offset2 - offset1) * 60;
  3650. result = new_delta(delta_d, delta_s, delta_us, 1);
  3651. }
  3652. else if (PyDelta_Check(right)) {
  3653. /* datetime - delta */
  3654. result = add_datetime_timedelta(
  3655. (PyDateTime_DateTime *)left,
  3656. (PyDateTime_Delta *)right,
  3657. -1);
  3658. }
  3659. }
  3660. if (result == Py_NotImplemented)
  3661. Py_INCREF(result);
  3662. return result;
  3663. }
  3664. /* Various ways to turn a datetime into a string. */
  3665. static PyObject *
  3666. datetime_repr(PyDateTime_DateTime *self)
  3667. {
  3668. char buffer[1000];
  3669. const char *type_name = Py_TYPE(self)->tp_name;
  3670. PyObject *baserepr;
  3671. if (DATE_GET_MICROSECOND(self)) {
  3672. PyOS_snprintf(buffer, sizeof(buffer),
  3673. "%s(%d, %d, %d, %d, %d, %d, %d)",
  3674. type_name,
  3675. GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
  3676. DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
  3677. DATE_GET_SECOND(self),
  3678. DATE_GET_MICROSECOND(self));
  3679. }
  3680. else if (DATE_GET_SECOND(self)) {
  3681. PyOS_snprintf(buffer, sizeof(buffer),
  3682. "%s(%d, %d, %d, %d, %d, %d)",
  3683. type_name,
  3684. GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
  3685. DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
  3686. DATE_GET_SECOND(self));
  3687. }
  3688. else {
  3689. PyOS_snprintf(buffer, sizeof(buffer),
  3690. "%s(%d, %d, %d, %d, %d)",
  3691. type_name,
  3692. GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
  3693. DATE_GET_HOUR(self), DATE_GET_MINUTE(self));
  3694. }
  3695. baserepr = PyString_FromString(buffer);
  3696. if (baserepr == NULL || ! HASTZINFO(self))
  3697. return baserepr;
  3698. return append_keyword_tzinfo(baserepr, self->tzinfo);
  3699. }
  3700. static PyObject *
  3701. datetime_str(PyDateTime_DateTime *self)
  3702. {
  3703. return PyObject_CallMethod((PyObject *)self, "isoformat", "(s)", " ");
  3704. }
  3705. static PyObject *
  3706. datetime_isoformat(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
  3707. {
  3708. char sep = 'T';
  3709. static char *keywords[] = {"sep", NULL};
  3710. char buffer[100];
  3711. char *cp;
  3712. PyObject *result;
  3713. if (!PyArg_ParseTupleAndKeywords(args, kw, "|c:isoformat", keywords,
  3714. &sep))
  3715. return NULL;
  3716. cp = isoformat_date((PyDateTime_Date *)self, buffer, sizeof(buffer));
  3717. assert(cp != NULL);
  3718. *cp++ = sep;
  3719. isoformat_time(self, cp, sizeof(buffer) - (cp - buffer));
  3720. result = PyString_FromString(buffer);
  3721. if (result == NULL || ! HASTZINFO(self))
  3722. return result;
  3723. /* We need to append the UTC offset. */
  3724. if (format_utcoffset(buffer, sizeof(buffer), ":", self->tzinfo,
  3725. (PyObject *)self) < 0) {
  3726. Py_DECREF(result);
  3727. return NULL;
  3728. }
  3729. PyString_ConcatAndDel(&result, PyString_FromString(buffer));
  3730. return result;
  3731. }
  3732. static PyObject *
  3733. datetime_ctime(PyDateTime_DateTime *self)
  3734. {
  3735. return format_ctime((PyDateTime_Date *)self,
  3736. DATE_GET_HOUR(self),
  3737. DATE_GET_MINUTE(self),
  3738. DATE_GET_SECOND(self));
  3739. }
  3740. /* Miscellaneous methods. */
  3741. /* This is more natural as a tp_compare, but doesn't work then: for whatever
  3742. * reason, Python's try_3way_compare ignores tp_compare unless
  3743. * PyInstance_Check returns true, but these aren't old-style classes.
  3744. */
  3745. static PyObject *
  3746. datetime_richcompare(PyDateTime_DateTime *self, PyObject *other, int op)
  3747. {
  3748. int diff;
  3749. naivety n1, n2;
  3750. int offset1, offset2;
  3751. if (! PyDateTime_Check(other)) {
  3752. /* If other has a "timetuple" attr, that's an advertised
  3753. * hook for other classes to ask to get comparison control.
  3754. * However, date instances have a timetuple attr, and we
  3755. * don't want to allow that comparison. Because datetime
  3756. * is a subclass of date, when mixing date and datetime
  3757. * in a comparison, Python gives datetime the first shot
  3758. * (it's the more specific subtype). So we can stop that
  3759. * combination here reliably.
  3760. */
  3761. if (PyObject_HasAttrString(other, "timetuple") &&
  3762. ! PyDate_Check(other)) {
  3763. /* A hook for other kinds of datetime objects. */
  3764. Py_INCREF(Py_NotImplemented);
  3765. return Py_NotImplemented;
  3766. }
  3767. if (op == Py_EQ || op == Py_NE) {
  3768. PyObject *result = op == Py_EQ ? Py_False : Py_True;
  3769. Py_INCREF(result);
  3770. return result;
  3771. }
  3772. /* Stop this from falling back to address comparison. */
  3773. return cmperror((PyObject *)self, other);
  3774. }
  3775. if (classify_two_utcoffsets((PyObject *)self, &offset1, &n1,
  3776. (PyObject *)self,
  3777. other, &offset2, &n2,
  3778. other) < 0)
  3779. return NULL;
  3780. assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
  3781. /* If they're both naive, or both aware and have the same offsets,
  3782. * we get off cheap. Note that if they're both naive, offset1 ==
  3783. * offset2 == 0 at this point.
  3784. */
  3785. if (n1 == n2 && offset1 == offset2) {
  3786. diff = memcmp(self->data, ((PyDateTime_DateTime *)other)->data,
  3787. _PyDateTime_DATETIME_DATASIZE);
  3788. return diff_to_bool(diff, op);
  3789. }
  3790. if (n1 == OFFSET_AWARE && n2 == OFFSET_AWARE) {
  3791. PyDateTime_Delta *delta;
  3792. assert(offset1 != offset2); /* else last "if" handled it */
  3793. delta = (PyDateTime_Delta *)datetime_subtract((PyObject *)self,
  3794. other);
  3795. if (delta == NULL)
  3796. return NULL;
  3797. diff = GET_TD_DAYS(delta);
  3798. if (diff == 0)
  3799. diff = GET_TD_SECONDS(delta) |
  3800. GET_TD_MICROSECONDS(delta);
  3801. Py_DECREF(delta);
  3802. return diff_to_bool(diff, op);
  3803. }
  3804. assert(n1 != n2);
  3805. PyErr_SetString(PyExc_TypeError,
  3806. "can't compare offset-naive and "
  3807. "offset-aware datetimes");
  3808. return NULL;
  3809. }
  3810. static long
  3811. datetime_hash(PyDateTime_DateTime *self)
  3812. {
  3813. if (self->hashcode == -1) {
  3814. naivety n;
  3815. int offset;
  3816. PyObject *temp;
  3817. n = classify_utcoffset((PyObject *)self, (PyObject *)self,
  3818. &offset);
  3819. assert(n != OFFSET_UNKNOWN);
  3820. if (n == OFFSET_ERROR)
  3821. return -1;
  3822. /* Reduce this to a hash of another object. */
  3823. if (n == OFFSET_NAIVE)
  3824. temp = PyString_FromStringAndSize(
  3825. (char *)self->data,
  3826. _PyDateTime_DATETIME_DATASIZE);
  3827. else {
  3828. int days;
  3829. int seconds;
  3830. assert(n == OFFSET_AWARE);
  3831. assert(HASTZINFO(self));
  3832. days = ymd_to_ord(GET_YEAR(self),
  3833. GET_MONTH(self),
  3834. GET_DAY(self));
  3835. seconds = DATE_GET_HOUR(self) * 3600 +
  3836. (DATE_GET_MINUTE(self) - offset) * 60 +
  3837. DATE_GET_SECOND(self);
  3838. temp = new_delta(days,
  3839. seconds,
  3840. DATE_GET_MICROSECOND(self),
  3841. 1);
  3842. }
  3843. if (temp != NULL) {
  3844. self->hashcode = PyObject_Hash(temp);
  3845. Py_DECREF(temp);
  3846. }
  3847. }
  3848. return self->hashcode;
  3849. }
  3850. static PyObject *
  3851. datetime_replace(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
  3852. {
  3853. PyObject *clone;
  3854. PyObject *tuple;
  3855. int y = GET_YEAR(self);
  3856. int m = GET_MONTH(self);
  3857. int d = GET_DAY(self);
  3858. int hh = DATE_GET_HOUR(self);
  3859. int mm = DATE_GET_MINUTE(self);
  3860. int ss = DATE_GET_SECOND(self);
  3861. int us = DATE_GET_MICROSECOND(self);
  3862. PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
  3863. if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiiiiO:replace",
  3864. datetime_kws,
  3865. &y, &m, &d, &hh, &mm, &ss, &us,
  3866. &tzinfo))
  3867. return NULL;
  3868. tuple = Py_BuildValue("iiiiiiiO", y, m, d, hh, mm, ss, us, tzinfo);
  3869. if (tuple == NULL)
  3870. return NULL;
  3871. clone = datetime_new(Py_TYPE(self), tuple, NULL);
  3872. Py_DECREF(tuple);
  3873. return clone;
  3874. }
  3875. static PyObject *
  3876. datetime_astimezone(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
  3877. {
  3878. int y, m, d, hh, mm, ss, us;
  3879. PyObject *result;
  3880. int offset, none;
  3881. PyObject *tzinfo;
  3882. static char *keywords[] = {"tz", NULL};
  3883. if (! PyArg_ParseTupleAndKeywords(args, kw, "O!:astimezone", keywords,
  3884. &PyDateTime_TZInfoType, &tzinfo))
  3885. return NULL;
  3886. if (!HASTZINFO(self) || self->tzinfo == Py_None)
  3887. goto NeedAware;
  3888. /* Conversion to self's own time zone is a NOP. */
  3889. if (self->tzinfo == tzinfo) {
  3890. Py_INCREF(self);
  3891. return (PyObject *)self;
  3892. }
  3893. /* Convert self to UTC. */
  3894. offset = call_utcoffset(self->tzinfo, (PyObject *)self, &none);
  3895. if (offset == -1 && PyErr_Occurred())
  3896. return NULL;
  3897. if (none)
  3898. goto NeedAware;
  3899. y = GET_YEAR(self);
  3900. m = GET_MONTH(self);
  3901. d = GET_DAY(self);
  3902. hh = DATE_GET_HOUR(self);
  3903. mm = DATE_GET_MINUTE(self);
  3904. ss = DATE_GET_SECOND(self);
  3905. us = DATE_GET_MICROSECOND(self);
  3906. mm -= offset;
  3907. if ((mm < 0 || mm >= 60) &&
  3908. normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
  3909. return NULL;
  3910. /* Attach new tzinfo and let fromutc() do the rest. */
  3911. result = new_datetime(y, m, d, hh, mm, ss, us, tzinfo);
  3912. if (result != NULL) {
  3913. PyObject *temp = result;
  3914. result = PyObject_CallMethod(tzinfo, "fromutc", "O", temp);
  3915. Py_DECREF(temp);
  3916. }
  3917. return result;
  3918. NeedAware:
  3919. PyErr_SetString(PyExc_ValueError, "astimezone() cannot be applied to "
  3920. "a naive datetime");
  3921. return NULL;
  3922. }
  3923. static PyObject *
  3924. datetime_timetuple(PyDateTime_DateTime *self)
  3925. {
  3926. int dstflag = -1;
  3927. if (HASTZINFO(self) && self->tzinfo != Py_None) {
  3928. int none;
  3929. dstflag = call_dst(self->tzinfo, (PyObject *)self, &none);
  3930. if (dstflag == -1 && PyErr_Occurred())
  3931. return NULL;
  3932. if (none)
  3933. dstflag = -1;
  3934. else if (dstflag != 0)
  3935. dstflag = 1;
  3936. }
  3937. return build_struct_time(GET_YEAR(self),
  3938. GET_MONTH(self),
  3939. GET_DAY(self),
  3940. DATE_GET_HOUR(self),
  3941. DATE_GET_MINUTE(self),
  3942. DATE_GET_SECOND(self),
  3943. dstflag);
  3944. }
  3945. static PyObject *
  3946. datetime_getdate(PyDateTime_DateTime *self)
  3947. {
  3948. return new_date(GET_YEAR(self),
  3949. GET_MONTH(self),
  3950. GET_DAY(self));
  3951. }
  3952. static PyObject *
  3953. datetime_gettime(PyDateTime_DateTime *self)
  3954. {
  3955. return new_time(DATE_GET_HOUR(self),
  3956. DATE_GET_MINUTE(self),
  3957. DATE_GET_SECOND(self),
  3958. DATE_GET_MICROSECOND(self),
  3959. Py_None);
  3960. }
  3961. static PyObject *
  3962. datetime_gettimetz(PyDateTime_DateTime *self)
  3963. {
  3964. return new_time(DATE_GET_HOUR(self),
  3965. DATE_GET_MINUTE(self),
  3966. DATE_GET_SECOND(self),
  3967. DATE_GET_MICROSECOND(self),
  3968. HASTZINFO(self) ? self->tzinfo : Py_None);
  3969. }
  3970. static PyObject *
  3971. datetime_utctimetuple(PyDateTime_DateTime *self)
  3972. {
  3973. int y = GET_YEAR(self);
  3974. int m = GET_MONTH(self);
  3975. int d = GET_DAY(self);
  3976. int hh = DATE_GET_HOUR(self);
  3977. int mm = DATE_GET_MINUTE(self);
  3978. int ss = DATE_GET_SECOND(self);
  3979. int us = 0; /* microseconds are ignored in a timetuple */
  3980. int offset = 0;
  3981. if (HASTZINFO(self) && self->tzinfo != Py_None) {
  3982. int none;
  3983. offset = call_utcoffset(self->tzinfo, (PyObject *)self, &none);
  3984. if (offset == -1 && PyErr_Occurred())
  3985. return NULL;
  3986. }
  3987. /* Even if offset is 0, don't call timetuple() -- tm_isdst should be
  3988. * 0 in a UTC timetuple regardless of what dst() says.
  3989. */
  3990. if (offset) {
  3991. /* Subtract offset minutes & normalize. */
  3992. int stat;
  3993. mm -= offset;
  3994. stat = normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us);
  3995. if (stat < 0) {
  3996. /* At the edges, it's possible we overflowed
  3997. * beyond MINYEAR or MAXYEAR.
  3998. */
  3999. if (PyErr_ExceptionMatches(PyExc_OverflowError))
  4000. PyErr_Clear();
  4001. else
  4002. return NULL;
  4003. }
  4004. }
  4005. return build_struct_time(y, m, d, hh, mm, ss, 0);
  4006. }
  4007. /* Pickle support, a simple use of __reduce__. */
  4008. /* Let basestate be the non-tzinfo data string.
  4009. * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
  4010. * So it's a tuple in any (non-error) case.
  4011. * __getstate__ isn't exposed.
  4012. */
  4013. static PyObject *
  4014. datetime_getstate(PyDateTime_DateTime *self)
  4015. {
  4016. PyObject *basestate;
  4017. PyObject *result = NULL;
  4018. basestate = PyString_FromStringAndSize((char *)self->data,
  4019. _PyDateTime_DATETIME_DATASIZE);
  4020. if (basestate != NULL) {
  4021. if (! HASTZINFO(self) || self->tzinfo == Py_None)
  4022. result = PyTuple_Pack(1, basestate);
  4023. else
  4024. result = PyTuple_Pack(2, basestate, self->tzinfo);
  4025. Py_DECREF(basestate);
  4026. }
  4027. return result;
  4028. }
  4029. static PyObject *
  4030. datetime_reduce(PyDateTime_DateTime *self, PyObject *arg)
  4031. {
  4032. return Py_BuildValue("(ON)", Py_TYPE(self), datetime_getstate(self));
  4033. }
  4034. static PyMethodDef datetime_methods[] = {
  4035. /* Class methods: */
  4036. {"now", (PyCFunction)datetime_now,
  4037. METH_VARARGS | METH_KEYWORDS | METH_CLASS,
  4038. PyDoc_STR("[tz] -> new datetime with tz's local day and time.")},
  4039. {"utcnow", (PyCFunction)datetime_utcnow,
  4040. METH_NOARGS | METH_CLASS,
  4041. PyDoc_STR("Return a new datetime representing UTC day and time.")},
  4042. {"fromtimestamp", (PyCFunction)datetime_fromtimestamp,
  4043. METH_VARARGS | METH_KEYWORDS | METH_CLASS,
  4044. PyDoc_STR("timestamp[, tz] -> tz's local time from POSIX timestamp.")},
  4045. {"utcfromtimestamp", (PyCFunction)datetime_utcfromtimestamp,
  4046. METH_VARARGS | METH_CLASS,
  4047. PyDoc_STR("timestamp -> UTC datetime from a POSIX timestamp "
  4048. "(like time.time()).")},
  4049. {"strptime", (PyCFunction)datetime_strptime,
  4050. METH_VARARGS | METH_CLASS,
  4051. PyDoc_STR("string, format -> new datetime parsed from a string "
  4052. "(like time.strptime()).")},
  4053. {"combine", (PyCFunction)datetime_combine,
  4054. METH_VARARGS | METH_KEYWORDS | METH_CLASS,
  4055. PyDoc_STR("date, time -> datetime with same date and time fields")},
  4056. /* Instance methods: */
  4057. {"date", (PyCFunction)datetime_getdate, METH_NOARGS,
  4058. PyDoc_STR("Return date object with same year, month and day.")},
  4059. {"time", (PyCFunction)datetime_gettime, METH_NOARGS,
  4060. PyDoc_STR("Return time object with same time but with tzinfo=None.")},
  4061. {"timetz", (PyCFunction)datetime_gettimetz, METH_NOARGS,
  4062. PyDoc_STR("Return time object with same time and tzinfo.")},
  4063. {"ctime", (PyCFunction)datetime_ctime, METH_NOARGS,
  4064. PyDoc_STR("Return ctime() style string.")},
  4065. {"timetuple", (PyCFunction)datetime_timetuple, METH_NOARGS,
  4066. PyDoc_STR("Return time tuple, compatible with time.localtime().")},
  4067. {"utctimetuple", (PyCFunction)datetime_utctimetuple, METH_NOARGS,
  4068. PyDoc_STR("Return UTC time tuple, compatible with time.localtime().")},
  4069. {"isoformat", (PyCFunction)datetime_isoformat, METH_VARARGS | METH_KEYWORDS,
  4070. PyDoc_STR("[sep] -> string in ISO 8601 format, "
  4071. "YYYY-MM-DDTHH:MM:SS[.mmmmmm][+HH:MM].\n\n"
  4072. "sep is used to separate the year from the time, and "
  4073. "defaults to 'T'.")},
  4074. {"utcoffset", (PyCFunction)datetime_utcoffset, METH_NOARGS,
  4075. PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
  4076. {"tzname", (PyCFunction)datetime_tzname, METH_NOARGS,
  4077. PyDoc_STR("Return self.tzinfo.tzname(self).")},
  4078. {"dst", (PyCFunction)datetime_dst, METH_NOARGS,
  4079. PyDoc_STR("Return self.tzinfo.dst(self).")},
  4080. {"replace", (PyCFunction)datetime_replace, METH_VARARGS | METH_KEYWORDS,
  4081. PyDoc_STR("Return datetime with new specified fields.")},
  4082. {"astimezone", (PyCFunction)datetime_astimezone, METH_VARARGS | METH_KEYWORDS,
  4083. PyDoc_STR("tz -> convert to local time in new timezone tz\n")},
  4084. {"__reduce__", (PyCFunction)datetime_reduce, METH_NOARGS,
  4085. PyDoc_STR("__reduce__() -> (cls, state)")},
  4086. {NULL, NULL}
  4087. };
  4088. static char datetime_doc[] =
  4089. PyDoc_STR("datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]])\n\
  4090. \n\
  4091. The year, month and day arguments are required. tzinfo may be None, or an\n\
  4092. instance of a tzinfo subclass. The remaining arguments may be ints or longs.\n");
  4093. static PyNumberMethods datetime_as_number = {
  4094. datetime_add, /* nb_add */
  4095. datetime_subtract, /* nb_subtract */
  4096. 0, /* nb_multiply */
  4097. 0, /* nb_divide */
  4098. 0, /* nb_remainder */
  4099. 0, /* nb_divmod */
  4100. 0, /* nb_power */
  4101. 0, /* nb_negative */
  4102. 0, /* nb_positive */
  4103. 0, /* nb_absolute */
  4104. 0, /* nb_nonzero */
  4105. };
  4106. statichere PyTypeObject PyDateTime_DateTimeType = {
  4107. PyObject_HEAD_INIT(NULL)
  4108. 0, /* ob_size */
  4109. "datetime.datetime", /* tp_name */
  4110. sizeof(PyDateTime_DateTime), /* tp_basicsize */
  4111. 0, /* tp_itemsize */
  4112. (destructor)datetime_dealloc, /* tp_dealloc */
  4113. 0, /* tp_print */
  4114. 0, /* tp_getattr */
  4115. 0, /* tp_setattr */
  4116. 0, /* tp_compare */
  4117. (reprfunc)datetime_repr, /* tp_repr */
  4118. &datetime_as_number, /* tp_as_number */
  4119. 0, /* tp_as_sequence */
  4120. 0, /* tp_as_mapping */
  4121. (hashfunc)datetime_hash, /* tp_hash */
  4122. 0, /* tp_call */
  4123. (reprfunc)datetime_str, /* tp_str */
  4124. PyObject_GenericGetAttr, /* tp_getattro */
  4125. 0, /* tp_setattro */
  4126. 0, /* tp_as_buffer */
  4127. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
  4128. Py_TPFLAGS_BASETYPE, /* tp_flags */
  4129. datetime_doc, /* tp_doc */
  4130. 0, /* tp_traverse */
  4131. 0, /* tp_clear */
  4132. (richcmpfunc)datetime_richcompare, /* tp_richcompare */
  4133. 0, /* tp_weaklistoffset */
  4134. 0, /* tp_iter */
  4135. 0, /* tp_iternext */
  4136. datetime_methods, /* tp_methods */
  4137. 0, /* tp_members */
  4138. datetime_getset, /* tp_getset */
  4139. &PyDateTime_DateType, /* tp_base */
  4140. 0, /* tp_dict */
  4141. 0, /* tp_descr_get */
  4142. 0, /* tp_descr_set */
  4143. 0, /* tp_dictoffset */
  4144. 0, /* tp_init */
  4145. datetime_alloc, /* tp_alloc */
  4146. datetime_new, /* tp_new */
  4147. 0, /* tp_free */
  4148. };
  4149. /* ---------------------------------------------------------------------------
  4150. * Module methods and initialization.
  4151. */
  4152. static PyMethodDef module_methods[] = {
  4153. {NULL, NULL}
  4154. };
  4155. /* C API. Clients get at this via PyDateTime_IMPORT, defined in
  4156. * datetime.h.
  4157. */
  4158. static PyDateTime_CAPI CAPI = {
  4159. &PyDateTime_DateType,
  4160. &PyDateTime_DateTimeType,
  4161. &PyDateTime_TimeType,
  4162. &PyDateTime_DeltaType,
  4163. &PyDateTime_TZInfoType,
  4164. new_date_ex,
  4165. new_datetime_ex,
  4166. new_time_ex,
  4167. new_delta_ex,
  4168. datetime_fromtimestamp,
  4169. date_fromtimestamp
  4170. };
  4171. PyMODINIT_FUNC
  4172. initdatetime(void)
  4173. {
  4174. PyObject *m; /* a module object */
  4175. PyObject *d; /* its dict */
  4176. PyObject *x;
  4177. m = Py_InitModule3("datetime", module_methods,
  4178. "Fast implementation of the datetime type.");
  4179. if (m == NULL)
  4180. return;
  4181. if (PyType_Ready(&PyDateTime_DateType) < 0)
  4182. return;
  4183. if (PyType_Ready(&PyDateTime_DateTimeType) < 0)
  4184. return;
  4185. if (PyType_Ready(&PyDateTime_DeltaType) < 0)
  4186. return;
  4187. if (PyType_Ready(&PyDateTime_TimeType) < 0)
  4188. return;
  4189. if (PyType_Ready(&PyDateTime_TZInfoType) < 0)
  4190. return;
  4191. /* timedelta values */
  4192. d = PyDateTime_DeltaType.tp_dict;
  4193. x = new_delta(0, 0, 1, 0);
  4194. if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
  4195. return;
  4196. Py_DECREF(x);
  4197. x = new_delta(-MAX_DELTA_DAYS, 0, 0, 0);
  4198. if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
  4199. return;
  4200. Py_DECREF(x);
  4201. x = new_delta(MAX_DELTA_DAYS, 24*3600-1, 1000000-1, 0);
  4202. if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
  4203. return;
  4204. Py_DECREF(x);
  4205. /* date values */
  4206. d = PyDateTime_DateType.tp_dict;
  4207. x = new_date(1, 1, 1);
  4208. if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
  4209. return;
  4210. Py_DECREF(x);
  4211. x = new_date(MAXYEAR, 12, 31);
  4212. if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
  4213. return;
  4214. Py_DECREF(x);
  4215. x = new_delta(1, 0, 0, 0);
  4216. if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
  4217. return;
  4218. Py_DECREF(x);
  4219. /* time values */
  4220. d = PyDateTime_TimeType.tp_dict;
  4221. x = new_time(0, 0, 0, 0, Py_None);
  4222. if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
  4223. return;
  4224. Py_DECREF(x);
  4225. x = new_time(23, 59, 59, 999999, Py_None);
  4226. if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
  4227. return;
  4228. Py_DECREF(x);
  4229. x = new_delta(0, 0, 1, 0);
  4230. if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
  4231. return;
  4232. Py_DECREF(x);
  4233. /* datetime values */
  4234. d = PyDateTime_DateTimeType.tp_dict;
  4235. x = new_datetime(1, 1, 1, 0, 0, 0, 0, Py_None);
  4236. if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
  4237. return;
  4238. Py_DECREF(x);
  4239. x = new_datetime(MAXYEAR, 12, 31, 23, 59, 59, 999999, Py_None);
  4240. if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
  4241. return;
  4242. Py_DECREF(x);
  4243. x = new_delta(0, 0, 1, 0);
  4244. if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
  4245. return;
  4246. Py_DECREF(x);
  4247. /* module initialization */
  4248. PyModule_AddIntConstant(m, "MINYEAR", MINYEAR);
  4249. PyModule_AddIntConstant(m, "MAXYEAR", MAXYEAR);
  4250. Py_INCREF(&PyDateTime_DateType);
  4251. PyModule_AddObject(m, "date", (PyObject *) &PyDateTime_DateType);
  4252. Py_INCREF(&PyDateTime_DateTimeType);
  4253. PyModule_AddObject(m, "datetime",
  4254. (PyObject *)&PyDateTime_DateTimeType);
  4255. Py_INCREF(&PyDateTime_TimeType);
  4256. PyModule_AddObject(m, "time", (PyObject *) &PyDateTime_TimeType);
  4257. Py_INCREF(&PyDateTime_DeltaType);
  4258. PyModule_AddObject(m, "timedelta", (PyObject *) &PyDateTime_DeltaType);
  4259. Py_INCREF(&PyDateTime_TZInfoType);
  4260. PyModule_AddObject(m, "tzinfo", (PyObject *) &PyDateTime_TZInfoType);
  4261. x = PyCObject_FromVoidPtrAndDesc(&CAPI, (void*) DATETIME_API_MAGIC,
  4262. NULL);
  4263. if (x == NULL)
  4264. return;
  4265. PyModule_AddObject(m, "datetime_CAPI", x);
  4266. /* A 4-year cycle has an extra leap day over what we'd get from
  4267. * pasting together 4 single years.
  4268. */
  4269. assert(DI4Y == 4 * 365 + 1);
  4270. assert(DI4Y == days_before_year(4+1));
  4271. /* Similarly, a 400-year cycle has an extra leap day over what we'd
  4272. * get from pasting together 4 100-year cycles.
  4273. */
  4274. assert(DI400Y == 4 * DI100Y + 1);
  4275. assert(DI400Y == days_before_year(400+1));
  4276. /* OTOH, a 100-year cycle has one fewer leap day than we'd get from
  4277. * pasting together 25 4-year cycles.
  4278. */
  4279. assert(DI100Y == 25 * DI4Y - 1);
  4280. assert(DI100Y == days_before_year(100+1));
  4281. us_per_us = PyInt_FromLong(1);
  4282. us_per_ms = PyInt_FromLong(1000);
  4283. us_per_second = PyInt_FromLong(1000000);
  4284. us_per_minute = PyInt_FromLong(60000000);
  4285. seconds_per_day = PyInt_FromLong(24 * 3600);
  4286. if (us_per_us == NULL || us_per_ms == NULL || us_per_second == NULL ||
  4287. us_per_minute == NULL || seconds_per_day == NULL)
  4288. return;
  4289. /* The rest are too big for 32-bit ints, but even
  4290. * us_per_week fits in 40 bits, so doubles should be exact.
  4291. */
  4292. us_per_hour = PyLong_FromDouble(3600000000.0);
  4293. us_per_day = PyLong_FromDouble(86400000000.0);
  4294. us_per_week = PyLong_FromDouble(604800000000.0);
  4295. if (us_per_hour == NULL || us_per_day == NULL || us_per_week == NULL)
  4296. return;
  4297. }
  4298. /* ---------------------------------------------------------------------------
  4299. Some time zone algebra. For a datetime x, let
  4300. x.n = x stripped of its timezone -- its naive time.
  4301. x.o = x.utcoffset(), and assuming that doesn't raise an exception or
  4302. return None
  4303. x.d = x.dst(), and assuming that doesn't raise an exception or
  4304. return None
  4305. x.s = x's standard offset, x.o - x.d
  4306. Now some derived rules, where k is a duration (timedelta).
  4307. 1. x.o = x.s + x.d
  4308. This follows from the definition of x.s.
  4309. 2. If x and y have the same tzinfo member, x.s = y.s.
  4310. This is actually a requirement, an assumption we need to make about
  4311. sane tzinfo classes.
  4312. 3. The naive UTC time corresponding to x is x.n - x.o.
  4313. This is again a requirement for a sane tzinfo class.
  4314. 4. (x+k).s = x.s
  4315. This follows from #2, and that datimetimetz+timedelta preserves tzinfo.
  4316. 5. (x+k).n = x.n + k
  4317. Again follows from how arithmetic is defined.
  4318. Now we can explain tz.fromutc(x). Let's assume it's an interesting case
  4319. (meaning that the various tzinfo methods exist, and don't blow up or return
  4320. None when called).
  4321. The function wants to return a datetime y with timezone tz, equivalent to x.
  4322. x is already in UTC.
  4323. By #3, we want
  4324. y.n - y.o = x.n [1]
  4325. The algorithm starts by attaching tz to x.n, and calling that y. So
  4326. x.n = y.n at the start. Then it wants to add a duration k to y, so that [1]
  4327. becomes true; in effect, we want to solve [2] for k:
  4328. (y+k).n - (y+k).o = x.n [2]
  4329. By #1, this is the same as
  4330. (y+k).n - ((y+k).s + (y+k).d) = x.n [3]
  4331. By #5, (y+k).n = y.n + k, which equals x.n + k because x.n=y.n at the start.
  4332. Substituting that into [3],
  4333. x.n + k - (y+k).s - (y+k).d = x.n; the x.n terms cancel, leaving
  4334. k - (y+k).s - (y+k).d = 0; rearranging,
  4335. k = (y+k).s - (y+k).d; by #4, (y+k).s == y.s, so
  4336. k = y.s - (y+k).d
  4337. On the RHS, (y+k).d can't be computed directly, but y.s can be, and we
  4338. approximate k by ignoring the (y+k).d term at first. Note that k can't be
  4339. very large, since all offset-returning methods return a duration of magnitude
  4340. less than 24 hours. For that reason, if y is firmly in std time, (y+k).d must
  4341. be 0, so ignoring it has no consequence then.
  4342. In any case, the new value is
  4343. z = y + y.s [4]
  4344. It's helpful to step back at look at [4] from a higher level: it's simply
  4345. mapping from UTC to tz's standard time.
  4346. At this point, if
  4347. z.n - z.o = x.n [5]
  4348. we have an equivalent time, and are almost done. The insecurity here is
  4349. at the start of daylight time. Picture US Eastern for concreteness. The wall
  4350. time jumps from 1:59 to 3:00, and wall hours of the form 2:MM don't make good
  4351. sense then. The docs ask that an Eastern tzinfo class consider such a time to
  4352. be EDT (because it's "after 2"), which is a redundant spelling of 1:MM EST
  4353. on the day DST starts. We want to return the 1:MM EST spelling because that's
  4354. the only spelling that makes sense on the local wall clock.
  4355. In fact, if [5] holds at this point, we do have the standard-time spelling,
  4356. but that takes a bit of proof. We first prove a stronger result. What's the
  4357. difference between the LHS and RHS of [5]? Let
  4358. diff = x.n - (z.n - z.o) [6]
  4359. Now
  4360. z.n = by [4]
  4361. (y + y.s).n = by #5
  4362. y.n + y.s = since y.n = x.n
  4363. x.n + y.s = since z and y are have the same tzinfo member,
  4364. y.s = z.s by #2
  4365. x.n + z.s
  4366. Plugging that back into [6] gives
  4367. diff =
  4368. x.n - ((x.n + z.s) - z.o) = expanding
  4369. x.n - x.n - z.s + z.o = cancelling
  4370. - z.s + z.o = by #2
  4371. z.d
  4372. So diff = z.d.
  4373. If [5] is true now, diff = 0, so z.d = 0 too, and we have the standard-time
  4374. spelling we wanted in the endcase described above. We're done. Contrarily,
  4375. if z.d = 0, then we have a UTC equivalent, and are also done.
  4376. If [5] is not true now, diff = z.d != 0, and z.d is the offset we need to
  4377. add to z (in effect, z is in tz's standard time, and we need to shift the
  4378. local clock into tz's daylight time).
  4379. Let
  4380. z' = z + z.d = z + diff [7]
  4381. and we can again ask whether
  4382. z'.n - z'.o = x.n [8]
  4383. If so, we're done. If not, the tzinfo class is insane, according to the
  4384. assumptions we've made. This also requires a bit of proof. As before, let's
  4385. compute the difference between the LHS and RHS of [8] (and skipping some of
  4386. the justifications for the kinds of substitutions we've done several times
  4387. already):
  4388. diff' = x.n - (z'.n - z'.o) = replacing z'.n via [7]
  4389. x.n - (z.n + diff - z'.o) = replacing diff via [6]
  4390. x.n - (z.n + x.n - (z.n - z.o) - z'.o) =
  4391. x.n - z.n - x.n + z.n - z.o + z'.o = cancel x.n
  4392. - z.n + z.n - z.o + z'.o = cancel z.n
  4393. - z.o + z'.o = #1 twice
  4394. -z.s - z.d + z'.s + z'.d = z and z' have same tzinfo
  4395. z'.d - z.d
  4396. So z' is UTC-equivalent to x iff z'.d = z.d at this point. If they are equal,
  4397. we've found the UTC-equivalent so are done. In fact, we stop with [7] and
  4398. return z', not bothering to compute z'.d.
  4399. How could z.d and z'd differ? z' = z + z.d [7], so merely moving z' by
  4400. a dst() offset, and starting *from* a time already in DST (we know z.d != 0),
  4401. would have to change the result dst() returns: we start in DST, and moving
  4402. a little further into it takes us out of DST.
  4403. There isn't a sane case where this can happen. The closest it gets is at
  4404. the end of DST, where there's an hour in UTC with no spelling in a hybrid
  4405. tzinfo class. In US Eastern, that's 5:MM UTC = 0:MM EST = 1:MM EDT. During
  4406. that hour, on an Eastern clock 1:MM is taken as being in standard time (6:MM
  4407. UTC) because the docs insist on that, but 0:MM is taken as being in daylight
  4408. time (4:MM UTC). There is no local time mapping to 5:MM UTC. The local
  4409. clock jumps from 1:59 back to 1:00 again, and repeats the 1:MM hour in
  4410. standard time. Since that's what the local clock *does*, we want to map both
  4411. UTC hours 5:MM and 6:MM to 1:MM Eastern. The result is ambiguous
  4412. in local time, but so it goes -- it's the way the local clock works.
  4413. When x = 5:MM UTC is the input to this algorithm, x.o=0, y.o=-5 and y.d=0,
  4414. so z=0:MM. z.d=60 (minutes) then, so [5] doesn't hold and we keep going.
  4415. z' = z + z.d = 1:MM then, and z'.d=0, and z'.d - z.d = -60 != 0 so [8]
  4416. (correctly) concludes that z' is not UTC-equivalent to x.
  4417. Because we know z.d said z was in daylight time (else [5] would have held and
  4418. we would have stopped then), and we know z.d != z'.d (else [8] would have held
  4419. and we would have stopped then), and there are only 2 possible values dst() can
  4420. return in Eastern, it follows that z'.d must be 0 (which it is in the example,
  4421. but the reasoning doesn't depend on the example -- it depends on there being
  4422. two possible dst() outcomes, one zero and the other non-zero). Therefore
  4423. z' must be in standard time, and is the spelling we want in this case.
  4424. Note again that z' is not UTC-equivalent as far as the hybrid tzinfo class is
  4425. concerned (because it takes z' as being in standard time rather than the
  4426. daylight time we intend here), but returning it gives the real-life "local
  4427. clock repeats an hour" behavior when mapping the "unspellable" UTC hour into
  4428. tz.
  4429. When the input is 6:MM, z=1:MM and z.d=0, and we stop at once, again with
  4430. the 1:MM standard time spelling we want.
  4431. So how can this break? One of the assumptions must be violated. Two
  4432. possibilities:
  4433. 1) [2] effectively says that y.s is invariant across all y belong to a given
  4434. time zone. This isn't true if, for political reasons or continental drift,
  4435. a region decides to change its base offset from UTC.
  4436. 2) There may be versions of "double daylight" time where the tail end of
  4437. the analysis gives up a step too early. I haven't thought about that
  4438. enough to say.
  4439. In any case, it's clear that the default fromutc() is strong enough to handle
  4440. "almost all" time zones: so long as the standard offset is invariant, it
  4441. doesn't matter if daylight time transition points change from year to year, or
  4442. if daylight time is skipped in some years; it doesn't matter how large or
  4443. small dst() may get within its bounds; and it doesn't even matter if some
  4444. perverse time zone returns a negative dst()). So a breaking case must be
  4445. pretty bizarre, and a tzinfo subclass can override fromutc() if it is.
  4446. --------------------------------------------------------------------------- */