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