1 /* Time module */ 2 3 #include "Python.h" 4 5 #include <ctype.h> 6 7 #ifdef HAVE_SYS_TIMES_H 8 #include <sys/times.h> 9 #endif 10 11 #ifdef HAVE_SYS_TYPES_H 12 #include <sys/types.h> 13 #endif 14 15 #if defined(HAVE_SYS_RESOURCE_H) 16 #include <sys/resource.h> 17 #endif 18 19 #ifdef QUICKWIN 20 #include <io.h> 21 #endif 22 23 #if defined(__WATCOMC__) && !defined(__QNX__) 24 #include <i86.h> 25 #else 26 #ifdef MS_WINDOWS 27 #define WIN32_LEAN_AND_MEAN 28 #include <windows.h> 29 #include "pythread.h" 30 #endif /* MS_WINDOWS */ 31 #endif /* !__WATCOMC__ || __QNX__ */ 32 33 /* Forward declarations */ 34 static int pysleep(_PyTime_t); 35 static PyObject* floattime(_Py_clock_info_t *info); 36 37 static PyObject * 38 time_time(PyObject *self, PyObject *unused) 39 { 40 return floattime(NULL); 41 } 42 43 PyDoc_STRVAR(time_doc, 44 "time() -> floating point number\n\ 45 \n\ 46 Return the current time in seconds since the Epoch.\n\ 47 Fractions of a second may be present if the system clock provides them."); 48 49 #if defined(HAVE_CLOCK) 50 51 #ifndef CLOCKS_PER_SEC 52 #ifdef CLK_TCK 53 #define CLOCKS_PER_SEC CLK_TCK 54 #else 55 #define CLOCKS_PER_SEC 1000000 56 #endif 57 #endif 58 59 static PyObject * 60 floatclock(_Py_clock_info_t *info) 61 { 62 clock_t value; 63 value = clock(); 64 if (value == (clock_t)-1) { 65 PyErr_SetString(PyExc_RuntimeError, 66 "the processor time used is not available " 67 "or its value cannot be represented"); 68 return NULL; 69 } 70 if (info) { 71 info->implementation = "clock()"; 72 info->resolution = 1.0 / (double)CLOCKS_PER_SEC; 73 info->monotonic = 1; 74 info->adjustable = 0; 75 } 76 return PyFloat_FromDouble((double)value / CLOCKS_PER_SEC); 77 } 78 #endif /* HAVE_CLOCK */ 79 80 #ifdef MS_WINDOWS 81 #define WIN32_PERF_COUNTER 82 /* Win32 has better clock replacement; we have our own version, due to Mark 83 Hammond and Tim Peters */ 84 static PyObject* 85 win_perf_counter(_Py_clock_info_t *info) 86 { 87 static LONGLONG cpu_frequency = 0; 88 static LONGLONG ctrStart; 89 LARGE_INTEGER now; 90 double diff; 91 92 if (cpu_frequency == 0) { 93 LARGE_INTEGER freq; 94 QueryPerformanceCounter(&now); 95 ctrStart = now.QuadPart; 96 if (!QueryPerformanceFrequency(&freq) || freq.QuadPart == 0) { 97 PyErr_SetFromWindowsErr(0); 98 return NULL; 99 } 100 cpu_frequency = freq.QuadPart; 101 } 102 QueryPerformanceCounter(&now); 103 diff = (double)(now.QuadPart - ctrStart); 104 if (info) { 105 info->implementation = "QueryPerformanceCounter()"; 106 info->resolution = 1.0 / (double)cpu_frequency; 107 info->monotonic = 1; 108 info->adjustable = 0; 109 } 110 return PyFloat_FromDouble(diff / (double)cpu_frequency); 111 } 112 #endif /* MS_WINDOWS */ 113 114 #if defined(WIN32_PERF_COUNTER) || defined(HAVE_CLOCK) 115 #define PYCLOCK 116 static PyObject* 117 pyclock(_Py_clock_info_t *info) 118 { 119 #ifdef WIN32_PERF_COUNTER 120 return win_perf_counter(info); 121 #else 122 return floatclock(info); 123 #endif 124 } 125 126 static PyObject * 127 time_clock(PyObject *self, PyObject *unused) 128 { 129 return pyclock(NULL); 130 } 131 132 PyDoc_STRVAR(clock_doc, 133 "clock() -> floating point number\n\ 134 \n\ 135 Return the CPU time or real time since the start of the process or since\n\ 136 the first call to clock(). This has as much precision as the system\n\ 137 records."); 138 #endif 139 140 #ifdef HAVE_CLOCK_GETTIME 141 static PyObject * 142 time_clock_gettime(PyObject *self, PyObject *args) 143 { 144 int ret; 145 int clk_id; 146 struct timespec tp; 147 148 if (!PyArg_ParseTuple(args, "i:clock_gettime", &clk_id)) 149 return NULL; 150 151 ret = clock_gettime((clockid_t)clk_id, &tp); 152 if (ret != 0) { 153 PyErr_SetFromErrno(PyExc_OSError); 154 return NULL; 155 } 156 return PyFloat_FromDouble(tp.tv_sec + tp.tv_nsec * 1e-9); 157 } 158 159 PyDoc_STRVAR(clock_gettime_doc, 160 "clock_gettime(clk_id) -> floating point number\n\ 161 \n\ 162 Return the time of the specified clock clk_id."); 163 #endif /* HAVE_CLOCK_GETTIME */ 164 165 #ifdef HAVE_CLOCK_SETTIME 166 static PyObject * 167 time_clock_settime(PyObject *self, PyObject *args) 168 { 169 int clk_id; 170 PyObject *obj; 171 _PyTime_t t; 172 struct timespec tp; 173 int ret; 174 175 if (!PyArg_ParseTuple(args, "iO:clock_settime", &clk_id, &obj)) 176 return NULL; 177 178 if (_PyTime_FromSecondsObject(&t, obj, _PyTime_ROUND_FLOOR) < 0) 179 return NULL; 180 181 if (_PyTime_AsTimespec(t, &tp) == -1) 182 return NULL; 183 184 ret = clock_settime((clockid_t)clk_id, &tp); 185 if (ret != 0) { 186 PyErr_SetFromErrno(PyExc_OSError); 187 return NULL; 188 } 189 Py_RETURN_NONE; 190 } 191 192 PyDoc_STRVAR(clock_settime_doc, 193 "clock_settime(clk_id, time)\n\ 194 \n\ 195 Set the time of the specified clock clk_id."); 196 #endif /* HAVE_CLOCK_SETTIME */ 197 198 #ifdef HAVE_CLOCK_GETRES 199 static PyObject * 200 time_clock_getres(PyObject *self, PyObject *args) 201 { 202 int ret; 203 int clk_id; 204 struct timespec tp; 205 206 if (!PyArg_ParseTuple(args, "i:clock_getres", &clk_id)) 207 return NULL; 208 209 ret = clock_getres((clockid_t)clk_id, &tp); 210 if (ret != 0) { 211 PyErr_SetFromErrno(PyExc_OSError); 212 return NULL; 213 } 214 215 return PyFloat_FromDouble(tp.tv_sec + tp.tv_nsec * 1e-9); 216 } 217 218 PyDoc_STRVAR(clock_getres_doc, 219 "clock_getres(clk_id) -> floating point number\n\ 220 \n\ 221 Return the resolution (precision) of the specified clock clk_id."); 222 #endif /* HAVE_CLOCK_GETRES */ 223 224 static PyObject * 225 time_sleep(PyObject *self, PyObject *obj) 226 { 227 _PyTime_t secs; 228 if (_PyTime_FromSecondsObject(&secs, obj, _PyTime_ROUND_CEILING)) 229 return NULL; 230 if (secs < 0) { 231 PyErr_SetString(PyExc_ValueError, 232 "sleep length must be non-negative"); 233 return NULL; 234 } 235 if (pysleep(secs) != 0) 236 return NULL; 237 Py_INCREF(Py_None); 238 return Py_None; 239 } 240 241 PyDoc_STRVAR(sleep_doc, 242 "sleep(seconds)\n\ 243 \n\ 244 Delay execution for a given number of seconds. The argument may be\n\ 245 a floating point number for subsecond precision."); 246 247 static PyStructSequence_Field struct_time_type_fields[] = { 248 {"tm_year", "year, for example, 1993"}, 249 {"tm_mon", "month of year, range [1, 12]"}, 250 {"tm_mday", "day of month, range [1, 31]"}, 251 {"tm_hour", "hours, range [0, 23]"}, 252 {"tm_min", "minutes, range [0, 59]"}, 253 {"tm_sec", "seconds, range [0, 61])"}, 254 {"tm_wday", "day of week, range [0, 6], Monday is 0"}, 255 {"tm_yday", "day of year, range [1, 366]"}, 256 {"tm_isdst", "1 if summer time is in effect, 0 if not, and -1 if unknown"}, 257 {"tm_zone", "abbreviation of timezone name"}, 258 {"tm_gmtoff", "offset from UTC in seconds"}, 259 {0} 260 }; 261 262 static PyStructSequence_Desc struct_time_type_desc = { 263 "time.struct_time", 264 "The time value as returned by gmtime(), localtime(), and strptime(), and\n" 265 " accepted by asctime(), mktime() and strftime(). May be considered as a\n" 266 " sequence of 9 integers.\n\n" 267 " Note that several fields' values are not the same as those defined by\n" 268 " the C language standard for struct tm. For example, the value of the\n" 269 " field tm_year is the actual year, not year - 1900. See individual\n" 270 " fields' descriptions for details.", 271 struct_time_type_fields, 272 9, 273 }; 274 275 static int initialized; 276 static PyTypeObject StructTimeType; 277 278 279 static PyObject * 280 tmtotuple(struct tm *p 281 #ifndef HAVE_STRUCT_TM_TM_ZONE 282 , const char *zone, int gmtoff 283 #endif 284 ) 285 { 286 PyObject *v = PyStructSequence_New(&StructTimeType); 287 if (v == NULL) 288 return NULL; 289 290 #define SET(i,val) PyStructSequence_SET_ITEM(v, i, PyLong_FromLong((long) val)) 291 292 SET(0, p->tm_year + 1900); 293 SET(1, p->tm_mon + 1); /* Want January == 1 */ 294 SET(2, p->tm_mday); 295 SET(3, p->tm_hour); 296 SET(4, p->tm_min); 297 SET(5, p->tm_sec); 298 SET(6, (p->tm_wday + 6) % 7); /* Want Monday == 0 */ 299 SET(7, p->tm_yday + 1); /* Want January, 1 == 1 */ 300 SET(8, p->tm_isdst); 301 #ifdef HAVE_STRUCT_TM_TM_ZONE 302 PyStructSequence_SET_ITEM(v, 9, 303 PyUnicode_DecodeLocale(p->tm_zone, "surrogateescape")); 304 SET(10, p->tm_gmtoff); 305 #else 306 PyStructSequence_SET_ITEM(v, 9, 307 PyUnicode_DecodeLocale(zone, "surrogateescape")); 308 SET(10, gmtoff); 309 #endif /* HAVE_STRUCT_TM_TM_ZONE */ 310 #undef SET 311 if (PyErr_Occurred()) { 312 Py_XDECREF(v); 313 return NULL; 314 } 315 316 return v; 317 } 318 319 /* Parse arg tuple that can contain an optional float-or-None value; 320 format needs to be "|O:name". 321 Returns non-zero on success (parallels PyArg_ParseTuple). 322 */ 323 static int 324 parse_time_t_args(PyObject *args, const char *format, time_t *pwhen) 325 { 326 PyObject *ot = NULL; 327 time_t whent; 328 329 if (!PyArg_ParseTuple(args, format, &ot)) 330 return 0; 331 if (ot == NULL || ot == Py_None) { 332 whent = time(NULL); 333 } 334 else { 335 if (_PyTime_ObjectToTime_t(ot, &whent, _PyTime_ROUND_FLOOR) == -1) 336 return 0; 337 } 338 *pwhen = whent; 339 return 1; 340 } 341 342 static PyObject * 343 time_gmtime(PyObject *self, PyObject *args) 344 { 345 time_t when; 346 struct tm buf; 347 348 if (!parse_time_t_args(args, "|O:gmtime", &when)) 349 return NULL; 350 351 errno = 0; 352 if (_PyTime_gmtime(when, &buf) != 0) 353 return NULL; 354 #ifdef HAVE_STRUCT_TM_TM_ZONE 355 return tmtotuple(&buf); 356 #else 357 return tmtotuple(&buf, "UTC", 0); 358 #endif 359 } 360 361 #ifndef HAVE_TIMEGM 362 static time_t 363 timegm(struct tm *p) 364 { 365 /* XXX: the following implementation will not work for tm_year < 1970. 366 but it is likely that platforms that don't have timegm do not support 367 negative timestamps anyways. */ 368 return p->tm_sec + p->tm_min*60 + p->tm_hour*3600 + p->tm_yday*86400 + 369 (p->tm_year-70)*31536000 + ((p->tm_year-69)/4)*86400 - 370 ((p->tm_year-1)/100)*86400 + ((p->tm_year+299)/400)*86400; 371 } 372 #endif 373 374 PyDoc_STRVAR(gmtime_doc, 375 "gmtime([seconds]) -> (tm_year, tm_mon, tm_mday, tm_hour, tm_min,\n\ 376 tm_sec, tm_wday, tm_yday, tm_isdst)\n\ 377 \n\ 378 Convert seconds since the Epoch to a time tuple expressing UTC (a.k.a.\n\ 379 GMT). When 'seconds' is not passed in, convert the current time instead.\n\ 380 \n\ 381 If the platform supports the tm_gmtoff and tm_zone, they are available as\n\ 382 attributes only."); 383 384 static PyObject * 385 time_localtime(PyObject *self, PyObject *args) 386 { 387 time_t when; 388 struct tm buf; 389 390 if (!parse_time_t_args(args, "|O:localtime", &when)) 391 return NULL; 392 if (_PyTime_localtime(when, &buf) != 0) 393 return NULL; 394 #ifdef HAVE_STRUCT_TM_TM_ZONE 395 return tmtotuple(&buf); 396 #else 397 { 398 struct tm local = buf; 399 char zone[100]; 400 int gmtoff; 401 strftime(zone, sizeof(zone), "%Z", &buf); 402 gmtoff = timegm(&buf) - when; 403 return tmtotuple(&local, zone, gmtoff); 404 } 405 #endif 406 } 407 408 PyDoc_STRVAR(localtime_doc, 409 "localtime([seconds]) -> (tm_year,tm_mon,tm_mday,tm_hour,tm_min,\n\ 410 tm_sec,tm_wday,tm_yday,tm_isdst)\n\ 411 \n\ 412 Convert seconds since the Epoch to a time tuple expressing local time.\n\ 413 When 'seconds' is not passed in, convert the current time instead."); 414 415 /* Convert 9-item tuple to tm structure. Return 1 on success, set 416 * an exception and return 0 on error. 417 */ 418 static int 419 gettmarg(PyObject *args, struct tm *p) 420 { 421 int y; 422 423 memset((void *) p, '\0', sizeof(struct tm)); 424 425 if (!PyTuple_Check(args)) { 426 PyErr_SetString(PyExc_TypeError, 427 "Tuple or struct_time argument required"); 428 return 0; 429 } 430 431 if (!PyArg_ParseTuple(args, "iiiiiiiii", 432 &y, &p->tm_mon, &p->tm_mday, 433 &p->tm_hour, &p->tm_min, &p->tm_sec, 434 &p->tm_wday, &p->tm_yday, &p->tm_isdst)) 435 return 0; 436 p->tm_year = y - 1900; 437 p->tm_mon--; 438 p->tm_wday = (p->tm_wday + 1) % 7; 439 p->tm_yday--; 440 #ifdef HAVE_STRUCT_TM_TM_ZONE 441 if (Py_TYPE(args) == &StructTimeType) { 442 PyObject *item; 443 item = PyTuple_GET_ITEM(args, 9); 444 p->tm_zone = item == Py_None ? NULL : PyUnicode_AsUTF8(item); 445 item = PyTuple_GET_ITEM(args, 10); 446 p->tm_gmtoff = item == Py_None ? 0 : PyLong_AsLong(item); 447 if (PyErr_Occurred()) 448 return 0; 449 } 450 #endif /* HAVE_STRUCT_TM_TM_ZONE */ 451 return 1; 452 } 453 454 /* Check values of the struct tm fields before it is passed to strftime() and 455 * asctime(). Return 1 if all values are valid, otherwise set an exception 456 * and returns 0. 457 */ 458 static int 459 checktm(struct tm* buf) 460 { 461 /* Checks added to make sure strftime() and asctime() does not crash Python by 462 indexing blindly into some array for a textual representation 463 by some bad index (fixes bug #897625 and #6608). 464 465 Also support values of zero from Python code for arguments in which 466 that is out of range by forcing that value to the lowest value that 467 is valid (fixed bug #1520914). 468 469 Valid ranges based on what is allowed in struct tm: 470 471 - tm_year: [0, max(int)] (1) 472 - tm_mon: [0, 11] (2) 473 - tm_mday: [1, 31] 474 - tm_hour: [0, 23] 475 - tm_min: [0, 59] 476 - tm_sec: [0, 60] 477 - tm_wday: [0, 6] (1) 478 - tm_yday: [0, 365] (2) 479 - tm_isdst: [-max(int), max(int)] 480 481 (1) gettmarg() handles bounds-checking. 482 (2) Python's acceptable range is one greater than the range in C, 483 thus need to check against automatic decrement by gettmarg(). 484 */ 485 if (buf->tm_mon == -1) 486 buf->tm_mon = 0; 487 else if (buf->tm_mon < 0 || buf->tm_mon > 11) { 488 PyErr_SetString(PyExc_ValueError, "month out of range"); 489 return 0; 490 } 491 if (buf->tm_mday == 0) 492 buf->tm_mday = 1; 493 else if (buf->tm_mday < 0 || buf->tm_mday > 31) { 494 PyErr_SetString(PyExc_ValueError, "day of month out of range"); 495 return 0; 496 } 497 if (buf->tm_hour < 0 || buf->tm_hour > 23) { 498 PyErr_SetString(PyExc_ValueError, "hour out of range"); 499 return 0; 500 } 501 if (buf->tm_min < 0 || buf->tm_min > 59) { 502 PyErr_SetString(PyExc_ValueError, "minute out of range"); 503 return 0; 504 } 505 if (buf->tm_sec < 0 || buf->tm_sec > 61) { 506 PyErr_SetString(PyExc_ValueError, "seconds out of range"); 507 return 0; 508 } 509 /* tm_wday does not need checking of its upper-bound since taking 510 ``% 7`` in gettmarg() automatically restricts the range. */ 511 if (buf->tm_wday < 0) { 512 PyErr_SetString(PyExc_ValueError, "day of week out of range"); 513 return 0; 514 } 515 if (buf->tm_yday == -1) 516 buf->tm_yday = 0; 517 else if (buf->tm_yday < 0 || buf->tm_yday > 365) { 518 PyErr_SetString(PyExc_ValueError, "day of year out of range"); 519 return 0; 520 } 521 return 1; 522 } 523 524 #ifdef MS_WINDOWS 525 /* wcsftime() doesn't format correctly time zones, see issue #10653 */ 526 # undef HAVE_WCSFTIME 527 #endif 528 #define STRFTIME_FORMAT_CODES \ 529 "Commonly used format codes:\n\ 530 \n\ 531 %Y Year with century as a decimal number.\n\ 532 %m Month as a decimal number [01,12].\n\ 533 %d Day of the month as a decimal number [01,31].\n\ 534 %H Hour (24-hour clock) as a decimal number [00,23].\n\ 535 %M Minute as a decimal number [00,59].\n\ 536 %S Second as a decimal number [00,61].\n\ 537 %z Time zone offset from UTC.\n\ 538 %a Locale's abbreviated weekday name.\n\ 539 %A Locale's full weekday name.\n\ 540 %b Locale's abbreviated month name.\n\ 541 %B Locale's full month name.\n\ 542 %c Locale's appropriate date and time representation.\n\ 543 %I Hour (12-hour clock) as a decimal number [01,12].\n\ 544 %p Locale's equivalent of either AM or PM.\n\ 545 \n\ 546 Other codes may be available on your platform. See documentation for\n\ 547 the C library strftime function.\n" 548 549 #ifdef HAVE_STRFTIME 550 #ifdef HAVE_WCSFTIME 551 #define time_char wchar_t 552 #define format_time wcsftime 553 #define time_strlen wcslen 554 #else 555 #define time_char char 556 #define format_time strftime 557 #define time_strlen strlen 558 #endif 559 560 static PyObject * 561 time_strftime(PyObject *self, PyObject *args) 562 { 563 PyObject *tup = NULL; 564 struct tm buf; 565 const time_char *fmt; 566 #ifdef HAVE_WCSFTIME 567 wchar_t *format; 568 #else 569 PyObject *format; 570 #endif 571 PyObject *format_arg; 572 size_t fmtlen, buflen; 573 time_char *outbuf = NULL; 574 size_t i; 575 PyObject *ret = NULL; 576 577 memset((void *) &buf, '\0', sizeof(buf)); 578 579 /* Will always expect a unicode string to be passed as format. 580 Given that there's no str type anymore in py3k this seems safe. 581 */ 582 if (!PyArg_ParseTuple(args, "U|O:strftime", &format_arg, &tup)) 583 return NULL; 584 585 if (tup == NULL) { 586 time_t tt = time(NULL); 587 if (_PyTime_localtime(tt, &buf) != 0) 588 return NULL; 589 } 590 else if (!gettmarg(tup, &buf) || !checktm(&buf)) 591 return NULL; 592 593 #if defined(_MSC_VER) || defined(sun) || defined(_AIX) 594 if (buf.tm_year + 1900 < 1 || 9999 < buf.tm_year + 1900) { 595 PyErr_SetString(PyExc_ValueError, 596 "strftime() requires year in [1; 9999]"); 597 return NULL; 598 } 599 #endif 600 601 /* Normalize tm_isdst just in case someone foolishly implements %Z 602 based on the assumption that tm_isdst falls within the range of 603 [-1, 1] */ 604 if (buf.tm_isdst < -1) 605 buf.tm_isdst = -1; 606 else if (buf.tm_isdst > 1) 607 buf.tm_isdst = 1; 608 609 #ifdef HAVE_WCSFTIME 610 format = PyUnicode_AsWideCharString(format_arg, NULL); 611 if (format == NULL) 612 return NULL; 613 fmt = format; 614 #else 615 /* Convert the unicode string to an ascii one */ 616 format = PyUnicode_EncodeLocale(format_arg, "surrogateescape"); 617 if (format == NULL) 618 return NULL; 619 fmt = PyBytes_AS_STRING(format); 620 #endif 621 622 #if defined(MS_WINDOWS) && !defined(HAVE_WCSFTIME) 623 /* check that the format string contains only valid directives */ 624 for (outbuf = strchr(fmt, '%'); 625 outbuf != NULL; 626 outbuf = strchr(outbuf+2, '%')) 627 { 628 if (outbuf[1] == '#') 629 ++outbuf; /* not documented by python, */ 630 if (outbuf[1] == '\0') 631 break; 632 if ((outbuf[1] == 'y') && buf.tm_year < 0) { 633 PyErr_SetString(PyExc_ValueError, 634 "format %y requires year >= 1900 on Windows"); 635 Py_DECREF(format); 636 return NULL; 637 } 638 } 639 #elif (defined(_AIX) || defined(sun)) && defined(HAVE_WCSFTIME) 640 for (outbuf = wcschr(fmt, '%'); 641 outbuf != NULL; 642 outbuf = wcschr(outbuf+2, '%')) 643 { 644 if (outbuf[1] == L'\0') 645 break; 646 /* Issue #19634: On AIX, wcsftime("y", (1899, 1, 1, 0, 0, 0, 0, 0, 0)) 647 returns "0/" instead of "99" */ 648 if (outbuf[1] == L'y' && buf.tm_year < 0) { 649 PyErr_SetString(PyExc_ValueError, 650 "format %y requires year >= 1900 on AIX"); 651 return NULL; 652 } 653 } 654 #endif 655 656 fmtlen = time_strlen(fmt); 657 658 /* I hate these functions that presume you know how big the output 659 * will be ahead of time... 660 */ 661 for (i = 1024; ; i += i) { 662 outbuf = (time_char *)PyMem_Malloc(i*sizeof(time_char)); 663 if (outbuf == NULL) { 664 PyErr_NoMemory(); 665 break; 666 } 667 #if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__) 668 errno = 0; 669 #endif 670 _Py_BEGIN_SUPPRESS_IPH 671 buflen = format_time(outbuf, i, fmt, &buf); 672 _Py_END_SUPPRESS_IPH 673 #if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__) 674 /* VisualStudio .NET 2005 does this properly */ 675 if (buflen == 0 && errno == EINVAL) { 676 PyErr_SetString(PyExc_ValueError, "Invalid format string"); 677 PyMem_Free(outbuf); 678 break; 679 } 680 #endif 681 if (buflen > 0 || i >= 256 * fmtlen) { 682 /* If the buffer is 256 times as long as the format, 683 it's probably not failing for lack of room! 684 More likely, the format yields an empty result, 685 e.g. an empty format, or %Z when the timezone 686 is unknown. */ 687 #ifdef HAVE_WCSFTIME 688 ret = PyUnicode_FromWideChar(outbuf, buflen); 689 #else 690 ret = PyUnicode_DecodeLocaleAndSize(outbuf, buflen, 691 "surrogateescape"); 692 #endif 693 PyMem_Free(outbuf); 694 break; 695 } 696 PyMem_Free(outbuf); 697 } 698 #ifdef HAVE_WCSFTIME 699 PyMem_Free(format); 700 #else 701 Py_DECREF(format); 702 #endif 703 return ret; 704 } 705 706 #undef time_char 707 #undef format_time 708 PyDoc_STRVAR(strftime_doc, 709 "strftime(format[, tuple]) -> string\n\ 710 \n\ 711 Convert a time tuple to a string according to a format specification.\n\ 712 See the library reference manual for formatting codes. When the time tuple\n\ 713 is not present, current time as returned by localtime() is used.\n\ 714 \n" STRFTIME_FORMAT_CODES); 715 #endif /* HAVE_STRFTIME */ 716 717 static PyObject * 718 time_strptime(PyObject *self, PyObject *args) 719 { 720 PyObject *strptime_module = PyImport_ImportModuleNoBlock("_strptime"); 721 PyObject *strptime_result; 722 _Py_IDENTIFIER(_strptime_time); 723 724 if (!strptime_module) 725 return NULL; 726 strptime_result = _PyObject_CallMethodId(strptime_module, 727 &PyId__strptime_time, "O", args); 728 Py_DECREF(strptime_module); 729 return strptime_result; 730 } 731 732 733 PyDoc_STRVAR(strptime_doc, 734 "strptime(string, format) -> struct_time\n\ 735 \n\ 736 Parse a string to a time tuple according to a format specification.\n\ 737 See the library reference manual for formatting codes (same as\n\ 738 strftime()).\n\ 739 \n" STRFTIME_FORMAT_CODES); 740 741 static PyObject * 742 _asctime(struct tm *timeptr) 743 { 744 /* Inspired by Open Group reference implementation available at 745 * http://pubs.opengroup.org/onlinepubs/009695399/functions/asctime.html */ 746 static const char wday_name[7][4] = { 747 "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" 748 }; 749 static const char mon_name[12][4] = { 750 "Jan", "Feb", "Mar", "Apr", "May", "Jun", 751 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" 752 }; 753 return PyUnicode_FromFormat( 754 "%s %s%3d %.2d:%.2d:%.2d %d", 755 wday_name[timeptr->tm_wday], 756 mon_name[timeptr->tm_mon], 757 timeptr->tm_mday, timeptr->tm_hour, 758 timeptr->tm_min, timeptr->tm_sec, 759 1900 + timeptr->tm_year); 760 } 761 762 static PyObject * 763 time_asctime(PyObject *self, PyObject *args) 764 { 765 PyObject *tup = NULL; 766 struct tm buf; 767 768 if (!PyArg_UnpackTuple(args, "asctime", 0, 1, &tup)) 769 return NULL; 770 if (tup == NULL) { 771 time_t tt = time(NULL); 772 if (_PyTime_localtime(tt, &buf) != 0) 773 return NULL; 774 775 } else if (!gettmarg(tup, &buf) || !checktm(&buf)) 776 return NULL; 777 return _asctime(&buf); 778 } 779 780 PyDoc_STRVAR(asctime_doc, 781 "asctime([tuple]) -> string\n\ 782 \n\ 783 Convert a time tuple to a string, e.g. 'Sat Jun 06 16:26:11 1998'.\n\ 784 When the time tuple is not present, current time as returned by localtime()\n\ 785 is used."); 786 787 static PyObject * 788 time_ctime(PyObject *self, PyObject *args) 789 { 790 time_t tt; 791 struct tm buf; 792 if (!parse_time_t_args(args, "|O:ctime", &tt)) 793 return NULL; 794 if (_PyTime_localtime(tt, &buf) != 0) 795 return NULL; 796 return _asctime(&buf); 797 } 798 799 PyDoc_STRVAR(ctime_doc, 800 "ctime(seconds) -> string\n\ 801 \n\ 802 Convert a time in seconds since the Epoch to a string in local time.\n\ 803 This is equivalent to asctime(localtime(seconds)). When the time tuple is\n\ 804 not present, current time as returned by localtime() is used."); 805 806 #ifdef HAVE_MKTIME 807 static PyObject * 808 time_mktime(PyObject *self, PyObject *tup) 809 { 810 struct tm buf; 811 time_t tt; 812 if (!gettmarg(tup, &buf)) 813 return NULL; 814 #ifdef _AIX 815 /* year < 1902 or year > 2037 */ 816 if (buf.tm_year < 2 || buf.tm_year > 137) { 817 /* Issue #19748: On AIX, mktime() doesn't report overflow error for 818 * timestamp < -2^31 or timestamp > 2**31-1. */ 819 PyErr_SetString(PyExc_OverflowError, 820 "mktime argument out of range"); 821 return NULL; 822 } 823 #else 824 buf.tm_wday = -1; /* sentinel; original value ignored */ 825 #endif 826 tt = mktime(&buf); 827 /* Return value of -1 does not necessarily mean an error, but tm_wday 828 * cannot remain set to -1 if mktime succeeded. */ 829 if (tt == (time_t)(-1) 830 #ifndef _AIX 831 /* Return value of -1 does not necessarily mean an error, but 832 * tm_wday cannot remain set to -1 if mktime succeeded. */ 833 && buf.tm_wday == -1 834 #else 835 /* on AIX, tm_wday is always sets, even on error */ 836 #endif 837 ) 838 { 839 PyErr_SetString(PyExc_OverflowError, 840 "mktime argument out of range"); 841 return NULL; 842 } 843 return PyFloat_FromDouble((double)tt); 844 } 845 846 PyDoc_STRVAR(mktime_doc, 847 "mktime(tuple) -> floating point number\n\ 848 \n\ 849 Convert a time tuple in local time to seconds since the Epoch.\n\ 850 Note that mktime(gmtime(0)) will not generally return zero for most\n\ 851 time zones; instead the returned value will either be equal to that\n\ 852 of the timezone or altzone attributes on the time module."); 853 #endif /* HAVE_MKTIME */ 854 855 #ifdef HAVE_WORKING_TZSET 856 static void PyInit_timezone(PyObject *module); 857 858 static PyObject * 859 time_tzset(PyObject *self, PyObject *unused) 860 { 861 PyObject* m; 862 863 m = PyImport_ImportModuleNoBlock("time"); 864 if (m == NULL) { 865 return NULL; 866 } 867 868 tzset(); 869 870 /* Reset timezone, altzone, daylight and tzname */ 871 PyInit_timezone(m); 872 Py_DECREF(m); 873 if (PyErr_Occurred()) 874 return NULL; 875 876 Py_INCREF(Py_None); 877 return Py_None; 878 } 879 880 PyDoc_STRVAR(tzset_doc, 881 "tzset()\n\ 882 \n\ 883 Initialize, or reinitialize, the local timezone to the value stored in\n\ 884 os.environ['TZ']. The TZ environment variable should be specified in\n\ 885 standard Unix timezone format as documented in the tzset man page\n\ 886 (eg. 'US/Eastern', 'Europe/Amsterdam'). Unknown timezones will silently\n\ 887 fall back to UTC. If the TZ environment variable is not set, the local\n\ 888 timezone is set to the systems best guess of wallclock time.\n\ 889 Changing the TZ environment variable without calling tzset *may* change\n\ 890 the local timezone used by methods such as localtime, but this behaviour\n\ 891 should not be relied on."); 892 #endif /* HAVE_WORKING_TZSET */ 893 894 static PyObject * 895 pymonotonic(_Py_clock_info_t *info) 896 { 897 _PyTime_t t; 898 double d; 899 if (_PyTime_GetMonotonicClockWithInfo(&t, info) < 0) { 900 assert(info != NULL); 901 return NULL; 902 } 903 d = _PyTime_AsSecondsDouble(t); 904 return PyFloat_FromDouble(d); 905 } 906 907 static PyObject * 908 time_monotonic(PyObject *self, PyObject *unused) 909 { 910 return pymonotonic(NULL); 911 } 912 913 PyDoc_STRVAR(monotonic_doc, 914 "monotonic() -> float\n\ 915 \n\ 916 Monotonic clock, cannot go backward."); 917 918 static PyObject* 919 perf_counter(_Py_clock_info_t *info) 920 { 921 #ifdef WIN32_PERF_COUNTER 922 return win_perf_counter(info); 923 #else 924 return pymonotonic(info); 925 #endif 926 } 927 928 static PyObject * 929 time_perf_counter(PyObject *self, PyObject *unused) 930 { 931 return perf_counter(NULL); 932 } 933 934 PyDoc_STRVAR(perf_counter_doc, 935 "perf_counter() -> float\n\ 936 \n\ 937 Performance counter for benchmarking."); 938 939 static PyObject* 940 py_process_time(_Py_clock_info_t *info) 941 { 942 #if defined(MS_WINDOWS) 943 HANDLE process; 944 FILETIME creation_time, exit_time, kernel_time, user_time; 945 ULARGE_INTEGER large; 946 double total; 947 BOOL ok; 948 949 process = GetCurrentProcess(); 950 ok = GetProcessTimes(process, &creation_time, &exit_time, &kernel_time, &user_time); 951 if (!ok) 952 return PyErr_SetFromWindowsErr(0); 953 954 large.u.LowPart = kernel_time.dwLowDateTime; 955 large.u.HighPart = kernel_time.dwHighDateTime; 956 total = (double)large.QuadPart; 957 large.u.LowPart = user_time.dwLowDateTime; 958 large.u.HighPart = user_time.dwHighDateTime; 959 total += (double)large.QuadPart; 960 if (info) { 961 info->implementation = "GetProcessTimes()"; 962 info->resolution = 1e-7; 963 info->monotonic = 1; 964 info->adjustable = 0; 965 } 966 return PyFloat_FromDouble(total * 1e-7); 967 #else 968 969 #if defined(HAVE_SYS_RESOURCE_H) 970 struct rusage ru; 971 #endif 972 #ifdef HAVE_TIMES 973 struct tms t; 974 static long ticks_per_second = -1; 975 #endif 976 977 #if defined(HAVE_CLOCK_GETTIME) \ 978 && (defined(CLOCK_PROCESS_CPUTIME_ID) || defined(CLOCK_PROF)) 979 struct timespec tp; 980 #ifdef CLOCK_PROF 981 const clockid_t clk_id = CLOCK_PROF; 982 const char *function = "clock_gettime(CLOCK_PROF)"; 983 #else 984 const clockid_t clk_id = CLOCK_PROCESS_CPUTIME_ID; 985 const char *function = "clock_gettime(CLOCK_PROCESS_CPUTIME_ID)"; 986 #endif 987 988 if (clock_gettime(clk_id, &tp) == 0) { 989 if (info) { 990 struct timespec res; 991 info->implementation = function; 992 info->monotonic = 1; 993 info->adjustable = 0; 994 if (clock_getres(clk_id, &res) == 0) 995 info->resolution = res.tv_sec + res.tv_nsec * 1e-9; 996 else 997 info->resolution = 1e-9; 998 } 999 return PyFloat_FromDouble(tp.tv_sec + tp.tv_nsec * 1e-9); 1000 } 1001 #endif 1002 1003 #if defined(HAVE_SYS_RESOURCE_H) 1004 if (getrusage(RUSAGE_SELF, &ru) == 0) { 1005 double total; 1006 total = ru.ru_utime.tv_sec + ru.ru_utime.tv_usec * 1e-6; 1007 total += ru.ru_stime.tv_sec + ru.ru_stime.tv_usec * 1e-6; 1008 if (info) { 1009 info->implementation = "getrusage(RUSAGE_SELF)"; 1010 info->monotonic = 1; 1011 info->adjustable = 0; 1012 info->resolution = 1e-6; 1013 } 1014 return PyFloat_FromDouble(total); 1015 } 1016 #endif 1017 1018 #ifdef HAVE_TIMES 1019 if (times(&t) != (clock_t)-1) { 1020 double total; 1021 1022 if (ticks_per_second == -1) { 1023 #if defined(HAVE_SYSCONF) && defined(_SC_CLK_TCK) 1024 ticks_per_second = sysconf(_SC_CLK_TCK); 1025 if (ticks_per_second < 1) 1026 ticks_per_second = -1; 1027 #elif defined(HZ) 1028 ticks_per_second = HZ; 1029 #else 1030 ticks_per_second = 60; /* magic fallback value; may be bogus */ 1031 #endif 1032 } 1033 1034 if (ticks_per_second != -1) { 1035 total = (double)t.tms_utime / ticks_per_second; 1036 total += (double)t.tms_stime / ticks_per_second; 1037 if (info) { 1038 info->implementation = "times()"; 1039 info->monotonic = 1; 1040 info->adjustable = 0; 1041 info->resolution = 1.0 / ticks_per_second; 1042 } 1043 return PyFloat_FromDouble(total); 1044 } 1045 } 1046 #endif 1047 1048 /* Currently, Python 3 requires clock() to build: see issue #22624 */ 1049 return floatclock(info); 1050 #endif 1051 } 1052 1053 static PyObject * 1054 time_process_time(PyObject *self, PyObject *unused) 1055 { 1056 return py_process_time(NULL); 1057 } 1058 1059 PyDoc_STRVAR(process_time_doc, 1060 "process_time() -> float\n\ 1061 \n\ 1062 Process time for profiling: sum of the kernel and user-space CPU time."); 1063 1064 1065 static PyObject * 1066 time_get_clock_info(PyObject *self, PyObject *args) 1067 { 1068 char *name; 1069 _Py_clock_info_t info; 1070 PyObject *obj = NULL, *dict, *ns; 1071 1072 if (!PyArg_ParseTuple(args, "s:get_clock_info", &name)) 1073 return NULL; 1074 1075 #ifdef Py_DEBUG 1076 info.implementation = NULL; 1077 info.monotonic = -1; 1078 info.adjustable = -1; 1079 info.resolution = -1.0; 1080 #else 1081 info.implementation = ""; 1082 info.monotonic = 0; 1083 info.adjustable = 0; 1084 info.resolution = 1.0; 1085 #endif 1086 1087 if (strcmp(name, "time") == 0) 1088 obj = floattime(&info); 1089 #ifdef PYCLOCK 1090 else if (strcmp(name, "clock") == 0) 1091 obj = pyclock(&info); 1092 #endif 1093 else if (strcmp(name, "monotonic") == 0) 1094 obj = pymonotonic(&info); 1095 else if (strcmp(name, "perf_counter") == 0) 1096 obj = perf_counter(&info); 1097 else if (strcmp(name, "process_time") == 0) 1098 obj = py_process_time(&info); 1099 else { 1100 PyErr_SetString(PyExc_ValueError, "unknown clock"); 1101 return NULL; 1102 } 1103 if (obj == NULL) 1104 return NULL; 1105 Py_DECREF(obj); 1106 1107 dict = PyDict_New(); 1108 if (dict == NULL) 1109 return NULL; 1110 1111 assert(info.implementation != NULL); 1112 obj = PyUnicode_FromString(info.implementation); 1113 if (obj == NULL) 1114 goto error; 1115 if (PyDict_SetItemString(dict, "implementation", obj) == -1) 1116 goto error; 1117 Py_CLEAR(obj); 1118 1119 assert(info.monotonic != -1); 1120 obj = PyBool_FromLong(info.monotonic); 1121 if (obj == NULL) 1122 goto error; 1123 if (PyDict_SetItemString(dict, "monotonic", obj) == -1) 1124 goto error; 1125 Py_CLEAR(obj); 1126 1127 assert(info.adjustable != -1); 1128 obj = PyBool_FromLong(info.adjustable); 1129 if (obj == NULL) 1130 goto error; 1131 if (PyDict_SetItemString(dict, "adjustable", obj) == -1) 1132 goto error; 1133 Py_CLEAR(obj); 1134 1135 assert(info.resolution > 0.0); 1136 assert(info.resolution <= 1.0); 1137 obj = PyFloat_FromDouble(info.resolution); 1138 if (obj == NULL) 1139 goto error; 1140 if (PyDict_SetItemString(dict, "resolution", obj) == -1) 1141 goto error; 1142 Py_CLEAR(obj); 1143 1144 ns = _PyNamespace_New(dict); 1145 Py_DECREF(dict); 1146 return ns; 1147 1148 error: 1149 Py_DECREF(dict); 1150 Py_XDECREF(obj); 1151 return NULL; 1152 } 1153 1154 PyDoc_STRVAR(get_clock_info_doc, 1155 "get_clock_info(name: str) -> dict\n\ 1156 \n\ 1157 Get information of the specified clock."); 1158 1159 static void 1160 get_zone(char *zone, int n, struct tm *p) 1161 { 1162 #ifdef HAVE_STRUCT_TM_TM_ZONE 1163 strncpy(zone, p->tm_zone ? p->tm_zone : " ", n); 1164 #else 1165 tzset(); 1166 strftime(zone, n, "%Z", p); 1167 #endif 1168 } 1169 1170 static int 1171 get_gmtoff(time_t t, struct tm *p) 1172 { 1173 #ifdef HAVE_STRUCT_TM_TM_ZONE 1174 return p->tm_gmtoff; 1175 #else 1176 return timegm(p) - t; 1177 #endif 1178 } 1179 1180 static void 1181 PyInit_timezone(PyObject *m) { 1182 /* This code moved from PyInit_time wholesale to allow calling it from 1183 time_tzset. In the future, some parts of it can be moved back 1184 (for platforms that don't HAVE_WORKING_TZSET, when we know what they 1185 are), and the extraneous calls to tzset(3) should be removed. 1186 I haven't done this yet, as I don't want to change this code as 1187 little as possible when introducing the time.tzset and time.tzsetwall 1188 methods. This should simply be a method of doing the following once, 1189 at the top of this function and removing the call to tzset() from 1190 time_tzset(): 1191 1192 #ifdef HAVE_TZSET 1193 tzset() 1194 #endif 1195 1196 And I'm lazy and hate C so nyer. 1197 */ 1198 #if defined(HAVE_TZNAME) && !defined(__GLIBC__) && !defined(__CYGWIN__) 1199 PyObject *otz0, *otz1; 1200 tzset(); 1201 PyModule_AddIntConstant(m, "timezone", timezone); 1202 #ifdef HAVE_ALTZONE 1203 PyModule_AddIntConstant(m, "altzone", altzone); 1204 #else 1205 PyModule_AddIntConstant(m, "altzone", timezone-3600); 1206 #endif 1207 PyModule_AddIntConstant(m, "daylight", daylight); 1208 otz0 = PyUnicode_DecodeLocale(tzname[0], "surrogateescape"); 1209 otz1 = PyUnicode_DecodeLocale(tzname[1], "surrogateescape"); 1210 PyModule_AddObject(m, "tzname", Py_BuildValue("(NN)", otz0, otz1)); 1211 #else /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/ 1212 { 1213 #define YEAR ((time_t)((365 * 24 + 6) * 3600)) 1214 time_t t; 1215 struct tm p; 1216 long janzone, julyzone; 1217 char janname[10], julyname[10]; 1218 t = (time((time_t *)0) / YEAR) * YEAR; 1219 _PyTime_localtime(t, &p); 1220 get_zone(janname, 9, &p); 1221 janzone = -get_gmtoff(t, &p); 1222 janname[9] = '\0'; 1223 t += YEAR/2; 1224 _PyTime_localtime(t, &p); 1225 get_zone(julyname, 9, &p); 1226 julyzone = -get_gmtoff(t, &p); 1227 julyname[9] = '\0'; 1228 1229 if( janzone < julyzone ) { 1230 /* DST is reversed in the southern hemisphere */ 1231 PyModule_AddIntConstant(m, "timezone", julyzone); 1232 PyModule_AddIntConstant(m, "altzone", janzone); 1233 PyModule_AddIntConstant(m, "daylight", 1234 janzone != julyzone); 1235 PyModule_AddObject(m, "tzname", 1236 Py_BuildValue("(zz)", 1237 julyname, janname)); 1238 } else { 1239 PyModule_AddIntConstant(m, "timezone", janzone); 1240 PyModule_AddIntConstant(m, "altzone", julyzone); 1241 PyModule_AddIntConstant(m, "daylight", 1242 janzone != julyzone); 1243 PyModule_AddObject(m, "tzname", 1244 Py_BuildValue("(zz)", 1245 janname, julyname)); 1246 } 1247 } 1248 #ifdef __CYGWIN__ 1249 tzset(); 1250 PyModule_AddIntConstant(m, "timezone", _timezone); 1251 PyModule_AddIntConstant(m, "altzone", _timezone-3600); 1252 PyModule_AddIntConstant(m, "daylight", _daylight); 1253 PyModule_AddObject(m, "tzname", 1254 Py_BuildValue("(zz)", _tzname[0], _tzname[1])); 1255 #endif /* __CYGWIN__ */ 1256 #endif /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/ 1257 } 1258 1259 1260 static PyMethodDef time_methods[] = { 1261 {"time", time_time, METH_NOARGS, time_doc}, 1262 #ifdef PYCLOCK 1263 {"clock", time_clock, METH_NOARGS, clock_doc}, 1264 #endif 1265 #ifdef HAVE_CLOCK_GETTIME 1266 {"clock_gettime", time_clock_gettime, METH_VARARGS, clock_gettime_doc}, 1267 #endif 1268 #ifdef HAVE_CLOCK_SETTIME 1269 {"clock_settime", time_clock_settime, METH_VARARGS, clock_settime_doc}, 1270 #endif 1271 #ifdef HAVE_CLOCK_GETRES 1272 {"clock_getres", time_clock_getres, METH_VARARGS, clock_getres_doc}, 1273 #endif 1274 {"sleep", time_sleep, METH_O, sleep_doc}, 1275 {"gmtime", time_gmtime, METH_VARARGS, gmtime_doc}, 1276 {"localtime", time_localtime, METH_VARARGS, localtime_doc}, 1277 {"asctime", time_asctime, METH_VARARGS, asctime_doc}, 1278 {"ctime", time_ctime, METH_VARARGS, ctime_doc}, 1279 #ifdef HAVE_MKTIME 1280 {"mktime", time_mktime, METH_O, mktime_doc}, 1281 #endif 1282 #ifdef HAVE_STRFTIME 1283 {"strftime", time_strftime, METH_VARARGS, strftime_doc}, 1284 #endif 1285 {"strptime", time_strptime, METH_VARARGS, strptime_doc}, 1286 #ifdef HAVE_WORKING_TZSET 1287 {"tzset", time_tzset, METH_NOARGS, tzset_doc}, 1288 #endif 1289 {"monotonic", time_monotonic, METH_NOARGS, monotonic_doc}, 1290 {"process_time", time_process_time, METH_NOARGS, process_time_doc}, 1291 {"perf_counter", time_perf_counter, METH_NOARGS, perf_counter_doc}, 1292 {"get_clock_info", time_get_clock_info, METH_VARARGS, get_clock_info_doc}, 1293 {NULL, NULL} /* sentinel */ 1294 }; 1295 1296 1297 PyDoc_STRVAR(module_doc, 1298 "This module provides various functions to manipulate time values.\n\ 1299 \n\ 1300 There are two standard representations of time. One is the number\n\ 1301 of seconds since the Epoch, in UTC (a.k.a. GMT). It may be an integer\n\ 1302 or a floating point number (to represent fractions of seconds).\n\ 1303 The Epoch is system-defined; on Unix, it is generally January 1st, 1970.\n\ 1304 The actual value can be retrieved by calling gmtime(0).\n\ 1305 \n\ 1306 The other representation is a tuple of 9 integers giving local time.\n\ 1307 The tuple items are:\n\ 1308 year (including century, e.g. 1998)\n\ 1309 month (1-12)\n\ 1310 day (1-31)\n\ 1311 hours (0-23)\n\ 1312 minutes (0-59)\n\ 1313 seconds (0-59)\n\ 1314 weekday (0-6, Monday is 0)\n\ 1315 Julian day (day in the year, 1-366)\n\ 1316 DST (Daylight Savings Time) flag (-1, 0 or 1)\n\ 1317 If the DST flag is 0, the time is given in the regular time zone;\n\ 1318 if it is 1, the time is given in the DST time zone;\n\ 1319 if it is -1, mktime() should guess based on the date and time.\n\ 1320 \n\ 1321 Variables:\n\ 1322 \n\ 1323 timezone -- difference in seconds between UTC and local standard time\n\ 1324 altzone -- difference in seconds between UTC and local DST time\n\ 1325 daylight -- whether local time should reflect DST\n\ 1326 tzname -- tuple of (standard time zone name, DST time zone name)\n\ 1327 \n\ 1328 Functions:\n\ 1329 \n\ 1330 time() -- return current time in seconds since the Epoch as a float\n\ 1331 clock() -- return CPU time since process start as a float\n\ 1332 sleep() -- delay for a number of seconds given as a float\n\ 1333 gmtime() -- convert seconds since Epoch to UTC tuple\n\ 1334 localtime() -- convert seconds since Epoch to local time tuple\n\ 1335 asctime() -- convert time tuple to string\n\ 1336 ctime() -- convert time in seconds to string\n\ 1337 mktime() -- convert local time tuple to seconds since Epoch\n\ 1338 strftime() -- convert time tuple to string according to format specification\n\ 1339 strptime() -- parse string to time tuple according to format specification\n\ 1340 tzset() -- change the local timezone"); 1341 1342 1343 1344 static struct PyModuleDef timemodule = { 1345 PyModuleDef_HEAD_INIT, 1346 "time", 1347 module_doc, 1348 -1, 1349 time_methods, 1350 NULL, 1351 NULL, 1352 NULL, 1353 NULL 1354 }; 1355 1356 PyMODINIT_FUNC 1357 PyInit_time(void) 1358 { 1359 PyObject *m; 1360 m = PyModule_Create(&timemodule); 1361 if (m == NULL) 1362 return NULL; 1363 1364 /* Set, or reset, module variables like time.timezone */ 1365 PyInit_timezone(m); 1366 1367 #ifdef CLOCK_REALTIME 1368 PyModule_AddIntMacro(m, CLOCK_REALTIME); 1369 #endif 1370 #ifdef CLOCK_MONOTONIC 1371 PyModule_AddIntMacro(m, CLOCK_MONOTONIC); 1372 #endif 1373 #ifdef CLOCK_MONOTONIC_RAW 1374 PyModule_AddIntMacro(m, CLOCK_MONOTONIC_RAW); 1375 #endif 1376 #ifdef CLOCK_HIGHRES 1377 PyModule_AddIntMacro(m, CLOCK_HIGHRES); 1378 #endif 1379 #ifdef CLOCK_PROCESS_CPUTIME_ID 1380 PyModule_AddIntMacro(m, CLOCK_PROCESS_CPUTIME_ID); 1381 #endif 1382 #ifdef CLOCK_THREAD_CPUTIME_ID 1383 PyModule_AddIntMacro(m, CLOCK_THREAD_CPUTIME_ID); 1384 #endif 1385 1386 if (!initialized) { 1387 if (PyStructSequence_InitType2(&StructTimeType, 1388 &struct_time_type_desc) < 0) 1389 return NULL; 1390 } 1391 Py_INCREF(&StructTimeType); 1392 PyModule_AddIntConstant(m, "_STRUCT_TM_ITEMS", 11); 1393 PyModule_AddObject(m, "struct_time", (PyObject*) &StructTimeType); 1394 initialized = 1; 1395 return m; 1396 } 1397 1398 static PyObject* 1399 floattime(_Py_clock_info_t *info) 1400 { 1401 _PyTime_t t; 1402 double d; 1403 if (_PyTime_GetSystemClockWithInfo(&t, info) < 0) { 1404 assert(info != NULL); 1405 return NULL; 1406 } 1407 d = _PyTime_AsSecondsDouble(t); 1408 return PyFloat_FromDouble(d); 1409 } 1410 1411 1412 /* Implement pysleep() for various platforms. 1413 When interrupted (or when another error occurs), return -1 and 1414 set an exception; else return 0. */ 1415 1416 static int 1417 pysleep(_PyTime_t secs) 1418 { 1419 _PyTime_t deadline, monotonic; 1420 #ifndef MS_WINDOWS 1421 struct timeval timeout; 1422 int err = 0; 1423 #else 1424 _PyTime_t millisecs; 1425 unsigned long ul_millis; 1426 DWORD rc; 1427 HANDLE hInterruptEvent; 1428 #endif 1429 1430 deadline = _PyTime_GetMonotonicClock() + secs; 1431 1432 do { 1433 #ifndef MS_WINDOWS 1434 if (_PyTime_AsTimeval(secs, &timeout, _PyTime_ROUND_CEILING) < 0) 1435 return -1; 1436 1437 Py_BEGIN_ALLOW_THREADS 1438 err = select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &timeout); 1439 Py_END_ALLOW_THREADS 1440 1441 if (err == 0) 1442 break; 1443 1444 if (errno != EINTR) { 1445 PyErr_SetFromErrno(PyExc_OSError); 1446 return -1; 1447 } 1448 #else 1449 millisecs = _PyTime_AsMilliseconds(secs, _PyTime_ROUND_CEILING); 1450 if (millisecs > (double)ULONG_MAX) { 1451 PyErr_SetString(PyExc_OverflowError, 1452 "sleep length is too large"); 1453 return -1; 1454 } 1455 1456 /* Allow sleep(0) to maintain win32 semantics, and as decreed 1457 * by Guido, only the main thread can be interrupted. 1458 */ 1459 ul_millis = (unsigned long)millisecs; 1460 if (ul_millis == 0 || !_PyOS_IsMainThread()) { 1461 Py_BEGIN_ALLOW_THREADS 1462 Sleep(ul_millis); 1463 Py_END_ALLOW_THREADS 1464 break; 1465 } 1466 1467 hInterruptEvent = _PyOS_SigintEvent(); 1468 ResetEvent(hInterruptEvent); 1469 1470 Py_BEGIN_ALLOW_THREADS 1471 rc = WaitForSingleObjectEx(hInterruptEvent, ul_millis, FALSE); 1472 Py_END_ALLOW_THREADS 1473 1474 if (rc != WAIT_OBJECT_0) 1475 break; 1476 #endif 1477 1478 /* sleep was interrupted by SIGINT */ 1479 if (PyErr_CheckSignals()) 1480 return -1; 1481 1482 monotonic = _PyTime_GetMonotonicClock(); 1483 secs = deadline - monotonic; 1484 if (secs < 0) 1485 break; 1486 /* retry with the recomputed delay */ 1487 } while (1); 1488 1489 return 0; 1490 } 1491