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