Instead of doing a make test, run the regression tests out of the installed
[python.git] / Modules / timemodule.c
blob2133273872544dad48c59188f80d9ddc0aed6c13
2 /* Time module */
4 #include "Python.h"
5 #include "structseq.h"
6 #include "timefuncs.h"
8 #ifdef __APPLE__
9 #if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_FTIME)
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.
16 # undef HAVE_FTIME
17 #endif
18 #endif
20 #include <ctype.h>
22 #ifdef HAVE_SYS_TYPES_H
23 #include <sys/types.h>
24 #endif /* HAVE_SYS_TYPES_H */
26 #ifdef QUICKWIN
27 #include <io.h>
28 #endif
30 #ifdef HAVE_FTIME
31 #include <sys/timeb.h>
32 #if !defined(MS_WINDOWS) && !defined(PYOS_OS2)
33 extern int ftime(struct timeb *);
34 #endif /* MS_WINDOWS */
35 #endif /* HAVE_FTIME */
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"
45 /* helper to allow us to interrupt sleep() on Windows*/
46 static HANDLE hInterruptEvent = NULL;
47 static BOOL WINAPI PyCtrlHandler(DWORD dwCtrlType)
49 SetEvent(hInterruptEvent);
50 /* allow other default handlers to be called.
51 Default Python handler will setup the
52 KeyboardInterrupt exception.
54 return FALSE;
56 static long main_thread;
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__ */
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__) */
73 #if defined(PYOS_OS2)
74 #define INCL_DOS
75 #define INCL_ERRORS
76 #include <os2.h>
77 #endif
79 #if defined(PYCC_VACPP)
80 #include <sys/time.h>
81 #endif
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
90 #ifdef RISCOS
91 extern int riscos_sleep(double);
92 #endif
94 /* Forward declarations */
95 static int floatsleep(double);
96 static double floattime(void);
98 /* For Y2K check */
99 static PyObject *moddict;
101 /* Exposed in timefuncs.h. */
102 time_t
103 _PyTime_DoubleToTimet(double x)
105 time_t result;
106 double diff;
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.
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;
124 return result;
127 static PyObject *
128 time_time(PyObject *self, PyObject *unused)
130 double secs;
131 secs = floattime();
132 if (secs == 0.0) {
133 PyErr_SetFromErrno(PyExc_IOError);
134 return NULL;
136 return PyFloat_FromDouble(secs);
139 PyDoc_STRVAR(time_doc,
140 "time() -> floating point number\n\
142 Return the current time in seconds since the Epoch.\n\
143 Fractions of a second may be present if the system clock provides them.");
145 #ifdef HAVE_CLOCK
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
155 static PyObject *
156 time_clock(PyObject *self, PyObject *unused)
158 return PyFloat_FromDouble(((double)clock()) / CLOCKS_PER_SEC);
160 #endif /* HAVE_CLOCK */
162 #if defined(MS_WINDOWS) && !defined(__BORLANDC__)
163 /* Due to Mark Hammond and Tim Peters */
164 static PyObject *
165 time_clock(PyObject *self, PyObject *unused)
167 static LARGE_INTEGER ctrStart;
168 static double divisor = 0.0;
169 LARGE_INTEGER now;
170 double diff;
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(clock());
180 divisor = (double)freq.QuadPart;
182 QueryPerformanceCounter(&now);
183 diff = (double)(now.QuadPart - ctrStart.QuadPart);
184 return PyFloat_FromDouble(diff / divisor);
187 #define HAVE_CLOCK /* So it gets included in the methods */
188 #endif /* MS_WINDOWS && !defined(__BORLANDC__) */
190 #ifdef HAVE_CLOCK
191 PyDoc_STRVAR(clock_doc,
192 "clock() -> floating point number\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
199 static PyObject *
200 time_sleep(PyObject *self, PyObject *args)
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;
211 PyDoc_STRVAR(sleep_doc,
212 "sleep(seconds)\n\
214 Delay execution for a given number of seconds. The argument may be\n\
215 a floating point number for subsecond precision.");
217 static PyStructSequence_Field struct_time_type_fields[] = {
218 {"tm_year", NULL},
219 {"tm_mon", NULL},
220 {"tm_mday", NULL},
221 {"tm_hour", NULL},
222 {"tm_min", NULL},
223 {"tm_sec", NULL},
224 {"tm_wday", NULL},
225 {"tm_yday", NULL},
226 {"tm_isdst", NULL},
230 static PyStructSequence_Desc struct_time_type_desc = {
231 "time.struct_time",
232 NULL,
233 struct_time_type_fields,
237 static int initialized;
238 static PyTypeObject StructTimeType;
240 static PyObject *
241 tmtotuple(struct tm *p)
243 PyObject *v = PyStructSequence_New(&StructTimeType);
244 if (v == NULL)
245 return NULL;
247 #define SET(i,val) PyStructSequence_SET_ITEM(v, i, PyInt_FromLong((long) val))
249 SET(0, p->tm_year + 1900);
250 SET(1, p->tm_mon + 1); /* Want January == 1 */
251 SET(2, p->tm_mday);
252 SET(3, p->tm_hour);
253 SET(4, p->tm_min);
254 SET(5, p->tm_sec);
255 SET(6, (p->tm_wday + 6) % 7); /* Want Monday == 0 */
256 SET(7, p->tm_yday + 1); /* Want January, 1 == 1 */
257 SET(8, p->tm_isdst);
258 #undef SET
259 if (PyErr_Occurred()) {
260 Py_XDECREF(v);
261 return NULL;
264 return v;
267 static PyObject *
268 time_convert(double when, struct tm * (*function)(const time_t *))
270 struct tm *p;
271 time_t whent = _PyTime_DoubleToTimet(when);
273 if (whent == (time_t)-1 && PyErr_Occurred())
274 return NULL;
275 errno = 0;
276 p = function(&whent);
277 if (p == NULL) {
278 #ifdef EINVAL
279 if (errno == 0)
280 errno = EINVAL;
281 #endif
282 return PyErr_SetFromErrno(PyExc_ValueError);
284 return tmtotuple(p);
287 /* Parse arg tuple that can contain an optional float-or-None value;
288 format needs to be "|O:name".
289 Returns non-zero on success (parallels PyArg_ParseTuple).
291 static int
292 parse_time_double_args(PyObject *args, char *format, double *pwhen)
294 PyObject *ot = NULL;
296 if (!PyArg_ParseTuple(args, format, &ot))
297 return 0;
298 if (ot == NULL || ot == Py_None)
299 *pwhen = floattime();
300 else {
301 double when = PyFloat_AsDouble(ot);
302 if (PyErr_Occurred())
303 return 0;
304 *pwhen = when;
306 return 1;
309 static PyObject *
310 time_gmtime(PyObject *self, PyObject *args)
312 double when;
313 if (!parse_time_double_args(args, "|O:gmtime", &when))
314 return NULL;
315 return time_convert(when, gmtime);
318 PyDoc_STRVAR(gmtime_doc,
319 "gmtime([seconds]) -> (tm_year, tm_mon, tm_day, tm_hour, tm_min,\n\
320 tm_sec, tm_wday, tm_yday, tm_isdst)\n\
322 Convert seconds since the Epoch to a time tuple expressing UTC (a.k.a.\n\
323 GMT). When 'seconds' is not passed in, convert the current time instead.");
325 static PyObject *
326 time_localtime(PyObject *self, PyObject *args)
328 double when;
329 if (!parse_time_double_args(args, "|O:localtime", &when))
330 return NULL;
331 return time_convert(when, localtime);
334 PyDoc_STRVAR(localtime_doc,
335 "localtime([seconds]) -> (tm_year,tm_mon,tm_day,tm_hour,tm_min,tm_sec,tm_wday,tm_yday,tm_isdst)\n\
337 Convert seconds since the Epoch to a time tuple expressing local time.\n\
338 When 'seconds' is not passed in, convert the current time instead.");
340 static int
341 gettmarg(PyObject *args, struct tm *p)
343 int y;
344 memset((void *) p, '\0', sizeof(struct tm));
346 if (!PyArg_Parse(args, "(iiiiiiiii)",
348 &p->tm_mon,
349 &p->tm_mday,
350 &p->tm_hour,
351 &p->tm_min,
352 &p->tm_sec,
353 &p->tm_wday,
354 &p->tm_yday,
355 &p->tm_isdst))
356 return 0;
357 if (y < 1900) {
358 PyObject *accept = PyDict_GetItemString(moddict,
359 "accept2dyear");
360 if (accept == NULL || !PyInt_Check(accept) ||
361 PyInt_AsLong(accept) == 0) {
362 PyErr_SetString(PyExc_ValueError,
363 "year >= 1900 required");
364 return 0;
366 if (69 <= y && y <= 99)
367 y += 1900;
368 else if (0 <= y && y <= 68)
369 y += 2000;
370 else {
371 PyErr_SetString(PyExc_ValueError,
372 "year out of range");
373 return 0;
376 p->tm_year = y - 1900;
377 p->tm_mon--;
378 p->tm_wday = (p->tm_wday + 1) % 7;
379 p->tm_yday--;
380 return 1;
383 #ifdef HAVE_STRFTIME
384 static PyObject *
385 time_strftime(PyObject *self, PyObject *args)
387 PyObject *tup = NULL;
388 struct tm buf;
389 const char *fmt;
390 size_t fmtlen, buflen;
391 char *outbuf = 0;
392 size_t i;
394 memset((void *) &buf, '\0', sizeof(buf));
396 if (!PyArg_ParseTuple(args, "s|O:strftime", &fmt, &tup))
397 return NULL;
399 if (tup == NULL) {
400 time_t tt = time(NULL);
401 buf = *localtime(&tt);
402 } else if (!gettmarg(tup, &buf))
403 return NULL;
405 /* Checks added to make sure strftime() does not crash Python by
406 indexing blindly into some array for a textual representation
407 by some bad index (fixes bug #897625).
409 No check for year since handled in gettmarg().
411 if (buf.tm_mon < 0 || buf.tm_mon > 11) {
412 PyErr_SetString(PyExc_ValueError, "month out of range");
413 return NULL;
415 if (buf.tm_mday < 1 || buf.tm_mday > 31) {
416 PyErr_SetString(PyExc_ValueError, "day of month out of range");
417 return NULL;
419 if (buf.tm_hour < 0 || buf.tm_hour > 23) {
420 PyErr_SetString(PyExc_ValueError, "hour out of range");
421 return NULL;
423 if (buf.tm_min < 0 || buf.tm_min > 59) {
424 PyErr_SetString(PyExc_ValueError, "minute out of range");
425 return NULL;
427 if (buf.tm_sec < 0 || buf.tm_sec > 61) {
428 PyErr_SetString(PyExc_ValueError, "seconds out of range");
429 return NULL;
431 /* tm_wday does not need checking of its upper-bound since taking
432 ``% 7`` in gettmarg() automatically restricts the range. */
433 if (buf.tm_wday < 0) {
434 PyErr_SetString(PyExc_ValueError, "day of week out of range");
435 return NULL;
437 if (buf.tm_yday < 0 || buf.tm_yday > 365) {
438 PyErr_SetString(PyExc_ValueError, "day of year out of range");
439 return NULL;
441 if (buf.tm_isdst < -1 || buf.tm_isdst > 1) {
442 PyErr_SetString(PyExc_ValueError,
443 "daylight savings flag out of range");
444 return NULL;
447 fmtlen = strlen(fmt);
449 /* I hate these functions that presume you know how big the output
450 * will be ahead of time...
452 for (i = 1024; ; i += i) {
453 outbuf = (char *)malloc(i);
454 if (outbuf == NULL) {
455 return PyErr_NoMemory();
457 buflen = strftime(outbuf, i, fmt, &buf);
458 if (buflen > 0 || i >= 256 * fmtlen) {
459 /* If the buffer is 256 times as long as the format,
460 it's probably not failing for lack of room!
461 More likely, the format yields an empty result,
462 e.g. an empty format, or %Z when the timezone
463 is unknown. */
464 PyObject *ret;
465 ret = PyString_FromStringAndSize(outbuf, buflen);
466 free(outbuf);
467 return ret;
469 free(outbuf);
470 #if defined _MSC_VER && _MSC_VER >= 1400
471 /* VisualStudio .NET 2005 does this properly */
472 if (buflen == 0 && errno == EINVAL) {
473 PyErr_SetString(PyExc_ValueError, "Invalid format string");
474 return 0;
476 #endif
481 PyDoc_STRVAR(strftime_doc,
482 "strftime(format[, tuple]) -> string\n\
484 Convert a time tuple to a string according to a format specification.\n\
485 See the library reference manual for formatting codes. When the time tuple\n\
486 is not present, current time as returned by localtime() is used.");
487 #endif /* HAVE_STRFTIME */
489 static PyObject *
490 time_strptime(PyObject *self, PyObject *args)
492 PyObject *strptime_module = PyImport_ImportModule("_strptime");
493 PyObject *strptime_result;
495 if (!strptime_module)
496 return NULL;
497 strptime_result = PyObject_CallMethod(strptime_module, "strptime", "O", args);
498 Py_DECREF(strptime_module);
499 return strptime_result;
502 PyDoc_STRVAR(strptime_doc,
503 "strptime(string, format) -> struct_time\n\
505 Parse a string to a time tuple according to a format specification.\n\
506 See the library reference manual for formatting codes (same as strftime()).");
509 static PyObject *
510 time_asctime(PyObject *self, PyObject *args)
512 PyObject *tup = NULL;
513 struct tm buf;
514 char *p;
515 if (!PyArg_UnpackTuple(args, "asctime", 0, 1, &tup))
516 return NULL;
517 if (tup == NULL) {
518 time_t tt = time(NULL);
519 buf = *localtime(&tt);
520 } else if (!gettmarg(tup, &buf))
521 return NULL;
522 p = asctime(&buf);
523 if (p[24] == '\n')
524 p[24] = '\0';
525 return PyString_FromString(p);
528 PyDoc_STRVAR(asctime_doc,
529 "asctime([tuple]) -> string\n\
531 Convert a time tuple to a string, e.g. 'Sat Jun 06 16:26:11 1998'.\n\
532 When the time tuple is not present, current time as returned by localtime()\n\
533 is used.");
535 static PyObject *
536 time_ctime(PyObject *self, PyObject *args)
538 PyObject *ot = NULL;
539 time_t tt;
540 char *p;
542 if (!PyArg_UnpackTuple(args, "ctime", 0, 1, &ot))
543 return NULL;
544 if (ot == NULL || ot == Py_None)
545 tt = time(NULL);
546 else {
547 double dt = PyFloat_AsDouble(ot);
548 if (PyErr_Occurred())
549 return NULL;
550 tt = _PyTime_DoubleToTimet(dt);
551 if (tt == (time_t)-1 && PyErr_Occurred())
552 return NULL;
554 p = ctime(&tt);
555 if (p == NULL) {
556 PyErr_SetString(PyExc_ValueError, "unconvertible time");
557 return NULL;
559 if (p[24] == '\n')
560 p[24] = '\0';
561 return PyString_FromString(p);
564 PyDoc_STRVAR(ctime_doc,
565 "ctime(seconds) -> string\n\
567 Convert a time in seconds since the Epoch to a string in local time.\n\
568 This is equivalent to asctime(localtime(seconds)). When the time tuple is\n\
569 not present, current time as returned by localtime() is used.");
571 #ifdef HAVE_MKTIME
572 static PyObject *
573 time_mktime(PyObject *self, PyObject *tup)
575 struct tm buf;
576 time_t tt;
577 tt = time(&tt);
578 buf = *localtime(&tt);
579 if (!gettmarg(tup, &buf))
580 return NULL;
581 tt = mktime(&buf);
582 if (tt == (time_t)(-1)) {
583 PyErr_SetString(PyExc_OverflowError,
584 "mktime argument out of range");
585 return NULL;
587 return PyFloat_FromDouble((double)tt);
590 PyDoc_STRVAR(mktime_doc,
591 "mktime(tuple) -> floating point number\n\
593 Convert a time tuple in local time to seconds since the Epoch.");
594 #endif /* HAVE_MKTIME */
596 #ifdef HAVE_WORKING_TZSET
597 void inittimezone(PyObject *module);
599 static PyObject *
600 time_tzset(PyObject *self, PyObject *unused)
602 PyObject* m;
604 m = PyImport_ImportModule("time");
605 if (m == NULL) {
606 return NULL;
609 tzset();
611 /* Reset timezone, altzone, daylight and tzname */
612 inittimezone(m);
613 Py_DECREF(m);
615 Py_INCREF(Py_None);
616 return Py_None;
619 PyDoc_STRVAR(tzset_doc,
620 "tzset(zone)\n\
622 Initialize, or reinitialize, the local timezone to the value stored in\n\
623 os.environ['TZ']. The TZ environment variable should be specified in\n\
624 standard Unix timezone format as documented in the tzset man page\n\
625 (eg. 'US/Eastern', 'Europe/Amsterdam'). Unknown timezones will silently\n\
626 fall back to UTC. If the TZ environment variable is not set, the local\n\
627 timezone is set to the systems best guess of wallclock time.\n\
628 Changing the TZ environment variable without calling tzset *may* change\n\
629 the local timezone used by methods such as localtime, but this behaviour\n\
630 should not be relied on.");
631 #endif /* HAVE_WORKING_TZSET */
633 void inittimezone(PyObject *m) {
634 /* This code moved from inittime wholesale to allow calling it from
635 time_tzset. In the future, some parts of it can be moved back
636 (for platforms that don't HAVE_WORKING_TZSET, when we know what they
637 are), and the extranious calls to tzset(3) should be removed.
638 I havn't done this yet, as I don't want to change this code as
639 little as possible when introducing the time.tzset and time.tzsetwall
640 methods. This should simply be a method of doing the following once,
641 at the top of this function and removing the call to tzset() from
642 time_tzset():
644 #ifdef HAVE_TZSET
645 tzset()
646 #endif
648 And I'm lazy and hate C so nyer.
650 #if defined(HAVE_TZNAME) && !defined(__GLIBC__) && !defined(__CYGWIN__)
651 tzset();
652 #ifdef PYOS_OS2
653 PyModule_AddIntConstant(m, "timezone", _timezone);
654 #else /* !PYOS_OS2 */
655 PyModule_AddIntConstant(m, "timezone", timezone);
656 #endif /* PYOS_OS2 */
657 #ifdef HAVE_ALTZONE
658 PyModule_AddIntConstant(m, "altzone", altzone);
659 #else
660 #ifdef PYOS_OS2
661 PyModule_AddIntConstant(m, "altzone", _timezone-3600);
662 #else /* !PYOS_OS2 */
663 PyModule_AddIntConstant(m, "altzone", timezone-3600);
664 #endif /* PYOS_OS2 */
665 #endif
666 PyModule_AddIntConstant(m, "daylight", daylight);
667 PyModule_AddObject(m, "tzname",
668 Py_BuildValue("(zz)", tzname[0], tzname[1]));
669 #else /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/
670 #ifdef HAVE_STRUCT_TM_TM_ZONE
672 #define YEAR ((time_t)((365 * 24 + 6) * 3600))
673 time_t t;
674 struct tm *p;
675 long janzone, julyzone;
676 char janname[10], julyname[10];
677 t = (time((time_t *)0) / YEAR) * YEAR;
678 p = localtime(&t);
679 janzone = -p->tm_gmtoff;
680 strncpy(janname, p->tm_zone ? p->tm_zone : " ", 9);
681 janname[9] = '\0';
682 t += YEAR/2;
683 p = localtime(&t);
684 julyzone = -p->tm_gmtoff;
685 strncpy(julyname, p->tm_zone ? p->tm_zone : " ", 9);
686 julyname[9] = '\0';
688 if( janzone < julyzone ) {
689 /* DST is reversed in the southern hemisphere */
690 PyModule_AddIntConstant(m, "timezone", julyzone);
691 PyModule_AddIntConstant(m, "altzone", janzone);
692 PyModule_AddIntConstant(m, "daylight",
693 janzone != julyzone);
694 PyModule_AddObject(m, "tzname",
695 Py_BuildValue("(zz)",
696 julyname, janname));
697 } else {
698 PyModule_AddIntConstant(m, "timezone", janzone);
699 PyModule_AddIntConstant(m, "altzone", julyzone);
700 PyModule_AddIntConstant(m, "daylight",
701 janzone != julyzone);
702 PyModule_AddObject(m, "tzname",
703 Py_BuildValue("(zz)",
704 janname, julyname));
707 #else
708 #endif /* HAVE_STRUCT_TM_TM_ZONE */
709 #ifdef __CYGWIN__
710 tzset();
711 PyModule_AddIntConstant(m, "timezone", _timezone);
712 PyModule_AddIntConstant(m, "altzone", _timezone-3600);
713 PyModule_AddIntConstant(m, "daylight", _daylight);
714 PyModule_AddObject(m, "tzname",
715 Py_BuildValue("(zz)", _tzname[0], _tzname[1]));
716 #endif /* __CYGWIN__ */
717 #endif /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/
721 static PyMethodDef time_methods[] = {
722 {"time", time_time, METH_NOARGS, time_doc},
723 #ifdef HAVE_CLOCK
724 {"clock", time_clock, METH_NOARGS, clock_doc},
725 #endif
726 {"sleep", time_sleep, METH_VARARGS, sleep_doc},
727 {"gmtime", time_gmtime, METH_VARARGS, gmtime_doc},
728 {"localtime", time_localtime, METH_VARARGS, localtime_doc},
729 {"asctime", time_asctime, METH_VARARGS, asctime_doc},
730 {"ctime", time_ctime, METH_VARARGS, ctime_doc},
731 #ifdef HAVE_MKTIME
732 {"mktime", time_mktime, METH_O, mktime_doc},
733 #endif
734 #ifdef HAVE_STRFTIME
735 {"strftime", time_strftime, METH_VARARGS, strftime_doc},
736 #endif
737 {"strptime", time_strptime, METH_VARARGS, strptime_doc},
738 #ifdef HAVE_WORKING_TZSET
739 {"tzset", time_tzset, METH_NOARGS, tzset_doc},
740 #endif
741 {NULL, NULL} /* sentinel */
745 PyDoc_STRVAR(module_doc,
746 "This module provides various functions to manipulate time values.\n\
748 There are two standard representations of time. One is the number\n\
749 of seconds since the Epoch, in UTC (a.k.a. GMT). It may be an integer\n\
750 or a floating point number (to represent fractions of seconds).\n\
751 The Epoch is system-defined; on Unix, it is generally January 1st, 1970.\n\
752 The actual value can be retrieved by calling gmtime(0).\n\
754 The other representation is a tuple of 9 integers giving local time.\n\
755 The tuple items are:\n\
756 year (four digits, e.g. 1998)\n\
757 month (1-12)\n\
758 day (1-31)\n\
759 hours (0-23)\n\
760 minutes (0-59)\n\
761 seconds (0-59)\n\
762 weekday (0-6, Monday is 0)\n\
763 Julian day (day in the year, 1-366)\n\
764 DST (Daylight Savings Time) flag (-1, 0 or 1)\n\
765 If the DST flag is 0, the time is given in the regular time zone;\n\
766 if it is 1, the time is given in the DST time zone;\n\
767 if it is -1, mktime() should guess based on the date and time.\n\
769 Variables:\n\
771 timezone -- difference in seconds between UTC and local standard time\n\
772 altzone -- difference in seconds between UTC and local DST time\n\
773 daylight -- whether local time should reflect DST\n\
774 tzname -- tuple of (standard time zone name, DST time zone name)\n\
776 Functions:\n\
778 time() -- return current time in seconds since the Epoch as a float\n\
779 clock() -- return CPU time since process start as a float\n\
780 sleep() -- delay for a number of seconds given as a float\n\
781 gmtime() -- convert seconds since Epoch to UTC tuple\n\
782 localtime() -- convert seconds since Epoch to local time tuple\n\
783 asctime() -- convert time tuple to string\n\
784 ctime() -- convert time in seconds to string\n\
785 mktime() -- convert local time tuple to seconds since Epoch\n\
786 strftime() -- convert time tuple to string according to format specification\n\
787 strptime() -- parse string to time tuple according to format specification\n\
788 tzset() -- change the local timezone");
791 PyMODINIT_FUNC
792 inittime(void)
794 PyObject *m;
795 char *p;
796 m = Py_InitModule3("time", time_methods, module_doc);
797 if (m == NULL)
798 return;
800 /* Accept 2-digit dates unless PYTHONY2K is set and non-empty */
801 p = Py_GETENV("PYTHONY2K");
802 PyModule_AddIntConstant(m, "accept2dyear", (long) (!p || !*p));
803 /* Squirrel away the module's dictionary for the y2k check */
804 moddict = PyModule_GetDict(m);
805 Py_INCREF(moddict);
807 /* Set, or reset, module variables like time.timezone */
808 inittimezone(m);
810 #ifdef MS_WINDOWS
811 /* Helper to allow interrupts for Windows.
812 If Ctrl+C event delivered while not sleeping
813 it will be ignored.
815 main_thread = PyThread_get_thread_ident();
816 hInterruptEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
817 SetConsoleCtrlHandler( PyCtrlHandler, TRUE);
818 #endif /* MS_WINDOWS */
819 if (!initialized) {
820 PyStructSequence_InitType(&StructTimeType,
821 &struct_time_type_desc);
823 Py_INCREF(&StructTimeType);
824 PyModule_AddObject(m, "struct_time", (PyObject*) &StructTimeType);
825 initialized = 1;
829 /* Implement floattime() for various platforms */
831 static double
832 floattime(void)
834 /* There are three ways to get the time:
835 (1) gettimeofday() -- resolution in microseconds
836 (2) ftime() -- resolution in milliseconds
837 (3) time() -- resolution in seconds
838 In all cases the return value is a float in seconds.
839 Since on some systems (e.g. SCO ODT 3.0) gettimeofday() may
840 fail, so we fall back on ftime() or time().
841 Note: clock resolution does not imply clock accuracy! */
842 #ifdef HAVE_GETTIMEOFDAY
844 struct timeval t;
845 #ifdef GETTIMEOFDAY_NO_TZ
846 if (gettimeofday(&t) == 0)
847 return (double)t.tv_sec + t.tv_usec*0.000001;
848 #else /* !GETTIMEOFDAY_NO_TZ */
849 if (gettimeofday(&t, (struct timezone *)NULL) == 0)
850 return (double)t.tv_sec + t.tv_usec*0.000001;
851 #endif /* !GETTIMEOFDAY_NO_TZ */
854 #endif /* !HAVE_GETTIMEOFDAY */
856 #if defined(HAVE_FTIME)
857 struct timeb t;
858 ftime(&t);
859 return (double)t.time + (double)t.millitm * (double)0.001;
860 #else /* !HAVE_FTIME */
861 time_t secs;
862 time(&secs);
863 return (double)secs;
864 #endif /* !HAVE_FTIME */
869 /* Implement floatsleep() for various platforms.
870 When interrupted (or when another error occurs), return -1 and
871 set an exception; else return 0. */
873 static int
874 floatsleep(double secs)
876 /* XXX Should test for MS_WINDOWS first! */
877 #if defined(HAVE_SELECT) && !defined(__BEOS__) && !defined(__EMX__)
878 struct timeval t;
879 double frac;
880 frac = fmod(secs, 1.0);
881 secs = floor(secs);
882 t.tv_sec = (long)secs;
883 t.tv_usec = (long)(frac*1000000.0);
884 Py_BEGIN_ALLOW_THREADS
885 if (select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &t) != 0) {
886 #ifdef EINTR
887 if (errno != EINTR) {
888 #else
889 if (1) {
890 #endif
891 Py_BLOCK_THREADS
892 PyErr_SetFromErrno(PyExc_IOError);
893 return -1;
896 Py_END_ALLOW_THREADS
897 #elif defined(__WATCOMC__) && !defined(__QNX__)
898 /* XXX Can't interrupt this sleep */
899 Py_BEGIN_ALLOW_THREADS
900 delay((int)(secs * 1000 + 0.5)); /* delay() uses milliseconds */
901 Py_END_ALLOW_THREADS
902 #elif defined(MS_WINDOWS)
904 double millisecs = secs * 1000.0;
905 unsigned long ul_millis;
907 if (millisecs > (double)ULONG_MAX) {
908 PyErr_SetString(PyExc_OverflowError,
909 "sleep length is too large");
910 return -1;
912 Py_BEGIN_ALLOW_THREADS
913 /* Allow sleep(0) to maintain win32 semantics, and as decreed
914 * by Guido, only the main thread can be interrupted.
916 ul_millis = (unsigned long)millisecs;
917 if (ul_millis == 0 ||
918 main_thread != PyThread_get_thread_ident())
919 Sleep(ul_millis);
920 else {
921 DWORD rc;
922 ResetEvent(hInterruptEvent);
923 rc = WaitForSingleObject(hInterruptEvent, ul_millis);
924 if (rc == WAIT_OBJECT_0) {
925 /* Yield to make sure real Python signal
926 * handler called.
928 Sleep(1);
929 Py_BLOCK_THREADS
930 errno = EINTR;
931 PyErr_SetFromErrno(PyExc_IOError);
932 return -1;
935 Py_END_ALLOW_THREADS
937 #elif defined(PYOS_OS2)
938 /* This Sleep *IS* Interruptable by Exceptions */
939 Py_BEGIN_ALLOW_THREADS
940 if (DosSleep(secs * 1000) != NO_ERROR) {
941 Py_BLOCK_THREADS
942 PyErr_SetFromErrno(PyExc_IOError);
943 return -1;
945 Py_END_ALLOW_THREADS
946 #elif defined(__BEOS__)
947 /* This sleep *CAN BE* interrupted. */
949 if( secs <= 0.0 ) {
950 return;
953 Py_BEGIN_ALLOW_THREADS
954 /* BeOS snooze() is in microseconds... */
955 if( snooze( (bigtime_t)( secs * 1000.0 * 1000.0 ) ) == B_INTERRUPTED ) {
956 Py_BLOCK_THREADS
957 PyErr_SetFromErrno( PyExc_IOError );
958 return -1;
960 Py_END_ALLOW_THREADS
962 #elif defined(RISCOS)
963 if (secs <= 0.0)
964 return 0;
965 Py_BEGIN_ALLOW_THREADS
966 /* This sleep *CAN BE* interrupted. */
967 if ( riscos_sleep(secs) )
968 return -1;
969 Py_END_ALLOW_THREADS
970 #elif defined(PLAN9)
972 double millisecs = secs * 1000.0;
973 if (millisecs > (double)LONG_MAX) {
974 PyErr_SetString(PyExc_OverflowError, "sleep length is too large");
975 return -1;
977 /* This sleep *CAN BE* interrupted. */
978 Py_BEGIN_ALLOW_THREADS
979 if(sleep((long)millisecs) < 0){
980 Py_BLOCK_THREADS
981 PyErr_SetFromErrno(PyExc_IOError);
982 return -1;
984 Py_END_ALLOW_THREADS
986 #else
987 /* XXX Can't interrupt this sleep */
988 Py_BEGIN_ALLOW_THREADS
989 sleep((int)secs);
990 Py_END_ALLOW_THREADS
991 #endif
993 return 0;