You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

5117 lines
167 KiB

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