timemodule.c 24.2 KB
Newer Older
1

Guido van Rossum's avatar
Guido van Rossum committed
2 3
/* Time module */

Barry Warsaw's avatar
Barry Warsaw committed
4
#include "Python.h"
5
#include "structseq.h"
Guido van Rossum's avatar
Guido van Rossum committed
6

7 8
#include <ctype.h>

9
#include <sys/types.h>
10

11 12
#ifdef QUICKWIN
#include <io.h>
13 14
#endif

15 16
#ifdef HAVE_FTIME
#include <sys/timeb.h>
17
#if !defined(MS_WINDOWS) && !defined(PYOS_OS2)
18
extern int ftime(struct timeb *);
19 20
#endif /* MS_WINDOWS */
#endif /* HAVE_FTIME */
21

22
#if defined(__WATCOMC__) && !defined(__QNX__)
Guido van Rossum's avatar
Guido van Rossum committed
23 24
#include <i86.h>
#else
25
#ifdef MS_WINDOWS
26
#define WIN32_LEAN_AND_MEAN
27
#include <windows.h>
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
#include "pythread.h"

/* helper to allow us to interrupt sleep() on Windows*/
static HANDLE hInterruptEvent = NULL;
static BOOL WINAPI PyCtrlHandler(DWORD dwCtrlType)
{
	SetEvent(hInterruptEvent);
	/* allow other default handlers to be called.
	   Default Python handler will setup the
	   KeyboardInterrupt exception.
	*/
	return FALSE;
}
static long main_thread;


44
#if defined(__BORLANDC__)
45
/* These overrides not needed for Win32 */
46
#define timezone _timezone
47
#define tzname _tzname
48
#define daylight _daylight
49
#endif /* __BORLANDC__ */
50
#endif /* MS_WINDOWS */
51
#endif /* !__WATCOMC__ || __QNX__ */
52

53
#if defined(MS_WINDOWS) && !defined(MS_WIN64) && !defined(__BORLANDC__)
54 55
/* Win32 has better clock replacement
   XXX Win64 does not yet, but might when the platform matures. */
56
#undef HAVE_CLOCK /* We have our own version down below */
57
#endif /* MS_WINDOWS && !MS_WIN64 */
58

59 60 61 62 63 64
#if defined(PYOS_OS2)
#define INCL_DOS
#define INCL_ERRORS
#include <os2.h>
#endif

65
#if defined(PYCC_VACPP)
66
#include <sys/time.h>
67 68
#endif

69
#ifdef __BEOS__
70
#include <time.h>
71 72 73 74 75
/* For bigtime_t, snooze(). - [cjh] */
#include <support/SupportDefs.h>
#include <kernel/OS.h>
#endif

76 77 78 79
#ifdef RISCOS
extern int riscos_sleep(double);
#endif

80
/* Forward declarations */
81
static int floatsleep(double);
82
static double floattime(void);
Guido van Rossum's avatar
Guido van Rossum committed
83

84 85 86
/* For Y2K check */
static PyObject *moddict;

Barry Warsaw's avatar
Barry Warsaw committed
87
static PyObject *
Peter Schneider-Kamp's avatar
Peter Schneider-Kamp committed
88
time_time(PyObject *self, PyObject *args)
Guido van Rossum's avatar
Guido van Rossum committed
89
{
90
	double secs;
91
	if (!PyArg_ParseTuple(args, ":time"))
92
		return NULL;
93 94
	secs = floattime();
	if (secs == 0.0) {
Barry Warsaw's avatar
Barry Warsaw committed
95
		PyErr_SetFromErrno(PyExc_IOError);
96 97
		return NULL;
	}
Barry Warsaw's avatar
Barry Warsaw committed
98
	return PyFloat_FromDouble(secs);
Guido van Rossum's avatar
Guido van Rossum committed
99 100
}

101
PyDoc_STRVAR(time_doc,
Guido van Rossum's avatar
Guido van Rossum committed
102 103 104
"time() -> floating point number\n\
\n\
Return the current time in seconds since the Epoch.\n\
105
Fractions of a second may be present if the system clock provides them.");
Guido van Rossum's avatar
Guido van Rossum committed
106

107
#ifdef HAVE_CLOCK
Guido van Rossum's avatar
Guido van Rossum committed
108

109
#ifndef CLOCKS_PER_SEC
110 111 112
#ifdef CLK_TCK
#define CLOCKS_PER_SEC CLK_TCK
#else
113 114
#define CLOCKS_PER_SEC 1000000
#endif
115
#endif
Guido van Rossum's avatar
Guido van Rossum committed
116

Barry Warsaw's avatar
Barry Warsaw committed
117
static PyObject *
Peter Schneider-Kamp's avatar
Peter Schneider-Kamp committed
118
time_clock(PyObject *self, PyObject *args)
Guido van Rossum's avatar
Guido van Rossum committed
119
{
120
	if (!PyArg_ParseTuple(args, ":clock"))
Guido van Rossum's avatar
Guido van Rossum committed
121
		return NULL;
Barry Warsaw's avatar
Barry Warsaw committed
122
	return PyFloat_FromDouble(((double)clock()) / CLOCKS_PER_SEC);
Guido van Rossum's avatar
Guido van Rossum committed
123
}
124
#endif /* HAVE_CLOCK */
Guido van Rossum's avatar
Guido van Rossum committed
125

126
#if defined(MS_WINDOWS) && !defined(MS_WIN64) && !defined(__BORLANDC__)
127
/* Due to Mark Hammond and Tim Peters */
128
static PyObject *
Peter Schneider-Kamp's avatar
Peter Schneider-Kamp committed
129
time_clock(PyObject *self, PyObject *args)
130
{
131
	static LARGE_INTEGER ctrStart;
132
	static double divisor = 0.0;
133
	LARGE_INTEGER now;
134
	double diff;
135

136
	if (!PyArg_ParseTuple(args, ":clock"))
137 138
		return NULL;

139
	if (divisor == 0.0) {
140 141 142
		LARGE_INTEGER freq;
		QueryPerformanceCounter(&ctrStart);
		if (!QueryPerformanceFrequency(&freq) || freq.QuadPart == 0) {
143 144
			/* Unlikely to happen - this works on all intel
			   machines at least!  Revert to clock() */
145 146
			return PyFloat_FromDouble(clock());
		}
147
		divisor = (double)freq.QuadPart;
148
	}
149 150
	QueryPerformanceCounter(&now);
	diff = (double)(now.QuadPart - ctrStart.QuadPart);
151
	return PyFloat_FromDouble(diff / divisor);
152
}
Guido van Rossum's avatar
Guido van Rossum committed
153

154
#define HAVE_CLOCK /* So it gets included in the methods */
155
#endif /* MS_WINDOWS && !MS_WIN64 */
156

Guido van Rossum's avatar
Guido van Rossum committed
157
#ifdef HAVE_CLOCK
158
PyDoc_STRVAR(clock_doc,
Guido van Rossum's avatar
Guido van Rossum committed
159 160 161
"clock() -> floating point number\n\
\n\
Return the CPU time or real time since the start of the process or since\n\
162 163
the first call to clock().  This has as much precision as the system\n\
records.");
Guido van Rossum's avatar
Guido van Rossum committed
164 165
#endif

Barry Warsaw's avatar
Barry Warsaw committed
166
static PyObject *
Peter Schneider-Kamp's avatar
Peter Schneider-Kamp committed
167
time_sleep(PyObject *self, PyObject *args)
Guido van Rossum's avatar
Guido van Rossum committed
168
{
169
	double secs;
170
	if (!PyArg_ParseTuple(args, "d:sleep", &secs))
Guido van Rossum's avatar
Guido van Rossum committed
171
		return NULL;
172 173 174
	if (floatsleep(secs) != 0)
		return NULL;
	Py_INCREF(Py_None);
Barry Warsaw's avatar
Barry Warsaw committed
175
	return Py_None;
Guido van Rossum's avatar
Guido van Rossum committed
176 177
}

178
PyDoc_STRVAR(sleep_doc,
Guido van Rossum's avatar
Guido van Rossum committed
179 180 181
"sleep(seconds)\n\
\n\
Delay execution for a given number of seconds.  The argument may be\n\
182
a floating point number for subsecond precision.");
Guido van Rossum's avatar
Guido van Rossum committed
183

184 185 186 187 188 189 190 191 192 193 194 195 196 197
static PyStructSequence_Field struct_time_type_fields[] = {
	{"tm_year", NULL},
	{"tm_mon", NULL},
	{"tm_mday", NULL},
	{"tm_hour", NULL},
	{"tm_min", NULL},
	{"tm_sec", NULL},
	{"tm_wday", NULL},
	{"tm_yday", NULL},
	{"tm_isdst", NULL},
	{0}
};

static PyStructSequence_Desc struct_time_type_desc = {
198
	"time.struct_time",
199 200 201 202
	NULL,
	struct_time_type_fields,
	9,
};
203

204 205
static PyTypeObject StructTimeType;

206
static PyObject *
Peter Schneider-Kamp's avatar
Peter Schneider-Kamp committed
207
tmtotuple(struct tm *p)
208
{
209 210 211
	PyObject *v = PyStructSequence_New(&StructTimeType);
	if (v == NULL)
		return NULL;
212

213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
#define SET(i,val) PyStructSequence_SET_ITEM(v, i, PyInt_FromLong((long) val))

	SET(0, p->tm_year + 1900);
	SET(1, p->tm_mon + 1);	   /* Want January == 1 */
	SET(2, p->tm_mday);
	SET(3, p->tm_hour);
	SET(4, p->tm_min);
	SET(5, p->tm_sec);
	SET(6, (p->tm_wday + 6) % 7); /* Want Monday == 0 */
	SET(7, p->tm_yday + 1);	   /* Want January, 1 == 1 */
	SET(8, p->tm_isdst);
#undef SET
	if (PyErr_Occurred()) {
		Py_XDECREF(v);
		return NULL;
	}

	return v;
231 232
}

Barry Warsaw's avatar
Barry Warsaw committed
233
static PyObject *
Peter Schneider-Kamp's avatar
Peter Schneider-Kamp committed
234
time_convert(time_t when, struct tm * (*function)(const time_t *))
235
{
236 237 238 239 240
	struct tm *p;
	errno = 0;
	p = function(&when);
	if (p == NULL) {
#ifdef EINVAL
241
		if (errno == 0)
242 243
			errno = EINVAL;
#endif
244
		return PyErr_SetFromErrno(PyExc_ValueError);
245
	}
246
	return tmtotuple(p);
247 248
}

Barry Warsaw's avatar
Barry Warsaw committed
249
static PyObject *
Peter Schneider-Kamp's avatar
Peter Schneider-Kamp committed
250
time_gmtime(PyObject *self, PyObject *args)
251 252
{
	double when;
253 254 255
	if (PyTuple_Size(args) == 0)
		when = floattime();
	if (!PyArg_ParseTuple(args, "|d:gmtime", &when))
256 257 258 259
		return NULL;
	return time_convert((time_t)when, gmtime);
}

260
PyDoc_STRVAR(gmtime_doc,
261 262
"gmtime([seconds]) -> (tm_year, tm_mon, tm_day, tm_hour, tm_min,\n\
                       tm_sec, tm_wday, tm_yday, tm_isdst)\n\
Guido van Rossum's avatar
Guido van Rossum committed
263
\n\
264
Convert seconds since the Epoch to a time tuple expressing UTC (a.k.a.\n\
265
GMT).  When 'seconds' is not passed in, convert the current time instead.");
Guido van Rossum's avatar
Guido van Rossum committed
266

Barry Warsaw's avatar
Barry Warsaw committed
267
static PyObject *
Peter Schneider-Kamp's avatar
Peter Schneider-Kamp committed
268
time_localtime(PyObject *self, PyObject *args)
269 270
{
	double when;
271 272 273
	if (PyTuple_Size(args) == 0)
		when = floattime();
	if (!PyArg_ParseTuple(args, "|d:localtime", &when))
274 275 276 277
		return NULL;
	return time_convert((time_t)when, localtime);
}

278
PyDoc_STRVAR(localtime_doc,
279
"localtime([seconds]) -> (tm_year,tm_mon,tm_day,tm_hour,tm_min,tm_sec,tm_wday,tm_yday,tm_isdst)\n\
280
\n\
281
Convert seconds since the Epoch to a time tuple expressing local time.\n\
282
When 'seconds' is not passed in, convert the current time instead.");
Guido van Rossum's avatar
Guido van Rossum committed
283

284
static int
Peter Schneider-Kamp's avatar
Peter Schneider-Kamp committed
285
gettmarg(PyObject *args, struct tm *p)
286
{
287
	int y;
288
	memset((void *) p, '\0', sizeof(struct tm));
289

Barry Warsaw's avatar
Barry Warsaw committed
290
	if (!PyArg_Parse(args, "(iiiiiiiii)",
291
			 &y,
292 293 294 295 296 297 298 299
			 &p->tm_mon,
			 &p->tm_mday,
			 &p->tm_hour,
			 &p->tm_min,
			 &p->tm_sec,
			 &p->tm_wday,
			 &p->tm_yday,
			 &p->tm_isdst))
300
		return 0;
301 302 303 304 305 306 307 308 309 310 311 312 313 314 315
	if (y < 1900) {
		PyObject *accept = PyDict_GetItemString(moddict,
							"accept2dyear");
		if (accept == NULL || !PyInt_Check(accept) ||
		    PyInt_AsLong(accept) == 0) {
			PyErr_SetString(PyExc_ValueError,
					"year >= 1900 required");
			return 0;
		}
		if (69 <= y && y <= 99)
			y += 1900;
		else if (0 <= y && y <= 68)
			y += 2000;
		else {
			PyErr_SetString(PyExc_ValueError,
316
					"year out of range");
317 318 319 320
			return 0;
		}
	}
	p->tm_year = y - 1900;
321 322 323 324 325 326
	p->tm_mon--;
	p->tm_wday = (p->tm_wday + 1) % 7;
	p->tm_yday--;
	return 1;
}

Guido van Rossum's avatar
Guido van Rossum committed
327
#ifdef HAVE_STRFTIME
Barry Warsaw's avatar
Barry Warsaw committed
328
static PyObject *
Peter Schneider-Kamp's avatar
Peter Schneider-Kamp committed
329
time_strftime(PyObject *self, PyObject *args)
Guido van Rossum's avatar
Guido van Rossum committed
330
{
331
	PyObject *tup = NULL;
Guido van Rossum's avatar
Guido van Rossum committed
332 333
	struct tm buf;
	const char *fmt;
334
	size_t fmtlen, buflen;
Guido van Rossum's avatar
Guido van Rossum committed
335
	char *outbuf = 0;
336
	size_t i;
Guido van Rossum's avatar
Guido van Rossum committed
337

338
	memset((void *) &buf, '\0', sizeof(buf));
339

340 341 342 343 344 345 346
	if (!PyArg_ParseTuple(args, "s|O:strftime", &fmt, &tup))
		return NULL;

	if (tup == NULL) {
		time_t tt = time(NULL);
		buf = *localtime(&tt);
	} else if (!gettmarg(tup, &buf))
Guido van Rossum's avatar
Guido van Rossum committed
347
		return NULL;
348

349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390
        /* Checks added to make sure strftime() does not crash Python by
            indexing blindly into some array for a textual representation
            by some bad index (fixes bug #897625).
        
            No check for year since handled in gettmarg().
        */
        if (buf.tm_mon < 0 || buf.tm_mon > 11) {
            PyErr_SetString(PyExc_ValueError, "month out of range");
                        return NULL;
        }
        if (buf.tm_mday < 1 || buf.tm_mday > 31) {
            PyErr_SetString(PyExc_ValueError, "day of month out of range");
                        return NULL;
        }
        if (buf.tm_hour < 0 || buf.tm_hour > 23) {
            PyErr_SetString(PyExc_ValueError, "hour out of range");
            return NULL;
        }
        if (buf.tm_min < 0 || buf.tm_min > 59) {
            PyErr_SetString(PyExc_ValueError, "minute out of range");
            return NULL;
        }
        if (buf.tm_sec < 0 || buf.tm_sec > 61) {
            PyErr_SetString(PyExc_ValueError, "seconds out of range");
            return NULL;
        }
        /* tm_wday does not need checking of its upper-bound since taking
        ``% 7`` in gettmarg() automatically restricts the range. */
        if (buf.tm_wday < 0) {
            PyErr_SetString(PyExc_ValueError, "day of week out of range");
            return NULL;
        }
        if (buf.tm_yday < 0 || buf.tm_yday > 365) {
            PyErr_SetString(PyExc_ValueError, "day of year out of range");
            return NULL;
        }
        if (buf.tm_isdst < -1 || buf.tm_isdst > 1) {
            PyErr_SetString(PyExc_ValueError,
                            "daylight savings flag out of range");
            return NULL;
        }

391 392
	fmtlen = strlen(fmt);

393 394 395
	/* I hate these functions that presume you know how big the output
	 * will be ahead of time...
	 */
396
	for (i = 1024; ; i += i) {
Guido van Rossum's avatar
Guido van Rossum committed
397 398
		outbuf = malloc(i);
		if (outbuf == NULL) {
Barry Warsaw's avatar
Barry Warsaw committed
399
			return PyErr_NoMemory();
Guido van Rossum's avatar
Guido van Rossum committed
400
		}
401 402 403 404 405 406 407
		buflen = strftime(outbuf, i, fmt, &buf);
		if (buflen > 0 || i >= 256 * fmtlen) {
			/* If the buffer is 256 times as long as the format,
			   it's probably not failing for lack of room!
			   More likely, the format yields an empty result,
			   e.g. an empty format, or %Z when the timezone
			   is unknown. */
Barry Warsaw's avatar
Barry Warsaw committed
408
			PyObject *ret;
409
			ret = PyString_FromStringAndSize(outbuf, buflen);
Guido van Rossum's avatar
Guido van Rossum committed
410 411 412 413 414 415
			free(outbuf);
			return ret;
		}
		free(outbuf);
	}
}
Guido van Rossum's avatar
Guido van Rossum committed
416

417
PyDoc_STRVAR(strftime_doc,
418
"strftime(format[, tuple]) -> string\n\
Guido van Rossum's avatar
Guido van Rossum committed
419 420
\n\
Convert a time tuple to a string according to a format specification.\n\
421
See the library reference manual for formatting codes. When the time tuple\n\
422
is not present, current time as returned by localtime() is used.");
Guido van Rossum's avatar
Guido van Rossum committed
423 424
#endif /* HAVE_STRFTIME */

425 426 427 428
static PyObject *
time_strptime(PyObject *self, PyObject *args)
{
    PyObject *strptime_module = PyImport_ImportModule("_strptime");
429
    PyObject *strptime_result;
430

431
    if (!strptime_module)
432
        return NULL;
433 434 435
    strptime_result = PyObject_CallMethod(strptime_module, "strptime", "O", args);
    Py_DECREF(strptime_module);
    return strptime_result;
436 437
}

438
PyDoc_STRVAR(strptime_doc,
439
"strptime(string, format) -> struct_time\n\
440
\n\
Guido van Rossum's avatar
Guido van Rossum committed
441
Parse a string to a time tuple according to a format specification.\n\
442
See the library reference manual for formatting codes (same as strftime()).");
443

444

Barry Warsaw's avatar
Barry Warsaw committed
445
static PyObject *
Peter Schneider-Kamp's avatar
Peter Schneider-Kamp committed
446
time_asctime(PyObject *self, PyObject *args)
447
{
448
	PyObject *tup = NULL;
449 450
	struct tm buf;
	char *p;
451
	if (!PyArg_ParseTuple(args, "|O:asctime", &tup))
452
		return NULL;
453 454 455 456
	if (tup == NULL) {
		time_t tt = time(NULL);
		buf = *localtime(&tt);
	} else if (!gettmarg(tup, &buf))
457 458 459 460
		return NULL;
	p = asctime(&buf);
	if (p[24] == '\n')
		p[24] = '\0';
Barry Warsaw's avatar
Barry Warsaw committed
461
	return PyString_FromString(p);
462 463
}

464
PyDoc_STRVAR(asctime_doc,
465
"asctime([tuple]) -> string\n\
Guido van Rossum's avatar
Guido van Rossum committed
466
\n\
467 468
Convert a time tuple to a string, e.g. 'Sat Jun 06 16:26:11 1998'.\n\
When the time tuple is not present, current time as returned by localtime()\n\
469
is used.");
Guido van Rossum's avatar
Guido van Rossum committed
470

Barry Warsaw's avatar
Barry Warsaw committed
471
static PyObject *
Peter Schneider-Kamp's avatar
Peter Schneider-Kamp committed
472
time_ctime(PyObject *self, PyObject *args)
473 474 475 476
{
	double dt;
	time_t tt;
	char *p;
477

478 479 480 481 482 483 484
	if (PyTuple_Size(args) == 0)
		tt = time(NULL);
	else {
		if (!PyArg_ParseTuple(args, "|d:ctime", &dt))
			return NULL;
		tt = (time_t)dt;
	}
485
	p = ctime(&tt);
486 487 488 489
	if (p == NULL) {
		PyErr_SetString(PyExc_ValueError, "unconvertible time");
		return NULL;
	}
490 491
	if (p[24] == '\n')
		p[24] = '\0';
Barry Warsaw's avatar
Barry Warsaw committed
492
	return PyString_FromString(p);
493 494
}

495
PyDoc_STRVAR(ctime_doc,
Guido van Rossum's avatar
Guido van Rossum committed
496 497 498
"ctime(seconds) -> string\n\
\n\
Convert a time in seconds since the Epoch to a string in local time.\n\
499
This is equivalent to asctime(localtime(seconds)). When the time tuple is\n\
500
not present, current time as returned by localtime() is used.");
Guido van Rossum's avatar
Guido van Rossum committed
501

502
#ifdef HAVE_MKTIME
Barry Warsaw's avatar
Barry Warsaw committed
503
static PyObject *
Peter Schneider-Kamp's avatar
Peter Schneider-Kamp committed
504
time_mktime(PyObject *self, PyObject *args)
505
{
506
	PyObject *tup;
507
	struct tm buf;
Guido van Rossum's avatar
Guido van Rossum committed
508
	time_t tt;
509
	if (!PyArg_ParseTuple(args, "O:mktime", &tup))
510
		return NULL;
Guido van Rossum's avatar
Guido van Rossum committed
511 512
	tt = time(&tt);
	buf = *localtime(&tt);
513
	if (!gettmarg(tup, &buf))
514
		return NULL;
Guido van Rossum's avatar
Guido van Rossum committed
515 516
	tt = mktime(&buf);
	if (tt == (time_t)(-1)) {
Barry Warsaw's avatar
Barry Warsaw committed
517
		PyErr_SetString(PyExc_OverflowError,
518
				"mktime argument out of range");
Guido van Rossum's avatar
Guido van Rossum committed
519 520
		return NULL;
	}
Barry Warsaw's avatar
Barry Warsaw committed
521
	return PyFloat_FromDouble((double)tt);
522
}
Guido van Rossum's avatar
Guido van Rossum committed
523

524
PyDoc_STRVAR(mktime_doc,
Guido van Rossum's avatar
Guido van Rossum committed
525 526
"mktime(tuple) -> floating point number\n\
\n\
527
Convert a time tuple in local time to seconds since the Epoch.");
528
#endif /* HAVE_MKTIME */
529

530 531
#ifdef HAVE_WORKING_TZSET
void inittimezone(PyObject *module);
Guido van Rossum's avatar
Guido van Rossum committed
532

533 534 535 536
static PyObject *
time_tzset(PyObject *self, PyObject *args)
{
	PyObject* m;
537

538 539
	if (!PyArg_ParseTuple(args, ":tzset"))
		return NULL;
540

541 542 543 544
	m = PyImport_ImportModule("time");
	if (m == NULL) {
	    return NULL;
	}
Guido van Rossum's avatar
Guido van Rossum committed
545

546
	tzset();
547

548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586
	/* Reset timezone, altzone, daylight and tzname */
	inittimezone(m);
	Py_DECREF(m);
	
	Py_INCREF(Py_None);
	return Py_None;
}

PyDoc_STRVAR(tzset_doc,
"tzset(zone)\n\
\n\
Initialize, or reinitialize, the local timezone to the value stored in\n\
os.environ['TZ']. The TZ environment variable should be specified in\n\
standard Uniz timezone format as documented in the tzset man page\n\
(eg. 'US/Eastern', 'Europe/Amsterdam'). Unknown timezones will silently\n\
fall back to UTC. If the TZ environment variable is not set, the local\n\
timezone is set to the systems best guess of wallclock time.\n\
Changing the TZ environment variable without calling tzset *may* change\n\
the local timezone used by methods such as localtime, but this behaviour\n\
should not be relied on.");
#endif /* HAVE_WORKING_TZSET */

void inittimezone(PyObject *m) {
    /* This code moved from inittime wholesale to allow calling it from
	time_tzset. In the future, some parts of it can be moved back
	(for platforms that don't HAVE_WORKING_TZSET, when we know what they
	are), and the extranious calls to tzset(3) should be removed.
	I havn't done this yet, as I don't want to change this code as
	little as possible when introducing the time.tzset and time.tzsetwall
	methods. This should simply be a method of doing the following once,
	at the top of this function and removing the call to tzset() from
	time_tzset():

	    #ifdef HAVE_TZSET
	    tzset()
	    #endif

	And I'm lazy and hate C so nyer.
     */
587
#if defined(HAVE_TZNAME) && !defined(__GLIBC__) && !defined(__CYGWIN__)
588
	tzset();
589
#ifdef PYOS_OS2
590
	PyModule_AddIntConstant(m, "timezone", _timezone);
591
#else /* !PYOS_OS2 */
592
	PyModule_AddIntConstant(m, "timezone", timezone);
593
#endif /* PYOS_OS2 */
594
#ifdef HAVE_ALTZONE
595
	PyModule_AddIntConstant(m, "altzone", altzone);
596
#else
597
#ifdef PYOS_OS2
598
	PyModule_AddIntConstant(m, "altzone", _timezone-3600);
599
#else /* !PYOS_OS2 */
600
	PyModule_AddIntConstant(m, "altzone", timezone-3600);
601
#endif /* PYOS_OS2 */
602
#endif
603 604 605
	PyModule_AddIntConstant(m, "daylight", daylight);
	PyModule_AddObject(m, "tzname",
			   Py_BuildValue("(zz)", tzname[0], tzname[1]));
606
#else /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/
607
#ifdef HAVE_STRUCT_TM_TM_ZONE
608 609 610 611
	{
#define YEAR ((time_t)((365 * 24 + 6) * 3600))
		time_t t;
		struct tm *p;
612 613
		long janzone, julyzone;
		char janname[10], julyname[10];
614 615
		t = (time((time_t *)0) / YEAR) * YEAR;
		p = localtime(&t);
616 617 618
		janzone = -p->tm_gmtoff;
		strncpy(janname, p->tm_zone ? p->tm_zone : "   ", 9);
		janname[9] = '\0';
619 620
		t += YEAR/2;
		p = localtime(&t);
621 622 623
		julyzone = -p->tm_gmtoff;
		strncpy(julyname, p->tm_zone ? p->tm_zone : "   ", 9);
		julyname[9] = '\0';
624

625 626
		if( janzone < julyzone ) {
			/* DST is reversed in the southern hemisphere */
627 628 629 630 631 632 633
			PyModule_AddIntConstant(m, "timezone", julyzone);
			PyModule_AddIntConstant(m, "altzone", janzone);
			PyModule_AddIntConstant(m, "daylight",
						janzone != julyzone);
			PyModule_AddObject(m, "tzname",
					   Py_BuildValue("(zz)",
							 julyname, janname));
634
		} else {
635 636 637 638 639 640 641
			PyModule_AddIntConstant(m, "timezone", janzone);
			PyModule_AddIntConstant(m, "altzone", julyzone);
			PyModule_AddIntConstant(m, "daylight",
						janzone != julyzone);
			PyModule_AddObject(m, "tzname",
					   Py_BuildValue("(zz)",
							 janname, julyname));
642
		}
643
	}
644
#else
645
#endif /* HAVE_STRUCT_TM_TM_ZONE */
646 647
#ifdef __CYGWIN__
	tzset();
648 649 650 651 652
	PyModule_AddIntConstant(m, "timezone", _timezone);
	PyModule_AddIntConstant(m, "altzone", _timezone);
	PyModule_AddIntConstant(m, "daylight", _daylight);
	PyModule_AddObject(m, "tzname",
			   Py_BuildValue("(zz)", _tzname[0], _tzname[1]));
653
#endif /* __CYGWIN__ */
654
#endif /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/
655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744
}


static PyMethodDef time_methods[] = {
	{"time",	time_time, METH_VARARGS, time_doc},
#ifdef HAVE_CLOCK
	{"clock",	time_clock, METH_VARARGS, clock_doc},
#endif
	{"sleep",	time_sleep, METH_VARARGS, sleep_doc},
	{"gmtime",	time_gmtime, METH_VARARGS, gmtime_doc},
	{"localtime",	time_localtime, METH_VARARGS, localtime_doc},
	{"asctime",	time_asctime, METH_VARARGS, asctime_doc},
	{"ctime",	time_ctime, METH_VARARGS, ctime_doc},
#ifdef HAVE_MKTIME
	{"mktime",	time_mktime, METH_VARARGS, mktime_doc},
#endif
#ifdef HAVE_STRFTIME
	{"strftime",	time_strftime, METH_VARARGS, strftime_doc},
#endif
	{"strptime",	time_strptime, METH_VARARGS, strptime_doc},
#ifdef HAVE_WORKING_TZSET
	{"tzset",	time_tzset, METH_VARARGS, tzset_doc},
#endif
	{NULL,		NULL}		/* sentinel */
};


PyDoc_STRVAR(module_doc,
"This module provides various functions to manipulate time values.\n\
\n\
There are two standard representations of time.  One is the number\n\
of seconds since the Epoch, in UTC (a.k.a. GMT).  It may be an integer\n\
or a floating point number (to represent fractions of seconds).\n\
The Epoch is system-defined; on Unix, it is generally January 1st, 1970.\n\
The actual value can be retrieved by calling gmtime(0).\n\
\n\
The other representation is a tuple of 9 integers giving local time.\n\
The tuple items are:\n\
  year (four digits, e.g. 1998)\n\
  month (1-12)\n\
  day (1-31)\n\
  hours (0-23)\n\
  minutes (0-59)\n\
  seconds (0-59)\n\
  weekday (0-6, Monday is 0)\n\
  Julian day (day in the year, 1-366)\n\
  DST (Daylight Savings Time) flag (-1, 0 or 1)\n\
If the DST flag is 0, the time is given in the regular time zone;\n\
if it is 1, the time is given in the DST time zone;\n\
if it is -1, mktime() should guess based on the date and time.\n\
\n\
Variables:\n\
\n\
timezone -- difference in seconds between UTC and local standard time\n\
altzone -- difference in  seconds between UTC and local DST time\n\
daylight -- whether local time should reflect DST\n\
tzname -- tuple of (standard time zone name, DST time zone name)\n\
\n\
Functions:\n\
\n\
time() -- return current time in seconds since the Epoch as a float\n\
clock() -- return CPU time since process start as a float\n\
sleep() -- delay for a number of seconds given as a float\n\
gmtime() -- convert seconds since Epoch to UTC tuple\n\
localtime() -- convert seconds since Epoch to local time tuple\n\
asctime() -- convert time tuple to string\n\
ctime() -- convert time in seconds to string\n\
mktime() -- convert local time tuple to seconds since Epoch\n\
strftime() -- convert time tuple to string according to format specification\n\
strptime() -- parse string to time tuple according to format specification\n\
tzset() -- change the local timezone");


PyMODINIT_FUNC
inittime(void)
{
	PyObject *m;
	char *p;
	m = Py_InitModule3("time", time_methods, module_doc);

	/* Accept 2-digit dates unless PYTHONY2K is set and non-empty */
	p = Py_GETENV("PYTHONY2K");
	PyModule_AddIntConstant(m, "accept2dyear", (long) (!p || !*p));
	/* Squirrel away the module's dictionary for the y2k check */
	moddict = PyModule_GetDict(m);
	Py_INCREF(moddict);

	/* Set, or reset, module variables like time.timezone */
	inittimezone(m);

745 746 747 748 749 750 751 752 753
#ifdef MS_WINDOWS
	/* Helper to allow interrupts for Windows.
	   If Ctrl+C event delivered while not sleeping
	   it will be ignored.
	*/
	main_thread = PyThread_get_thread_ident();
	hInterruptEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
	SetConsoleCtrlHandler( PyCtrlHandler, TRUE);
#endif /* MS_WINDOWS */
754
        PyStructSequence_InitType(&StructTimeType, &struct_time_type_desc);
755 756
	Py_INCREF(&StructTimeType);
	PyModule_AddObject(m, "struct_time", (PyObject*) &StructTimeType);
Guido van Rossum's avatar
Guido van Rossum committed
757 758 759
}


760
/* Implement floattime() for various platforms */
Guido van Rossum's avatar
Guido van Rossum committed
761

762
static double
763
floattime(void)
Guido van Rossum's avatar
Guido van Rossum committed
764
{
765
	/* There are three ways to get the time:
766 767 768 769 770 771 772
	  (1) gettimeofday() -- resolution in microseconds
	  (2) ftime() -- resolution in milliseconds
	  (3) time() -- resolution in seconds
	  In all cases the return value is a float in seconds.
	  Since on some systems (e.g. SCO ODT 3.0) gettimeofday() may
	  fail, so we fall back on ftime() or time().
	  Note: clock resolution does not imply clock accuracy! */
773
#ifdef HAVE_GETTIMEOFDAY
774 775
	{
		struct timeval t;
776
#ifdef GETTIMEOFDAY_NO_TZ
777 778
		if (gettimeofday(&t) == 0)
			return (double)t.tv_sec + t.tv_usec*0.000001;
779
#else /* !GETTIMEOFDAY_NO_TZ */
780 781
		if (gettimeofday(&t, (struct timezone *)NULL) == 0)
			return (double)t.tv_sec + t.tv_usec*0.000001;
782
#endif /* !GETTIMEOFDAY_NO_TZ */
783
	}
784
#endif /* !HAVE_GETTIMEOFDAY */
785
	{
786
#if defined(HAVE_FTIME)
787 788 789
		struct timeb t;
		ftime(&t);
		return (double)t.time + (double)t.millitm * (double)0.001;
790
#else /* !HAVE_FTIME */
791 792 793
		time_t secs;
		time(&secs);
		return (double)secs;
794
#endif /* !HAVE_FTIME */
795
	}
Guido van Rossum's avatar
Guido van Rossum committed
796 797
}

798

799 800 801
/* Implement floatsleep() for various platforms.
   When interrupted (or when another error occurs), return -1 and
   set an exception; else return 0. */
802

803
static int
Guido van Rossum's avatar
Guido van Rossum committed
804
floatsleep(double secs)
Guido van Rossum's avatar
Guido van Rossum committed
805
{
806
/* XXX Should test for MS_WINDOWS first! */
807
#if defined(HAVE_SELECT) && !defined(__BEOS__) && !defined(__EMX__)
Guido van Rossum's avatar
Guido van Rossum committed
808
	struct timeval t;
809 810 811 812 813
	double frac;
	frac = fmod(secs, 1.0);
	secs = floor(secs);
	t.tv_sec = (long)secs;
	t.tv_usec = (long)(frac*1000000.0);
814
	Py_BEGIN_ALLOW_THREADS
815
	if (select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &t) != 0) {
816
#ifdef EINTR
817
		if (errno != EINTR) {
818 819 820
#else
		if (1) {
#endif
821
			Py_BLOCK_THREADS
822 823 824
			PyErr_SetFromErrno(PyExc_IOError);
			return -1;
		}
825
	}
826
	Py_END_ALLOW_THREADS
827
#elif defined(__WATCOMC__) && !defined(__QNX__)
Guido van Rossum's avatar
Guido van Rossum committed
828
	/* XXX Can't interrupt this sleep */
829
	Py_BEGIN_ALLOW_THREADS
Guido van Rossum's avatar
Guido van Rossum committed
830
	delay((int)(secs * 1000 + 0.5));  /* delay() uses milliseconds */
831
	Py_END_ALLOW_THREADS
832
#elif defined(MS_WINDOWS)
833 834
	{
		double millisecs = secs * 1000.0;
835 836
		unsigned long ul_millis;

837
		if (millisecs > (double)ULONG_MAX) {
838 839
			PyErr_SetString(PyExc_OverflowError,
					"sleep length is too large");
840 841 842
			return -1;
		}
		Py_BEGIN_ALLOW_THREADS
843 844 845 846 847 848 849
		/* Allow sleep(0) to maintain win32 semantics, and as decreed
		 * by Guido, only the main thread can be interrupted.
		 */
		ul_millis = (unsigned long)millisecs;
		if (ul_millis == 0 ||
		    main_thread != PyThread_get_thread_ident())
			Sleep(ul_millis);
850 851 852
		else {
			DWORD rc;
			ResetEvent(hInterruptEvent);
853 854 855 856 857
			rc = WaitForSingleObject(hInterruptEvent, ul_millis);
			if (rc == WAIT_OBJECT_0) {
				/* Yield to make sure real Python signal
				 * handler called.
				 */
858 859 860 861 862 863 864
				Sleep(1);
				Py_BLOCK_THREADS
				errno = EINTR;
				PyErr_SetFromErrno(PyExc_IOError);
				return -1;
			}
		}
865 866
		Py_END_ALLOW_THREADS
	}
867
#elif defined(PYOS_OS2)
868
	/* This Sleep *IS* Interruptable by Exceptions */
869
	Py_BEGIN_ALLOW_THREADS
870
	if (DosSleep(secs * 1000) != NO_ERROR) {
871
		Py_BLOCK_THREADS
872 873 874
		PyErr_SetFromErrno(PyExc_IOError);
		return -1;
	}
875
	Py_END_ALLOW_THREADS
876
#elif defined(__BEOS__)
877 878 879 880 881
	/* This sleep *CAN BE* interrupted. */
	{
		if( secs <= 0.0 ) {
			return;
		}
882

883
		Py_BEGIN_ALLOW_THREADS
884 885
		/* BeOS snooze() is in microseconds... */
		if( snooze( (bigtime_t)( secs * 1000.0 * 1000.0 ) ) == B_INTERRUPTED ) {
886 887 888 889 890 891
			Py_BLOCK_THREADS
			PyErr_SetFromErrno( PyExc_IOError );
			return -1;
		}
		Py_END_ALLOW_THREADS
	}
892
#elif defined(RISCOS)
893 894 895 896
	if (secs <= 0.0)
		return 0;
	Py_BEGIN_ALLOW_THREADS
	/* This sleep *CAN BE* interrupted. */
897
	if ( riscos_sleep(secs) )
898 899
		return -1;
	Py_END_ALLOW_THREADS
900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916
#elif defined(PLAN9)
	{
		double millisecs = secs * 1000.0;
		if (millisecs > (double)LONG_MAX) {
			PyErr_SetString(PyExc_OverflowError, "sleep length is too large");
			return -1;
		}
		/* This sleep *CAN BE* interrupted. */
		Py_BEGIN_ALLOW_THREADS
		if(sleep((long)millisecs) < 0){
			Py_BLOCK_THREADS
			PyErr_SetFromErrno(PyExc_IOError);
			return -1;
		}
		Py_END_ALLOW_THREADS
	}
#else
917
	/* XXX Can't interrupt this sleep */
918
	Py_BEGIN_ALLOW_THREADS
919
	sleep((int)secs);
920
	Py_END_ALLOW_THREADS
921
#endif
922

923
	return 0;
924
}
925 926