Python-2.7.3/Modules/timemodule.c

No issues found

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