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