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