timemodule.c revision c83ea137d7e717f764e2f31fc2544f522de7d857
1 2/* Time module */ 3 4#include "Python.h" 5#include "structseq.h" 6#include "timefuncs.h" 7 8#ifdef __APPLE__ 9#if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_FTIME) 10 /* 11 * floattime falls back to ftime when getttimeofday fails because the latter 12 * might fail on some platforms. This fallback is unwanted on MacOSX because 13 * that makes it impossible to use a binary build on OSX 10.4 on earlier 14 * releases of the OS. Therefore claim we don't support ftime. 15 */ 16# undef HAVE_FTIME 17#endif 18#endif 19 20#include <ctype.h> 21 22#ifdef HAVE_SYS_TYPES_H 23#include <sys/types.h> 24#endif /* HAVE_SYS_TYPES_H */ 25 26#ifdef QUICKWIN 27#include <io.h> 28#endif 29 30#ifdef HAVE_FTIME 31#include <sys/timeb.h> 32#if !defined(MS_WINDOWS) && !defined(PYOS_OS2) 33extern int ftime(struct timeb *); 34#endif /* MS_WINDOWS */ 35#endif /* HAVE_FTIME */ 36 37#if defined(__WATCOMC__) && !defined(__QNX__) 38#include <i86.h> 39#else 40#ifdef MS_WINDOWS 41#define WIN32_LEAN_AND_MEAN 42#include <windows.h> 43#include "pythread.h" 44 45/* helper to allow us to interrupt sleep() on Windows*/ 46static HANDLE hInterruptEvent = NULL; 47static BOOL WINAPI PyCtrlHandler(DWORD dwCtrlType) 48{ 49 SetEvent(hInterruptEvent); 50 /* allow other default handlers to be called. 51 Default Python handler will setup the 52 KeyboardInterrupt exception. 53 */ 54 return FALSE; 55} 56static long main_thread; 57 58 59#if defined(__BORLANDC__) 60/* These overrides not needed for Win32 */ 61#define timezone _timezone 62#define tzname _tzname 63#define daylight _daylight 64#endif /* __BORLANDC__ */ 65#endif /* MS_WINDOWS */ 66#endif /* !__WATCOMC__ || __QNX__ */ 67 68#if defined(MS_WINDOWS) && !defined(__BORLANDC__) 69/* Win32 has better clock replacement; we have our own version below. */ 70#undef HAVE_CLOCK 71#endif /* MS_WINDOWS && !defined(__BORLANDC__) */ 72 73#if defined(PYOS_OS2) 74#define INCL_DOS 75#define INCL_ERRORS 76#include <os2.h> 77#endif 78 79#if defined(PYCC_VACPP) 80#include <sys/time.h> 81#endif 82 83#ifdef __BEOS__ 84#include <time.h> 85/* For bigtime_t, snooze(). - [cjh] */ 86#include <support/SupportDefs.h> 87#include <kernel/OS.h> 88#endif 89 90#ifdef RISCOS 91extern int riscos_sleep(double); 92#endif 93 94/* Forward declarations */ 95static int floatsleep(double); 96static double floattime(void); 97 98/* For Y2K check */ 99static PyObject *moddict; 100 101/* Exposed in timefuncs.h. */ 102time_t 103_PyTime_DoubleToTimet(double x) 104{ 105 time_t result; 106 double diff; 107 108 result = (time_t)x; 109 /* How much info did we lose? time_t may be an integral or 110 * floating type, and we don't know which. If it's integral, 111 * we don't know whether C truncates, rounds, returns the floor, 112 * etc. If we lost a second or more, the C rounding is 113 * unreasonable, or the input just doesn't fit in a time_t; 114 * call it an error regardless. Note that the original cast to 115 * time_t can cause a C error too, but nothing we can do to 116 * worm around that. 117 */ 118 diff = x - (double)result; 119 if (diff <= -1.0 || diff >= 1.0) { 120 PyErr_SetString(PyExc_ValueError, 121 "timestamp out of range for platform time_t"); 122 result = (time_t)-1; 123 } 124 return result; 125} 126 127static PyObject * 128time_time(PyObject *self, PyObject *unused) 129{ 130 double secs; 131 secs = floattime(); 132 if (secs == 0.0) { 133 PyErr_SetFromErrno(PyExc_IOError); 134 return NULL; 135 } 136 return PyFloat_FromDouble(secs); 137} 138 139PyDoc_STRVAR(time_doc, 140"time() -> floating point number\n\ 141\n\ 142Return the current time in seconds since the Epoch.\n\ 143Fractions of a second may be present if the system clock provides them."); 144 145#ifdef HAVE_CLOCK 146 147#ifndef CLOCKS_PER_SEC 148#ifdef CLK_TCK 149#define CLOCKS_PER_SEC CLK_TCK 150#else 151#define CLOCKS_PER_SEC 1000000 152#endif 153#endif 154 155static PyObject * 156time_clock(PyObject *self, PyObject *unused) 157{ 158 return PyFloat_FromDouble(((double)clock()) / CLOCKS_PER_SEC); 159} 160#endif /* HAVE_CLOCK */ 161 162#if defined(MS_WINDOWS) && !defined(__BORLANDC__) 163/* Due to Mark Hammond and Tim Peters */ 164static PyObject * 165time_clock(PyObject *self, PyObject *unused) 166{ 167 static LARGE_INTEGER ctrStart; 168 static double divisor = 0.0; 169 LARGE_INTEGER now; 170 double diff; 171 172 if (divisor == 0.0) { 173 LARGE_INTEGER freq; 174 QueryPerformanceCounter(&ctrStart); 175 if (!QueryPerformanceFrequency(&freq) || freq.QuadPart == 0) { 176 /* Unlikely to happen - this works on all intel 177 machines at least! Revert to clock() */ 178 return PyFloat_FromDouble(((double)clock()) / 179 CLOCKS_PER_SEC); 180 } 181 divisor = (double)freq.QuadPart; 182 } 183 QueryPerformanceCounter(&now); 184 diff = (double)(now.QuadPart - ctrStart.QuadPart); 185 return PyFloat_FromDouble(diff / divisor); 186} 187 188#define HAVE_CLOCK /* So it gets included in the methods */ 189#endif /* MS_WINDOWS && !defined(__BORLANDC__) */ 190 191#ifdef HAVE_CLOCK 192PyDoc_STRVAR(clock_doc, 193"clock() -> floating point number\n\ 194\n\ 195Return the CPU time or real time since the start of the process or since\n\ 196the first call to clock(). This has as much precision as the system\n\ 197records."); 198#endif 199 200static PyObject * 201time_sleep(PyObject *self, PyObject *args) 202{ 203 double secs; 204 if (!PyArg_ParseTuple(args, "d:sleep", &secs)) 205 return NULL; 206 if (floatsleep(secs) != 0) 207 return NULL; 208 Py_INCREF(Py_None); 209 return Py_None; 210} 211 212PyDoc_STRVAR(sleep_doc, 213"sleep(seconds)\n\ 214\n\ 215Delay execution for a given number of seconds. The argument may be\n\ 216a floating point number for subsecond precision."); 217 218static PyStructSequence_Field struct_time_type_fields[] = { 219 {"tm_year", NULL}, 220 {"tm_mon", NULL}, 221 {"tm_mday", NULL}, 222 {"tm_hour", NULL}, 223 {"tm_min", NULL}, 224 {"tm_sec", NULL}, 225 {"tm_wday", NULL}, 226 {"tm_yday", NULL}, 227 {"tm_isdst", NULL}, 228 {0} 229}; 230 231static PyStructSequence_Desc struct_time_type_desc = { 232 "time.struct_time", 233 NULL, 234 struct_time_type_fields, 235 9, 236}; 237 238static int initialized; 239static PyTypeObject StructTimeType; 240 241static PyObject * 242tmtotuple(struct tm *p) 243{ 244 PyObject *v = PyStructSequence_New(&StructTimeType); 245 if (v == NULL) 246 return NULL; 247 248#define SET(i,val) PyStructSequence_SET_ITEM(v, i, PyInt_FromLong((long) val)) 249 250 SET(0, p->tm_year + 1900); 251 SET(1, p->tm_mon + 1); /* Want January == 1 */ 252 SET(2, p->tm_mday); 253 SET(3, p->tm_hour); 254 SET(4, p->tm_min); 255 SET(5, p->tm_sec); 256 SET(6, (p->tm_wday + 6) % 7); /* Want Monday == 0 */ 257 SET(7, p->tm_yday + 1); /* Want January, 1 == 1 */ 258 SET(8, p->tm_isdst); 259#undef SET 260 if (PyErr_Occurred()) { 261 Py_XDECREF(v); 262 return NULL; 263 } 264 265 return v; 266} 267 268static PyObject * 269time_convert(double when, struct tm * (*function)(const time_t *)) 270{ 271 struct tm *p; 272 time_t whent = _PyTime_DoubleToTimet(when); 273 274 if (whent == (time_t)-1 && PyErr_Occurred()) 275 return NULL; 276 errno = 0; 277 p = function(&whent); 278 if (p == NULL) { 279#ifdef EINVAL 280 if (errno == 0) 281 errno = EINVAL; 282#endif 283 return PyErr_SetFromErrno(PyExc_ValueError); 284 } 285 return tmtotuple(p); 286} 287 288/* Parse arg tuple that can contain an optional float-or-None value; 289 format needs to be "|O:name". 290 Returns non-zero on success (parallels PyArg_ParseTuple). 291*/ 292static int 293parse_time_double_args(PyObject *args, char *format, double *pwhen) 294{ 295 PyObject *ot = NULL; 296 297 if (!PyArg_ParseTuple(args, format, &ot)) 298 return 0; 299 if (ot == NULL || ot == Py_None) 300 *pwhen = floattime(); 301 else { 302 double when = PyFloat_AsDouble(ot); 303 if (PyErr_Occurred()) 304 return 0; 305 *pwhen = when; 306 } 307 return 1; 308} 309 310static PyObject * 311time_gmtime(PyObject *self, PyObject *args) 312{ 313 double when; 314 if (!parse_time_double_args(args, "|O:gmtime", &when)) 315 return NULL; 316 return time_convert(when, gmtime); 317} 318 319PyDoc_STRVAR(gmtime_doc, 320"gmtime([seconds]) -> (tm_year, tm_mon, tm_mday, tm_hour, tm_min,\n\ 321 tm_sec, tm_wday, tm_yday, tm_isdst)\n\ 322\n\ 323Convert seconds since the Epoch to a time tuple expressing UTC (a.k.a.\n\ 324GMT). When 'seconds' is not passed in, convert the current time instead."); 325 326static PyObject * 327time_localtime(PyObject *self, PyObject *args) 328{ 329 double when; 330 if (!parse_time_double_args(args, "|O:localtime", &when)) 331 return NULL; 332 return time_convert(when, localtime); 333} 334 335PyDoc_STRVAR(localtime_doc, 336"localtime([seconds]) -> (tm_year,tm_mon,tm_mday,tm_hour,tm_min,\n\ 337 tm_sec,tm_wday,tm_yday,tm_isdst)\n\ 338\n\ 339Convert seconds since the Epoch to a time tuple expressing local time.\n\ 340When 'seconds' is not passed in, convert the current time instead."); 341 342static int 343gettmarg(PyObject *args, struct tm *p) 344{ 345 int y; 346 memset((void *) p, '\0', sizeof(struct tm)); 347 348 if (!PyArg_Parse(args, "(iiiiiiiii)", 349 &y, 350 &p->tm_mon, 351 &p->tm_mday, 352 &p->tm_hour, 353 &p->tm_min, 354 &p->tm_sec, 355 &p->tm_wday, 356 &p->tm_yday, 357 &p->tm_isdst)) 358 return 0; 359 if (y < 1900) { 360 PyObject *accept = PyDict_GetItemString(moddict, 361 "accept2dyear"); 362 if (accept == NULL || !PyInt_Check(accept) || 363 PyInt_AsLong(accept) == 0) { 364 PyErr_SetString(PyExc_ValueError, 365 "year >= 1900 required"); 366 return 0; 367 } 368 if (69 <= y && y <= 99) 369 y += 1900; 370 else if (0 <= y && y <= 68) 371 y += 2000; 372 else { 373 PyErr_SetString(PyExc_ValueError, 374 "year out of range"); 375 return 0; 376 } 377 } 378 p->tm_year = y - 1900; 379 p->tm_mon--; 380 p->tm_wday = (p->tm_wday + 1) % 7; 381 p->tm_yday--; 382 return 1; 383} 384 385#ifdef HAVE_STRFTIME 386static PyObject * 387time_strftime(PyObject *self, PyObject *args) 388{ 389 PyObject *tup = NULL; 390 struct tm buf; 391 const char *fmt; 392 size_t fmtlen, buflen; 393 char *outbuf = 0; 394 size_t i; 395 396 memset((void *) &buf, '\0', sizeof(buf)); 397 398 if (!PyArg_ParseTuple(args, "s|O:strftime", &fmt, &tup)) 399 return NULL; 400 401 if (tup == NULL) { 402 time_t tt = time(NULL); 403 buf = *localtime(&tt); 404 } else if (!gettmarg(tup, &buf)) 405 return NULL; 406 407 /* Checks added to make sure strftime() does not crash Python by 408 indexing blindly into some array for a textual representation 409 by some bad index (fixes bug #897625). 410 411 Also support values of zero from Python code for arguments in which 412 that is out of range by forcing that value to the lowest value that 413 is valid (fixed bug #1520914). 414 415 Valid ranges based on what is allowed in struct tm: 416 417 - tm_year: [0, max(int)] (1) 418 - tm_mon: [0, 11] (2) 419 - tm_mday: [1, 31] 420 - tm_hour: [0, 23] 421 - tm_min: [0, 59] 422 - tm_sec: [0, 60] 423 - tm_wday: [0, 6] (1) 424 - tm_yday: [0, 365] (2) 425 - tm_isdst: [-max(int), max(int)] 426 427 (1) gettmarg() handles bounds-checking. 428 (2) Python's acceptable range is one greater than the range in C, 429 thus need to check against automatic decrement by gettmarg(). 430 */ 431 if (buf.tm_mon == -1) 432 buf.tm_mon = 0; 433 else if (buf.tm_mon < 0 || buf.tm_mon > 11) { 434 PyErr_SetString(PyExc_ValueError, "month out of range"); 435 return NULL; 436 } 437 if (buf.tm_mday == 0) 438 buf.tm_mday = 1; 439 else if (buf.tm_mday < 0 || buf.tm_mday > 31) { 440 PyErr_SetString(PyExc_ValueError, "day of month out of range"); 441 return NULL; 442 } 443 if (buf.tm_hour < 0 || buf.tm_hour > 23) { 444 PyErr_SetString(PyExc_ValueError, "hour out of range"); 445 return NULL; 446 } 447 if (buf.tm_min < 0 || buf.tm_min > 59) { 448 PyErr_SetString(PyExc_ValueError, "minute out of range"); 449 return NULL; 450 } 451 if (buf.tm_sec < 0 || buf.tm_sec > 61) { 452 PyErr_SetString(PyExc_ValueError, "seconds out of range"); 453 return NULL; 454 } 455 /* tm_wday does not need checking of its upper-bound since taking 456 ``% 7`` in gettmarg() automatically restricts the range. */ 457 if (buf.tm_wday < 0) { 458 PyErr_SetString(PyExc_ValueError, "day of week out of range"); 459 return NULL; 460 } 461 if (buf.tm_yday == -1) 462 buf.tm_yday = 0; 463 else if (buf.tm_yday < 0 || buf.tm_yday > 365) { 464 PyErr_SetString(PyExc_ValueError, "day of year out of range"); 465 return NULL; 466 } 467 /* Normalize tm_isdst just in case someone foolishly implements %Z 468 based on the assumption that tm_isdst falls within the range of 469 [-1, 1] */ 470 if (buf.tm_isdst < -1) 471 buf.tm_isdst = -1; 472 else if (buf.tm_isdst > 1) 473 buf.tm_isdst = 1; 474 475#ifdef MS_WINDOWS 476 /* check that the format string contains only valid directives */ 477 for(outbuf = strchr(fmt, '%'); 478 outbuf != NULL; 479 outbuf = strchr(outbuf+2, '%')) 480 { 481 if (outbuf[1]=='#') 482 ++outbuf; /* not documented by python, */ 483 if (outbuf[1]=='\0' || 484 !strchr("aAbBcdfHIjmMpSUwWxXyYzZ%", outbuf[1])) 485 { 486 PyErr_SetString(PyExc_ValueError, "Invalid format string"); 487 return 0; 488 } 489 } 490#endif 491 492 fmtlen = strlen(fmt); 493 494 /* I hate these functions that presume you know how big the output 495 * will be ahead of time... 496 */ 497 for (i = 1024; ; i += i) { 498 outbuf = (char *)malloc(i); 499 if (outbuf == NULL) { 500 return PyErr_NoMemory(); 501 } 502 buflen = strftime(outbuf, i, fmt, &buf); 503 if (buflen > 0 || i >= 256 * fmtlen) { 504 /* If the buffer is 256 times as long as the format, 505 it's probably not failing for lack of room! 506 More likely, the format yields an empty result, 507 e.g. an empty format, or %Z when the timezone 508 is unknown. */ 509 PyObject *ret; 510 ret = PyString_FromStringAndSize(outbuf, buflen); 511 free(outbuf); 512 return ret; 513 } 514 free(outbuf); 515#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__) 516 /* VisualStudio .NET 2005 does this properly */ 517 if (buflen == 0 && errno == EINVAL) { 518 PyErr_SetString(PyExc_ValueError, "Invalid format string"); 519 return 0; 520 } 521#endif 522 523 } 524} 525 526PyDoc_STRVAR(strftime_doc, 527"strftime(format[, tuple]) -> string\n\ 528\n\ 529Convert a time tuple to a string according to a format specification.\n\ 530See the library reference manual for formatting codes. When the time tuple\n\ 531is not present, current time as returned by localtime() is used."); 532#endif /* HAVE_STRFTIME */ 533 534static PyObject * 535time_strptime(PyObject *self, PyObject *args) 536{ 537 PyObject *strptime_module = PyImport_ImportModuleNoBlock("_strptime"); 538 PyObject *strptime_result; 539 540 if (!strptime_module) 541 return NULL; 542 strptime_result = PyObject_CallMethod(strptime_module, 543 "_strptime_time", "O", args); 544 Py_DECREF(strptime_module); 545 return strptime_result; 546} 547 548PyDoc_STRVAR(strptime_doc, 549"strptime(string, format) -> struct_time\n\ 550\n\ 551Parse a string to a time tuple according to a format specification.\n\ 552See the library reference manual for formatting codes (same as strftime())."); 553 554 555static PyObject * 556time_asctime(PyObject *self, PyObject *args) 557{ 558 PyObject *tup = NULL; 559 struct tm buf; 560 char *p; 561 if (!PyArg_UnpackTuple(args, "asctime", 0, 1, &tup)) 562 return NULL; 563 if (tup == NULL) { 564 time_t tt = time(NULL); 565 buf = *localtime(&tt); 566 } else if (!gettmarg(tup, &buf)) 567 return NULL; 568 p = asctime(&buf); 569 if (p[24] == '\n') 570 p[24] = '\0'; 571 return PyString_FromString(p); 572} 573 574PyDoc_STRVAR(asctime_doc, 575"asctime([tuple]) -> string\n\ 576\n\ 577Convert a time tuple to a string, e.g. 'Sat Jun 06 16:26:11 1998'.\n\ 578When the time tuple is not present, current time as returned by localtime()\n\ 579is used."); 580 581static PyObject * 582time_ctime(PyObject *self, PyObject *args) 583{ 584 PyObject *ot = NULL; 585 time_t tt; 586 char *p; 587 588 if (!PyArg_UnpackTuple(args, "ctime", 0, 1, &ot)) 589 return NULL; 590 if (ot == NULL || ot == Py_None) 591 tt = time(NULL); 592 else { 593 double dt = PyFloat_AsDouble(ot); 594 if (PyErr_Occurred()) 595 return NULL; 596 tt = _PyTime_DoubleToTimet(dt); 597 if (tt == (time_t)-1 && PyErr_Occurred()) 598 return NULL; 599 } 600 p = ctime(&tt); 601 if (p == NULL) { 602 PyErr_SetString(PyExc_ValueError, "unconvertible time"); 603 return NULL; 604 } 605 if (p[24] == '\n') 606 p[24] = '\0'; 607 return PyString_FromString(p); 608} 609 610PyDoc_STRVAR(ctime_doc, 611"ctime(seconds) -> string\n\ 612\n\ 613Convert a time in seconds since the Epoch to a string in local time.\n\ 614This is equivalent to asctime(localtime(seconds)). When the time tuple is\n\ 615not present, current time as returned by localtime() is used."); 616 617#ifdef HAVE_MKTIME 618static PyObject * 619time_mktime(PyObject *self, PyObject *tup) 620{ 621 struct tm buf; 622 time_t tt; 623 if (!gettmarg(tup, &buf)) 624 return NULL; 625 tt = mktime(&buf); 626 if (tt == (time_t)(-1)) { 627 PyErr_SetString(PyExc_OverflowError, 628 "mktime argument out of range"); 629 return NULL; 630 } 631 return PyFloat_FromDouble((double)tt); 632} 633 634PyDoc_STRVAR(mktime_doc, 635"mktime(tuple) -> floating point number\n\ 636\n\ 637Convert a time tuple in local time to seconds since the Epoch."); 638#endif /* HAVE_MKTIME */ 639 640#ifdef HAVE_WORKING_TZSET 641static void inittimezone(PyObject *module); 642 643static PyObject * 644time_tzset(PyObject *self, PyObject *unused) 645{ 646 PyObject* m; 647 648 m = PyImport_ImportModuleNoBlock("time"); 649 if (m == NULL) { 650 return NULL; 651 } 652 653 tzset(); 654 655 /* Reset timezone, altzone, daylight and tzname */ 656 inittimezone(m); 657 Py_DECREF(m); 658 659 Py_INCREF(Py_None); 660 return Py_None; 661} 662 663PyDoc_STRVAR(tzset_doc, 664"tzset(zone)\n\ 665\n\ 666Initialize, or reinitialize, the local timezone to the value stored in\n\ 667os.environ['TZ']. The TZ environment variable should be specified in\n\ 668standard Unix timezone format as documented in the tzset man page\n\ 669(eg. 'US/Eastern', 'Europe/Amsterdam'). Unknown timezones will silently\n\ 670fall back to UTC. If the TZ environment variable is not set, the local\n\ 671timezone is set to the systems best guess of wallclock time.\n\ 672Changing the TZ environment variable without calling tzset *may* change\n\ 673the local timezone used by methods such as localtime, but this behaviour\n\ 674should not be relied on."); 675#endif /* HAVE_WORKING_TZSET */ 676 677static void 678inittimezone(PyObject *m) { 679 /* This code moved from inittime wholesale to allow calling it from 680 time_tzset. In the future, some parts of it can be moved back 681 (for platforms that don't HAVE_WORKING_TZSET, when we know what they 682 are), and the extraneous calls to tzset(3) should be removed. 683 I haven't done this yet, as I don't want to change this code as 684 little as possible when introducing the time.tzset and time.tzsetwall 685 methods. This should simply be a method of doing the following once, 686 at the top of this function and removing the call to tzset() from 687 time_tzset(): 688 689 #ifdef HAVE_TZSET 690 tzset() 691 #endif 692 693 And I'm lazy and hate C so nyer. 694 */ 695#if defined(HAVE_TZNAME) && !defined(__GLIBC__) && !defined(__CYGWIN__) 696 tzset(); 697#ifdef PYOS_OS2 698 PyModule_AddIntConstant(m, "timezone", _timezone); 699#else /* !PYOS_OS2 */ 700 PyModule_AddIntConstant(m, "timezone", timezone); 701#endif /* PYOS_OS2 */ 702#ifdef HAVE_ALTZONE 703 PyModule_AddIntConstant(m, "altzone", altzone); 704#else 705#ifdef PYOS_OS2 706 PyModule_AddIntConstant(m, "altzone", _timezone-3600); 707#else /* !PYOS_OS2 */ 708 PyModule_AddIntConstant(m, "altzone", timezone-3600); 709#endif /* PYOS_OS2 */ 710#endif 711 PyModule_AddIntConstant(m, "daylight", daylight); 712 PyModule_AddObject(m, "tzname", 713 Py_BuildValue("(zz)", tzname[0], tzname[1])); 714#else /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/ 715#ifdef HAVE_STRUCT_TM_TM_ZONE 716 { 717#define YEAR ((time_t)((365 * 24 + 6) * 3600)) 718 time_t t; 719 struct tm *p; 720 long janzone, julyzone; 721 char janname[10], julyname[10]; 722 t = (time((time_t *)0) / YEAR) * YEAR; 723 p = localtime(&t); 724 janzone = -p->tm_gmtoff; 725 strncpy(janname, p->tm_zone ? p->tm_zone : " ", 9); 726 janname[9] = '\0'; 727 t += YEAR/2; 728 p = localtime(&t); 729 julyzone = -p->tm_gmtoff; 730 strncpy(julyname, p->tm_zone ? p->tm_zone : " ", 9); 731 julyname[9] = '\0'; 732 733 if( janzone < julyzone ) { 734 /* DST is reversed in the southern hemisphere */ 735 PyModule_AddIntConstant(m, "timezone", julyzone); 736 PyModule_AddIntConstant(m, "altzone", janzone); 737 PyModule_AddIntConstant(m, "daylight", 738 janzone != julyzone); 739 PyModule_AddObject(m, "tzname", 740 Py_BuildValue("(zz)", 741 julyname, janname)); 742 } else { 743 PyModule_AddIntConstant(m, "timezone", janzone); 744 PyModule_AddIntConstant(m, "altzone", julyzone); 745 PyModule_AddIntConstant(m, "daylight", 746 janzone != julyzone); 747 PyModule_AddObject(m, "tzname", 748 Py_BuildValue("(zz)", 749 janname, julyname)); 750 } 751 } 752#else 753#endif /* HAVE_STRUCT_TM_TM_ZONE */ 754#ifdef __CYGWIN__ 755 tzset(); 756 PyModule_AddIntConstant(m, "timezone", _timezone); 757 PyModule_AddIntConstant(m, "altzone", _timezone-3600); 758 PyModule_AddIntConstant(m, "daylight", _daylight); 759 PyModule_AddObject(m, "tzname", 760 Py_BuildValue("(zz)", _tzname[0], _tzname[1])); 761#endif /* __CYGWIN__ */ 762#endif /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/ 763} 764 765 766static PyMethodDef time_methods[] = { 767 {"time", time_time, METH_NOARGS, time_doc}, 768#ifdef HAVE_CLOCK 769 {"clock", time_clock, METH_NOARGS, clock_doc}, 770#endif 771 {"sleep", time_sleep, METH_VARARGS, sleep_doc}, 772 {"gmtime", time_gmtime, METH_VARARGS, gmtime_doc}, 773 {"localtime", time_localtime, METH_VARARGS, localtime_doc}, 774 {"asctime", time_asctime, METH_VARARGS, asctime_doc}, 775 {"ctime", time_ctime, METH_VARARGS, ctime_doc}, 776#ifdef HAVE_MKTIME 777 {"mktime", time_mktime, METH_O, mktime_doc}, 778#endif 779#ifdef HAVE_STRFTIME 780 {"strftime", time_strftime, METH_VARARGS, strftime_doc}, 781#endif 782 {"strptime", time_strptime, METH_VARARGS, strptime_doc}, 783#ifdef HAVE_WORKING_TZSET 784 {"tzset", time_tzset, METH_NOARGS, tzset_doc}, 785#endif 786 {NULL, NULL} /* sentinel */ 787}; 788 789 790PyDoc_STRVAR(module_doc, 791"This module provides various functions to manipulate time values.\n\ 792\n\ 793There are two standard representations of time. One is the number\n\ 794of seconds since the Epoch, in UTC (a.k.a. GMT). It may be an integer\n\ 795or a floating point number (to represent fractions of seconds).\n\ 796The Epoch is system-defined; on Unix, it is generally January 1st, 1970.\n\ 797The actual value can be retrieved by calling gmtime(0).\n\ 798\n\ 799The other representation is a tuple of 9 integers giving local time.\n\ 800The tuple items are:\n\ 801 year (four digits, e.g. 1998)\n\ 802 month (1-12)\n\ 803 day (1-31)\n\ 804 hours (0-23)\n\ 805 minutes (0-59)\n\ 806 seconds (0-59)\n\ 807 weekday (0-6, Monday is 0)\n\ 808 Julian day (day in the year, 1-366)\n\ 809 DST (Daylight Savings Time) flag (-1, 0 or 1)\n\ 810If the DST flag is 0, the time is given in the regular time zone;\n\ 811if it is 1, the time is given in the DST time zone;\n\ 812if it is -1, mktime() should guess based on the date and time.\n\ 813\n\ 814Variables:\n\ 815\n\ 816timezone -- difference in seconds between UTC and local standard time\n\ 817altzone -- difference in seconds between UTC and local DST time\n\ 818daylight -- whether local time should reflect DST\n\ 819tzname -- tuple of (standard time zone name, DST time zone name)\n\ 820\n\ 821Functions:\n\ 822\n\ 823time() -- return current time in seconds since the Epoch as a float\n\ 824clock() -- return CPU time since process start as a float\n\ 825sleep() -- delay for a number of seconds given as a float\n\ 826gmtime() -- convert seconds since Epoch to UTC tuple\n\ 827localtime() -- convert seconds since Epoch to local time tuple\n\ 828asctime() -- convert time tuple to string\n\ 829ctime() -- convert time in seconds to string\n\ 830mktime() -- convert local time tuple to seconds since Epoch\n\ 831strftime() -- convert time tuple to string according to format specification\n\ 832strptime() -- parse string to time tuple according to format specification\n\ 833tzset() -- change the local timezone"); 834 835 836PyMODINIT_FUNC 837inittime(void) 838{ 839 PyObject *m; 840 char *p; 841 m = Py_InitModule3("time", time_methods, module_doc); 842 if (m == NULL) 843 return; 844 845 /* Accept 2-digit dates unless PYTHONY2K is set and non-empty */ 846 p = Py_GETENV("PYTHONY2K"); 847 PyModule_AddIntConstant(m, "accept2dyear", (long) (!p || !*p)); 848 /* Squirrel away the module's dictionary for the y2k check */ 849 moddict = PyModule_GetDict(m); 850 Py_INCREF(moddict); 851 852 /* Set, or reset, module variables like time.timezone */ 853 inittimezone(m); 854 855#ifdef MS_WINDOWS 856 /* Helper to allow interrupts for Windows. 857 If Ctrl+C event delivered while not sleeping 858 it will be ignored. 859 */ 860 main_thread = PyThread_get_thread_ident(); 861 hInterruptEvent = CreateEvent(NULL, TRUE, FALSE, NULL); 862 SetConsoleCtrlHandler( PyCtrlHandler, TRUE); 863#endif /* MS_WINDOWS */ 864 if (!initialized) { 865 PyStructSequence_InitType(&StructTimeType, 866 &struct_time_type_desc); 867 } 868 Py_INCREF(&StructTimeType); 869 PyModule_AddObject(m, "struct_time", (PyObject*) &StructTimeType); 870 initialized = 1; 871} 872 873 874/* Implement floattime() for various platforms */ 875 876static double 877floattime(void) 878{ 879 /* There are three ways to get the time: 880 (1) gettimeofday() -- resolution in microseconds 881 (2) ftime() -- resolution in milliseconds 882 (3) time() -- resolution in seconds 883 In all cases the return value is a float in seconds. 884 Since on some systems (e.g. SCO ODT 3.0) gettimeofday() may 885 fail, so we fall back on ftime() or time(). 886 Note: clock resolution does not imply clock accuracy! */ 887#ifdef HAVE_GETTIMEOFDAY 888 { 889 struct timeval t; 890#ifdef GETTIMEOFDAY_NO_TZ 891 if (gettimeofday(&t) == 0) 892 return (double)t.tv_sec + t.tv_usec*0.000001; 893#else /* !GETTIMEOFDAY_NO_TZ */ 894 if (gettimeofday(&t, (struct timezone *)NULL) == 0) 895 return (double)t.tv_sec + t.tv_usec*0.000001; 896#endif /* !GETTIMEOFDAY_NO_TZ */ 897 } 898 899#endif /* !HAVE_GETTIMEOFDAY */ 900 { 901#if defined(HAVE_FTIME) 902 struct timeb t; 903 ftime(&t); 904 return (double)t.time + (double)t.millitm * (double)0.001; 905#else /* !HAVE_FTIME */ 906 time_t secs; 907 time(&secs); 908 return (double)secs; 909#endif /* !HAVE_FTIME */ 910 } 911} 912 913 914/* Implement floatsleep() for various platforms. 915 When interrupted (or when another error occurs), return -1 and 916 set an exception; else return 0. */ 917 918static int 919floatsleep(double secs) 920{ 921/* XXX Should test for MS_WINDOWS first! */ 922#if defined(HAVE_SELECT) && !defined(__BEOS__) && !defined(__EMX__) 923 struct timeval t; 924 double frac; 925 frac = fmod(secs, 1.0); 926 secs = floor(secs); 927 t.tv_sec = (long)secs; 928 t.tv_usec = (long)(frac*1000000.0); 929 Py_BEGIN_ALLOW_THREADS 930 if (select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &t) != 0) { 931#ifdef EINTR 932 if (errno != EINTR) { 933#else 934 if (1) { 935#endif 936 Py_BLOCK_THREADS 937 PyErr_SetFromErrno(PyExc_IOError); 938 return -1; 939 } 940 } 941 Py_END_ALLOW_THREADS 942#elif defined(__WATCOMC__) && !defined(__QNX__) 943 /* XXX Can't interrupt this sleep */ 944 Py_BEGIN_ALLOW_THREADS 945 delay((int)(secs * 1000 + 0.5)); /* delay() uses milliseconds */ 946 Py_END_ALLOW_THREADS 947#elif defined(MS_WINDOWS) 948 { 949 double millisecs = secs * 1000.0; 950 unsigned long ul_millis; 951 952 if (millisecs > (double)ULONG_MAX) { 953 PyErr_SetString(PyExc_OverflowError, 954 "sleep length is too large"); 955 return -1; 956 } 957 Py_BEGIN_ALLOW_THREADS 958 /* Allow sleep(0) to maintain win32 semantics, and as decreed 959 * by Guido, only the main thread can be interrupted. 960 */ 961 ul_millis = (unsigned long)millisecs; 962 if (ul_millis == 0 || 963 main_thread != PyThread_get_thread_ident()) 964 Sleep(ul_millis); 965 else { 966 DWORD rc; 967 ResetEvent(hInterruptEvent); 968 rc = WaitForSingleObject(hInterruptEvent, ul_millis); 969 if (rc == WAIT_OBJECT_0) { 970 /* Yield to make sure real Python signal 971 * handler called. 972 */ 973 Sleep(1); 974 Py_BLOCK_THREADS 975 errno = EINTR; 976 PyErr_SetFromErrno(PyExc_IOError); 977 return -1; 978 } 979 } 980 Py_END_ALLOW_THREADS 981 } 982#elif defined(PYOS_OS2) 983 /* This Sleep *IS* Interruptable by Exceptions */ 984 Py_BEGIN_ALLOW_THREADS 985 if (DosSleep(secs * 1000) != NO_ERROR) { 986 Py_BLOCK_THREADS 987 PyErr_SetFromErrno(PyExc_IOError); 988 return -1; 989 } 990 Py_END_ALLOW_THREADS 991#elif defined(__BEOS__) 992 /* This sleep *CAN BE* interrupted. */ 993 { 994 if( secs <= 0.0 ) { 995 return; 996 } 997 998 Py_BEGIN_ALLOW_THREADS 999 /* BeOS snooze() is in microseconds... */ 1000 if( snooze( (bigtime_t)( secs * 1000.0 * 1000.0 ) ) == B_INTERRUPTED ) { 1001 Py_BLOCK_THREADS 1002 PyErr_SetFromErrno( PyExc_IOError ); 1003 return -1; 1004 } 1005 Py_END_ALLOW_THREADS 1006 } 1007#elif defined(RISCOS) 1008 if (secs <= 0.0) 1009 return 0; 1010 Py_BEGIN_ALLOW_THREADS 1011 /* This sleep *CAN BE* interrupted. */ 1012 if ( riscos_sleep(secs) ) 1013 return -1; 1014 Py_END_ALLOW_THREADS 1015#elif defined(PLAN9) 1016 { 1017 double millisecs = secs * 1000.0; 1018 if (millisecs > (double)LONG_MAX) { 1019 PyErr_SetString(PyExc_OverflowError, "sleep length is too large"); 1020 return -1; 1021 } 1022 /* This sleep *CAN BE* interrupted. */ 1023 Py_BEGIN_ALLOW_THREADS 1024 if(sleep((long)millisecs) < 0){ 1025 Py_BLOCK_THREADS 1026 PyErr_SetFromErrno(PyExc_IOError); 1027 return -1; 1028 } 1029 Py_END_ALLOW_THREADS 1030 } 1031#else 1032 /* XXX Can't interrupt this sleep */ 1033 Py_BEGIN_ALLOW_THREADS 1034 sleep((int)secs); 1035 Py_END_ALLOW_THREADS 1036#endif 1037 1038 return 0; 1039} 1040 1041 1042