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