Whitespace normalization.
[python/dscho.git] / Modules / timemodule.c
blobf8557968f55feb6e4f361cb3671af8a90729aa92
2 /* Time module */
4 #include "Python.h"
5 #include "structseq.h"
6 #include "timefuncs.h"
8 #include <ctype.h>
10 #include <sys/types.h>
12 #ifdef QUICKWIN
13 #include <io.h>
14 #endif
16 #ifdef HAVE_FTIME
17 #include <sys/timeb.h>
18 #if !defined(MS_WINDOWS) && !defined(PYOS_OS2)
19 extern int ftime(struct timeb *);
20 #endif /* MS_WINDOWS */
21 #endif /* HAVE_FTIME */
23 #if defined(__WATCOMC__) && !defined(__QNX__)
24 #include <i86.h>
25 #else
26 #ifdef MS_WINDOWS
27 #define WIN32_LEAN_AND_MEAN
28 #include <windows.h>
29 #include "pythread.h"
31 /* helper to allow us to interrupt sleep() on Windows*/
32 static HANDLE hInterruptEvent = NULL;
33 static BOOL WINAPI PyCtrlHandler(DWORD dwCtrlType)
35 SetEvent(hInterruptEvent);
36 /* allow other default handlers to be called.
37 Default Python handler will setup the
38 KeyboardInterrupt exception.
40 return FALSE;
42 static long main_thread;
45 #if defined(__BORLANDC__)
46 /* These overrides not needed for Win32 */
47 #define timezone _timezone
48 #define tzname _tzname
49 #define daylight _daylight
50 #endif /* __BORLANDC__ */
51 #endif /* MS_WINDOWS */
52 #endif /* !__WATCOMC__ || __QNX__ */
54 #if defined(MS_WINDOWS) && !defined(MS_WIN64) && !defined(__BORLANDC__)
55 /* Win32 has better clock replacement
56 XXX Win64 does not yet, but might when the platform matures. */
57 #undef HAVE_CLOCK /* We have our own version down below */
58 #endif /* MS_WINDOWS && !MS_WIN64 */
60 #if defined(PYOS_OS2)
61 #define INCL_DOS
62 #define INCL_ERRORS
63 #include <os2.h>
64 #endif
66 #if defined(PYCC_VACPP)
67 #include <sys/time.h>
68 #endif
70 #ifdef __BEOS__
71 #include <time.h>
72 /* For bigtime_t, snooze(). - [cjh] */
73 #include <support/SupportDefs.h>
74 #include <kernel/OS.h>
75 #endif
77 #ifdef RISCOS
78 extern int riscos_sleep(double);
79 #endif
81 /* Forward declarations */
82 static int floatsleep(double);
83 static double floattime(void);
85 /* For Y2K check */
86 static PyObject *moddict;
88 /* Exposed in timefuncs.h. */
89 time_t
90 _PyTime_DoubleToTimet(double x)
92 time_t result;
93 double diff;
95 result = (time_t)x;
96 /* How much info did we lose? time_t may be an integral or
97 * floating type, and we don't know which. If it's integral,
98 * we don't know whether C truncates, rounds, returns the floor,
99 * etc. If we lost a second or more, the C rounding is
100 * unreasonable, or the input just doesn't fit in a time_t;
101 * call it an error regardless. Note that the original cast to
102 * time_t can cause a C error too, but nothing we can do to
103 * worm around that.
105 diff = x - (double)result;
106 if (diff <= -1.0 || diff >= 1.0) {
107 PyErr_SetString(PyExc_ValueError,
108 "timestamp out of range for platform time_t");
109 result = (time_t)-1;
111 return result;
114 static PyObject *
115 time_time(PyObject *self, PyObject *args)
117 double secs;
118 if (!PyArg_ParseTuple(args, ":time"))
119 return NULL;
120 secs = floattime();
121 if (secs == 0.0) {
122 PyErr_SetFromErrno(PyExc_IOError);
123 return NULL;
125 return PyFloat_FromDouble(secs);
128 PyDoc_STRVAR(time_doc,
129 "time() -> floating point number\n\
131 Return the current time in seconds since the Epoch.\n\
132 Fractions of a second may be present if the system clock provides them.");
134 #ifdef HAVE_CLOCK
136 #ifndef CLOCKS_PER_SEC
137 #ifdef CLK_TCK
138 #define CLOCKS_PER_SEC CLK_TCK
139 #else
140 #define CLOCKS_PER_SEC 1000000
141 #endif
142 #endif
144 static PyObject *
145 time_clock(PyObject *self, PyObject *args)
147 if (!PyArg_ParseTuple(args, ":clock"))
148 return NULL;
149 return PyFloat_FromDouble(((double)clock()) / CLOCKS_PER_SEC);
151 #endif /* HAVE_CLOCK */
153 #if defined(MS_WINDOWS) && !defined(MS_WIN64) && !defined(__BORLANDC__)
154 /* Due to Mark Hammond and Tim Peters */
155 static PyObject *
156 time_clock(PyObject *self, PyObject *args)
158 static LARGE_INTEGER ctrStart;
159 static double divisor = 0.0;
160 LARGE_INTEGER now;
161 double diff;
163 if (!PyArg_ParseTuple(args, ":clock"))
164 return NULL;
166 if (divisor == 0.0) {
167 LARGE_INTEGER freq;
168 QueryPerformanceCounter(&ctrStart);
169 if (!QueryPerformanceFrequency(&freq) || freq.QuadPart == 0) {
170 /* Unlikely to happen - this works on all intel
171 machines at least! Revert to clock() */
172 return PyFloat_FromDouble(clock());
174 divisor = (double)freq.QuadPart;
176 QueryPerformanceCounter(&now);
177 diff = (double)(now.QuadPart - ctrStart.QuadPart);
178 return PyFloat_FromDouble(diff / divisor);
181 #define HAVE_CLOCK /* So it gets included in the methods */
182 #endif /* MS_WINDOWS && !MS_WIN64 */
184 #ifdef HAVE_CLOCK
185 PyDoc_STRVAR(clock_doc,
186 "clock() -> floating point number\n\
188 Return the CPU time or real time since the start of the process or since\n\
189 the first call to clock(). This has as much precision as the system\n\
190 records.");
191 #endif
193 static PyObject *
194 time_sleep(PyObject *self, PyObject *args)
196 double secs;
197 if (!PyArg_ParseTuple(args, "d:sleep", &secs))
198 return NULL;
199 if (floatsleep(secs) != 0)
200 return NULL;
201 Py_INCREF(Py_None);
202 return Py_None;
205 PyDoc_STRVAR(sleep_doc,
206 "sleep(seconds)\n\
208 Delay execution for a given number of seconds. The argument may be\n\
209 a floating point number for subsecond precision.");
211 static PyStructSequence_Field struct_time_type_fields[] = {
212 {"tm_year", NULL},
213 {"tm_mon", NULL},
214 {"tm_mday", NULL},
215 {"tm_hour", NULL},
216 {"tm_min", NULL},
217 {"tm_sec", NULL},
218 {"tm_wday", NULL},
219 {"tm_yday", NULL},
220 {"tm_isdst", NULL},
224 static PyStructSequence_Desc struct_time_type_desc = {
225 "time.struct_time",
226 NULL,
227 struct_time_type_fields,
231 static PyTypeObject StructTimeType;
233 static PyObject *
234 tmtotuple(struct tm *p)
236 PyObject *v = PyStructSequence_New(&StructTimeType);
237 if (v == NULL)
238 return NULL;
240 #define SET(i,val) PyStructSequence_SET_ITEM(v, i, PyInt_FromLong((long) val))
242 SET(0, p->tm_year + 1900);
243 SET(1, p->tm_mon + 1); /* Want January == 1 */
244 SET(2, p->tm_mday);
245 SET(3, p->tm_hour);
246 SET(4, p->tm_min);
247 SET(5, p->tm_sec);
248 SET(6, (p->tm_wday + 6) % 7); /* Want Monday == 0 */
249 SET(7, p->tm_yday + 1); /* Want January, 1 == 1 */
250 SET(8, p->tm_isdst);
251 #undef SET
252 if (PyErr_Occurred()) {
253 Py_XDECREF(v);
254 return NULL;
257 return v;
260 static PyObject *
261 time_convert(double when, struct tm * (*function)(const time_t *))
263 struct tm *p;
264 time_t whent = _PyTime_DoubleToTimet(when);
266 if (whent == (time_t)-1 && PyErr_Occurred())
267 return NULL;
268 errno = 0;
269 p = function(&whent);
270 if (p == NULL) {
271 #ifdef EINVAL
272 if (errno == 0)
273 errno = EINVAL;
274 #endif
275 return PyErr_SetFromErrno(PyExc_ValueError);
277 return tmtotuple(p);
280 static PyObject *
281 time_gmtime(PyObject *self, PyObject *args)
283 double when;
284 if (PyTuple_Size(args) == 0)
285 when = floattime();
286 if (!PyArg_ParseTuple(args, "|d:gmtime", &when))
287 return NULL;
288 return time_convert(when, gmtime);
291 PyDoc_STRVAR(gmtime_doc,
292 "gmtime([seconds]) -> (tm_year, tm_mon, tm_day, tm_hour, tm_min,\n\
293 tm_sec, tm_wday, tm_yday, tm_isdst)\n\
295 Convert seconds since the Epoch to a time tuple expressing UTC (a.k.a.\n\
296 GMT). When 'seconds' is not passed in, convert the current time instead.");
298 static PyObject *
299 time_localtime(PyObject *self, PyObject *args)
301 double when;
302 if (PyTuple_Size(args) == 0)
303 when = floattime();
304 if (!PyArg_ParseTuple(args, "|d:localtime", &when))
305 return NULL;
306 return time_convert(when, localtime);
309 PyDoc_STRVAR(localtime_doc,
310 "localtime([seconds]) -> (tm_year,tm_mon,tm_day,tm_hour,tm_min,tm_sec,tm_wday,tm_yday,tm_isdst)\n\
312 Convert seconds since the Epoch to a time tuple expressing local time.\n\
313 When 'seconds' is not passed in, convert the current time instead.");
315 static int
316 gettmarg(PyObject *args, struct tm *p)
318 int y;
319 memset((void *) p, '\0', sizeof(struct tm));
321 if (!PyArg_Parse(args, "(iiiiiiiii)",
323 &p->tm_mon,
324 &p->tm_mday,
325 &p->tm_hour,
326 &p->tm_min,
327 &p->tm_sec,
328 &p->tm_wday,
329 &p->tm_yday,
330 &p->tm_isdst))
331 return 0;
332 if (y < 1900) {
333 PyObject *accept = PyDict_GetItemString(moddict,
334 "accept2dyear");
335 if (accept == NULL || !PyInt_Check(accept) ||
336 PyInt_AsLong(accept) == 0) {
337 PyErr_SetString(PyExc_ValueError,
338 "year >= 1900 required");
339 return 0;
341 if (69 <= y && y <= 99)
342 y += 1900;
343 else if (0 <= y && y <= 68)
344 y += 2000;
345 else {
346 PyErr_SetString(PyExc_ValueError,
347 "year out of range");
348 return 0;
351 p->tm_year = y - 1900;
352 p->tm_mon--;
353 p->tm_wday = (p->tm_wday + 1) % 7;
354 p->tm_yday--;
355 return 1;
358 #ifdef HAVE_STRFTIME
359 static PyObject *
360 time_strftime(PyObject *self, PyObject *args)
362 PyObject *tup = NULL;
363 struct tm buf;
364 const char *fmt;
365 size_t fmtlen, buflen;
366 char *outbuf = 0;
367 size_t i;
369 memset((void *) &buf, '\0', sizeof(buf));
371 if (!PyArg_ParseTuple(args, "s|O:strftime", &fmt, &tup))
372 return NULL;
374 if (tup == NULL) {
375 time_t tt = time(NULL);
376 buf = *localtime(&tt);
377 } else if (!gettmarg(tup, &buf))
378 return NULL;
380 /* Checks added to make sure strftime() does not crash Python by
381 indexing blindly into some array for a textual representation
382 by some bad index (fixes bug #897625).
384 No check for year since handled in gettmarg().
386 if (buf.tm_mon < 0 || buf.tm_mon > 11) {
387 PyErr_SetString(PyExc_ValueError, "month out of range");
388 return NULL;
390 if (buf.tm_mday < 1 || buf.tm_mday > 31) {
391 PyErr_SetString(PyExc_ValueError, "day of month out of range");
392 return NULL;
394 if (buf.tm_hour < 0 || buf.tm_hour > 23) {
395 PyErr_SetString(PyExc_ValueError, "hour out of range");
396 return NULL;
398 if (buf.tm_min < 0 || buf.tm_min > 59) {
399 PyErr_SetString(PyExc_ValueError, "minute out of range");
400 return NULL;
402 if (buf.tm_sec < 0 || buf.tm_sec > 61) {
403 PyErr_SetString(PyExc_ValueError, "seconds out of range");
404 return NULL;
406 /* tm_wday does not need checking of its upper-bound since taking
407 ``% 7`` in gettmarg() automatically restricts the range. */
408 if (buf.tm_wday < 0) {
409 PyErr_SetString(PyExc_ValueError, "day of week out of range");
410 return NULL;
412 if (buf.tm_yday < 0 || buf.tm_yday > 365) {
413 PyErr_SetString(PyExc_ValueError, "day of year out of range");
414 return NULL;
416 if (buf.tm_isdst < -1 || buf.tm_isdst > 1) {
417 PyErr_SetString(PyExc_ValueError,
418 "daylight savings flag out of range");
419 return NULL;
422 fmtlen = strlen(fmt);
424 /* I hate these functions that presume you know how big the output
425 * will be ahead of time...
427 for (i = 1024; ; i += i) {
428 outbuf = malloc(i);
429 if (outbuf == NULL) {
430 return PyErr_NoMemory();
432 buflen = strftime(outbuf, i, fmt, &buf);
433 if (buflen > 0 || i >= 256 * fmtlen) {
434 /* If the buffer is 256 times as long as the format,
435 it's probably not failing for lack of room!
436 More likely, the format yields an empty result,
437 e.g. an empty format, or %Z when the timezone
438 is unknown. */
439 PyObject *ret;
440 ret = PyString_FromStringAndSize(outbuf, buflen);
441 free(outbuf);
442 return ret;
444 free(outbuf);
448 PyDoc_STRVAR(strftime_doc,
449 "strftime(format[, tuple]) -> string\n\
451 Convert a time tuple to a string according to a format specification.\n\
452 See the library reference manual for formatting codes. When the time tuple\n\
453 is not present, current time as returned by localtime() is used.");
454 #endif /* HAVE_STRFTIME */
456 static PyObject *
457 time_strptime(PyObject *self, PyObject *args)
459 PyObject *strptime_module = PyImport_ImportModule("_strptime");
460 PyObject *strptime_result;
462 if (!strptime_module)
463 return NULL;
464 strptime_result = PyObject_CallMethod(strptime_module, "strptime", "O", args);
465 Py_DECREF(strptime_module);
466 return strptime_result;
469 PyDoc_STRVAR(strptime_doc,
470 "strptime(string, format) -> struct_time\n\
472 Parse a string to a time tuple according to a format specification.\n\
473 See the library reference manual for formatting codes (same as strftime()).");
476 static PyObject *
477 time_asctime(PyObject *self, PyObject *args)
479 PyObject *tup = NULL;
480 struct tm buf;
481 char *p;
482 if (!PyArg_ParseTuple(args, "|O:asctime", &tup))
483 return NULL;
484 if (tup == NULL) {
485 time_t tt = time(NULL);
486 buf = *localtime(&tt);
487 } else if (!gettmarg(tup, &buf))
488 return NULL;
489 p = asctime(&buf);
490 if (p[24] == '\n')
491 p[24] = '\0';
492 return PyString_FromString(p);
495 PyDoc_STRVAR(asctime_doc,
496 "asctime([tuple]) -> string\n\
498 Convert a time tuple to a string, e.g. 'Sat Jun 06 16:26:11 1998'.\n\
499 When the time tuple is not present, current time as returned by localtime()\n\
500 is used.");
502 static PyObject *
503 time_ctime(PyObject *self, PyObject *args)
505 double dt;
506 time_t tt;
507 char *p;
509 if (PyTuple_Size(args) == 0)
510 tt = time(NULL);
511 else {
512 if (!PyArg_ParseTuple(args, "|d:ctime", &dt))
513 return NULL;
514 tt = _PyTime_DoubleToTimet(dt);
515 if (tt == (time_t)-1 && PyErr_Occurred())
516 return NULL;
518 p = ctime(&tt);
519 if (p == NULL) {
520 PyErr_SetString(PyExc_ValueError, "unconvertible time");
521 return NULL;
523 if (p[24] == '\n')
524 p[24] = '\0';
525 return PyString_FromString(p);
528 PyDoc_STRVAR(ctime_doc,
529 "ctime(seconds) -> string\n\
531 Convert a time in seconds since the Epoch to a string in local time.\n\
532 This is equivalent to asctime(localtime(seconds)). When the time tuple is\n\
533 not present, current time as returned by localtime() is used.");
535 #ifdef HAVE_MKTIME
536 static PyObject *
537 time_mktime(PyObject *self, PyObject *args)
539 PyObject *tup;
540 struct tm buf;
541 time_t tt;
542 if (!PyArg_ParseTuple(args, "O:mktime", &tup))
543 return NULL;
544 tt = time(&tt);
545 buf = *localtime(&tt);
546 if (!gettmarg(tup, &buf))
547 return NULL;
548 tt = mktime(&buf);
549 if (tt == (time_t)(-1)) {
550 PyErr_SetString(PyExc_OverflowError,
551 "mktime argument out of range");
552 return NULL;
554 return PyFloat_FromDouble((double)tt);
557 PyDoc_STRVAR(mktime_doc,
558 "mktime(tuple) -> floating point number\n\
560 Convert a time tuple in local time to seconds since the Epoch.");
561 #endif /* HAVE_MKTIME */
563 #ifdef HAVE_WORKING_TZSET
564 void inittimezone(PyObject *module);
566 static PyObject *
567 time_tzset(PyObject *self, PyObject *args)
569 PyObject* m;
571 if (!PyArg_ParseTuple(args, ":tzset"))
572 return NULL;
574 m = PyImport_ImportModule("time");
575 if (m == NULL) {
576 return NULL;
579 tzset();
581 /* Reset timezone, altzone, daylight and tzname */
582 inittimezone(m);
583 Py_DECREF(m);
585 Py_INCREF(Py_None);
586 return Py_None;
589 PyDoc_STRVAR(tzset_doc,
590 "tzset(zone)\n\
592 Initialize, or reinitialize, the local timezone to the value stored in\n\
593 os.environ['TZ']. The TZ environment variable should be specified in\n\
594 standard Uniz timezone format as documented in the tzset man page\n\
595 (eg. 'US/Eastern', 'Europe/Amsterdam'). Unknown timezones will silently\n\
596 fall back to UTC. If the TZ environment variable is not set, the local\n\
597 timezone is set to the systems best guess of wallclock time.\n\
598 Changing the TZ environment variable without calling tzset *may* change\n\
599 the local timezone used by methods such as localtime, but this behaviour\n\
600 should not be relied on.");
601 #endif /* HAVE_WORKING_TZSET */
603 void inittimezone(PyObject *m) {
604 /* This code moved from inittime wholesale to allow calling it from
605 time_tzset. In the future, some parts of it can be moved back
606 (for platforms that don't HAVE_WORKING_TZSET, when we know what they
607 are), and the extranious calls to tzset(3) should be removed.
608 I havn't done this yet, as I don't want to change this code as
609 little as possible when introducing the time.tzset and time.tzsetwall
610 methods. This should simply be a method of doing the following once,
611 at the top of this function and removing the call to tzset() from
612 time_tzset():
614 #ifdef HAVE_TZSET
615 tzset()
616 #endif
618 And I'm lazy and hate C so nyer.
620 #if defined(HAVE_TZNAME) && !defined(__GLIBC__) && !defined(__CYGWIN__)
621 tzset();
622 #ifdef PYOS_OS2
623 PyModule_AddIntConstant(m, "timezone", _timezone);
624 #else /* !PYOS_OS2 */
625 PyModule_AddIntConstant(m, "timezone", timezone);
626 #endif /* PYOS_OS2 */
627 #ifdef HAVE_ALTZONE
628 PyModule_AddIntConstant(m, "altzone", altzone);
629 #else
630 #ifdef PYOS_OS2
631 PyModule_AddIntConstant(m, "altzone", _timezone-3600);
632 #else /* !PYOS_OS2 */
633 PyModule_AddIntConstant(m, "altzone", timezone-3600);
634 #endif /* PYOS_OS2 */
635 #endif
636 PyModule_AddIntConstant(m, "daylight", daylight);
637 PyModule_AddObject(m, "tzname",
638 Py_BuildValue("(zz)", tzname[0], tzname[1]));
639 #else /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/
640 #ifdef HAVE_STRUCT_TM_TM_ZONE
642 #define YEAR ((time_t)((365 * 24 + 6) * 3600))
643 time_t t;
644 struct tm *p;
645 long janzone, julyzone;
646 char janname[10], julyname[10];
647 t = (time((time_t *)0) / YEAR) * YEAR;
648 p = localtime(&t);
649 janzone = -p->tm_gmtoff;
650 strncpy(janname, p->tm_zone ? p->tm_zone : " ", 9);
651 janname[9] = '\0';
652 t += YEAR/2;
653 p = localtime(&t);
654 julyzone = -p->tm_gmtoff;
655 strncpy(julyname, p->tm_zone ? p->tm_zone : " ", 9);
656 julyname[9] = '\0';
658 if( janzone < julyzone ) {
659 /* DST is reversed in the southern hemisphere */
660 PyModule_AddIntConstant(m, "timezone", julyzone);
661 PyModule_AddIntConstant(m, "altzone", janzone);
662 PyModule_AddIntConstant(m, "daylight",
663 janzone != julyzone);
664 PyModule_AddObject(m, "tzname",
665 Py_BuildValue("(zz)",
666 julyname, janname));
667 } else {
668 PyModule_AddIntConstant(m, "timezone", janzone);
669 PyModule_AddIntConstant(m, "altzone", julyzone);
670 PyModule_AddIntConstant(m, "daylight",
671 janzone != julyzone);
672 PyModule_AddObject(m, "tzname",
673 Py_BuildValue("(zz)",
674 janname, julyname));
677 #else
678 #endif /* HAVE_STRUCT_TM_TM_ZONE */
679 #ifdef __CYGWIN__
680 tzset();
681 PyModule_AddIntConstant(m, "timezone", _timezone);
682 PyModule_AddIntConstant(m, "altzone", _timezone);
683 PyModule_AddIntConstant(m, "daylight", _daylight);
684 PyModule_AddObject(m, "tzname",
685 Py_BuildValue("(zz)", _tzname[0], _tzname[1]));
686 #endif /* __CYGWIN__ */
687 #endif /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/
691 static PyMethodDef time_methods[] = {
692 {"time", time_time, METH_VARARGS, time_doc},
693 #ifdef HAVE_CLOCK
694 {"clock", time_clock, METH_VARARGS, clock_doc},
695 #endif
696 {"sleep", time_sleep, METH_VARARGS, sleep_doc},
697 {"gmtime", time_gmtime, METH_VARARGS, gmtime_doc},
698 {"localtime", time_localtime, METH_VARARGS, localtime_doc},
699 {"asctime", time_asctime, METH_VARARGS, asctime_doc},
700 {"ctime", time_ctime, METH_VARARGS, ctime_doc},
701 #ifdef HAVE_MKTIME
702 {"mktime", time_mktime, METH_VARARGS, mktime_doc},
703 #endif
704 #ifdef HAVE_STRFTIME
705 {"strftime", time_strftime, METH_VARARGS, strftime_doc},
706 #endif
707 {"strptime", time_strptime, METH_VARARGS, strptime_doc},
708 #ifdef HAVE_WORKING_TZSET
709 {"tzset", time_tzset, METH_VARARGS, tzset_doc},
710 #endif
711 {NULL, NULL} /* sentinel */
715 PyDoc_STRVAR(module_doc,
716 "This module provides various functions to manipulate time values.\n\
718 There are two standard representations of time. One is the number\n\
719 of seconds since the Epoch, in UTC (a.k.a. GMT). It may be an integer\n\
720 or a floating point number (to represent fractions of seconds).\n\
721 The Epoch is system-defined; on Unix, it is generally January 1st, 1970.\n\
722 The actual value can be retrieved by calling gmtime(0).\n\
724 The other representation is a tuple of 9 integers giving local time.\n\
725 The tuple items are:\n\
726 year (four digits, e.g. 1998)\n\
727 month (1-12)\n\
728 day (1-31)\n\
729 hours (0-23)\n\
730 minutes (0-59)\n\
731 seconds (0-59)\n\
732 weekday (0-6, Monday is 0)\n\
733 Julian day (day in the year, 1-366)\n\
734 DST (Daylight Savings Time) flag (-1, 0 or 1)\n\
735 If the DST flag is 0, the time is given in the regular time zone;\n\
736 if it is 1, the time is given in the DST time zone;\n\
737 if it is -1, mktime() should guess based on the date and time.\n\
739 Variables:\n\
741 timezone -- difference in seconds between UTC and local standard time\n\
742 altzone -- difference in seconds between UTC and local DST time\n\
743 daylight -- whether local time should reflect DST\n\
744 tzname -- tuple of (standard time zone name, DST time zone name)\n\
746 Functions:\n\
748 time() -- return current time in seconds since the Epoch as a float\n\
749 clock() -- return CPU time since process start as a float\n\
750 sleep() -- delay for a number of seconds given as a float\n\
751 gmtime() -- convert seconds since Epoch to UTC tuple\n\
752 localtime() -- convert seconds since Epoch to local time tuple\n\
753 asctime() -- convert time tuple to string\n\
754 ctime() -- convert time in seconds to string\n\
755 mktime() -- convert local time tuple to seconds since Epoch\n\
756 strftime() -- convert time tuple to string according to format specification\n\
757 strptime() -- parse string to time tuple according to format specification\n\
758 tzset() -- change the local timezone");
761 PyMODINIT_FUNC
762 inittime(void)
764 PyObject *m;
765 char *p;
766 m = Py_InitModule3("time", time_methods, module_doc);
768 /* Accept 2-digit dates unless PYTHONY2K is set and non-empty */
769 p = Py_GETENV("PYTHONY2K");
770 PyModule_AddIntConstant(m, "accept2dyear", (long) (!p || !*p));
771 /* Squirrel away the module's dictionary for the y2k check */
772 moddict = PyModule_GetDict(m);
773 Py_INCREF(moddict);
775 /* Set, or reset, module variables like time.timezone */
776 inittimezone(m);
778 #ifdef MS_WINDOWS
779 /* Helper to allow interrupts for Windows.
780 If Ctrl+C event delivered while not sleeping
781 it will be ignored.
783 main_thread = PyThread_get_thread_ident();
784 hInterruptEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
785 SetConsoleCtrlHandler( PyCtrlHandler, TRUE);
786 #endif /* MS_WINDOWS */
787 PyStructSequence_InitType(&StructTimeType, &struct_time_type_desc);
788 Py_INCREF(&StructTimeType);
789 PyModule_AddObject(m, "struct_time", (PyObject*) &StructTimeType);
793 /* Implement floattime() for various platforms */
795 static double
796 floattime(void)
798 /* There are three ways to get the time:
799 (1) gettimeofday() -- resolution in microseconds
800 (2) ftime() -- resolution in milliseconds
801 (3) time() -- resolution in seconds
802 In all cases the return value is a float in seconds.
803 Since on some systems (e.g. SCO ODT 3.0) gettimeofday() may
804 fail, so we fall back on ftime() or time().
805 Note: clock resolution does not imply clock accuracy! */
806 #ifdef HAVE_GETTIMEOFDAY
808 struct timeval t;
809 #ifdef GETTIMEOFDAY_NO_TZ
810 if (gettimeofday(&t) == 0)
811 return (double)t.tv_sec + t.tv_usec*0.000001;
812 #else /* !GETTIMEOFDAY_NO_TZ */
813 if (gettimeofday(&t, (struct timezone *)NULL) == 0)
814 return (double)t.tv_sec + t.tv_usec*0.000001;
815 #endif /* !GETTIMEOFDAY_NO_TZ */
817 #endif /* !HAVE_GETTIMEOFDAY */
819 #if defined(HAVE_FTIME)
820 struct timeb t;
821 ftime(&t);
822 return (double)t.time + (double)t.millitm * (double)0.001;
823 #else /* !HAVE_FTIME */
824 time_t secs;
825 time(&secs);
826 return (double)secs;
827 #endif /* !HAVE_FTIME */
832 /* Implement floatsleep() for various platforms.
833 When interrupted (or when another error occurs), return -1 and
834 set an exception; else return 0. */
836 static int
837 floatsleep(double secs)
839 /* XXX Should test for MS_WINDOWS first! */
840 #if defined(HAVE_SELECT) && !defined(__BEOS__) && !defined(__EMX__)
841 struct timeval t;
842 double frac;
843 frac = fmod(secs, 1.0);
844 secs = floor(secs);
845 t.tv_sec = (long)secs;
846 t.tv_usec = (long)(frac*1000000.0);
847 Py_BEGIN_ALLOW_THREADS
848 if (select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &t) != 0) {
849 #ifdef EINTR
850 if (errno != EINTR) {
851 #else
852 if (1) {
853 #endif
854 Py_BLOCK_THREADS
855 PyErr_SetFromErrno(PyExc_IOError);
856 return -1;
859 Py_END_ALLOW_THREADS
860 #elif defined(__WATCOMC__) && !defined(__QNX__)
861 /* XXX Can't interrupt this sleep */
862 Py_BEGIN_ALLOW_THREADS
863 delay((int)(secs * 1000 + 0.5)); /* delay() uses milliseconds */
864 Py_END_ALLOW_THREADS
865 #elif defined(MS_WINDOWS)
867 double millisecs = secs * 1000.0;
868 unsigned long ul_millis;
870 if (millisecs > (double)ULONG_MAX) {
871 PyErr_SetString(PyExc_OverflowError,
872 "sleep length is too large");
873 return -1;
875 Py_BEGIN_ALLOW_THREADS
876 /* Allow sleep(0) to maintain win32 semantics, and as decreed
877 * by Guido, only the main thread can be interrupted.
879 ul_millis = (unsigned long)millisecs;
880 if (ul_millis == 0 ||
881 main_thread != PyThread_get_thread_ident())
882 Sleep(ul_millis);
883 else {
884 DWORD rc;
885 ResetEvent(hInterruptEvent);
886 rc = WaitForSingleObject(hInterruptEvent, ul_millis);
887 if (rc == WAIT_OBJECT_0) {
888 /* Yield to make sure real Python signal
889 * handler called.
891 Sleep(1);
892 Py_BLOCK_THREADS
893 errno = EINTR;
894 PyErr_SetFromErrno(PyExc_IOError);
895 return -1;
898 Py_END_ALLOW_THREADS
900 #elif defined(PYOS_OS2)
901 /* This Sleep *IS* Interruptable by Exceptions */
902 Py_BEGIN_ALLOW_THREADS
903 if (DosSleep(secs * 1000) != NO_ERROR) {
904 Py_BLOCK_THREADS
905 PyErr_SetFromErrno(PyExc_IOError);
906 return -1;
908 Py_END_ALLOW_THREADS
909 #elif defined(__BEOS__)
910 /* This sleep *CAN BE* interrupted. */
912 if( secs <= 0.0 ) {
913 return;
916 Py_BEGIN_ALLOW_THREADS
917 /* BeOS snooze() is in microseconds... */
918 if( snooze( (bigtime_t)( secs * 1000.0 * 1000.0 ) ) == B_INTERRUPTED ) {
919 Py_BLOCK_THREADS
920 PyErr_SetFromErrno( PyExc_IOError );
921 return -1;
923 Py_END_ALLOW_THREADS
925 #elif defined(RISCOS)
926 if (secs <= 0.0)
927 return 0;
928 Py_BEGIN_ALLOW_THREADS
929 /* This sleep *CAN BE* interrupted. */
930 if ( riscos_sleep(secs) )
931 return -1;
932 Py_END_ALLOW_THREADS
933 #elif defined(PLAN9)
935 double millisecs = secs * 1000.0;
936 if (millisecs > (double)LONG_MAX) {
937 PyErr_SetString(PyExc_OverflowError, "sleep length is too large");
938 return -1;
940 /* This sleep *CAN BE* interrupted. */
941 Py_BEGIN_ALLOW_THREADS
942 if(sleep((long)millisecs) < 0){
943 Py_BLOCK_THREADS
944 PyErr_SetFromErrno(PyExc_IOError);
945 return -1;
947 Py_END_ALLOW_THREADS
949 #else
950 /* XXX Can't interrupt this sleep */
951 Py_BEGIN_ALLOW_THREADS
952 sleep((int)secs);
953 Py_END_ALLOW_THREADS
954 #endif
956 return 0;