timemodule.c 27 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"
6
#include "timefuncs.h"
Guido van Rossum's avatar
Guido van Rossum committed
7

8 9 10 11 12 13 14 15 16 17 18 19
#ifdef __APPLE__
#if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_FTIME)
  /*
   * floattime falls back to ftime when getttimeofday fails because the latter
   * might fail on some platforms. This fallback is unwanted on MacOSX because
   * that makes it impossible to use a binary build on OSX 10.4 on earlier
   * releases of the OS. Therefore claim we don't support ftime.
   */
# undef HAVE_FTIME
#endif
#endif

20 21
#include <ctype.h>

22
#ifdef HAVE_SYS_TYPES_H
23
#include <sys/types.h>
24
#endif /* HAVE_SYS_TYPES_H */
25

26 27
#ifdef QUICKWIN
#include <io.h>
28 29
#endif

30 31
#ifdef HAVE_FTIME
#include <sys/timeb.h>
32
#if !defined(MS_WINDOWS) && !defined(PYOS_OS2)
33
extern int ftime(struct timeb *);
34 35
#endif /* MS_WINDOWS */
#endif /* HAVE_FTIME */
36

37
#if defined(__WATCOMC__) && !defined(__QNX__)
Guido van Rossum's avatar
Guido van Rossum committed
38 39
#include <i86.h>
#else
40
#ifdef MS_WINDOWS
41
#define WIN32_LEAN_AND_MEAN
42
#include <windows.h>
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
#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;


59
#if defined(__BORLANDC__)
60
/* These overrides not needed for Win32 */
61
#define timezone _timezone
62
#define tzname _tzname
63
#define daylight _daylight
64
#endif /* __BORLANDC__ */
65
#endif /* MS_WINDOWS */
66
#endif /* !__WATCOMC__ || __QNX__ */
67

68
#if defined(MS_WINDOWS) && !defined(__BORLANDC__)
69 70
/* Win32 has better clock replacement; we have our own version below. */
#undef HAVE_CLOCK
71
#endif /* MS_WINDOWS && !defined(__BORLANDC__) */
72

73 74 75 76 77 78
#if defined(PYOS_OS2)
#define INCL_DOS
#define INCL_ERRORS
#include <os2.h>
#endif

79
#if defined(PYCC_VACPP)
80
#include <sys/time.h>
81 82
#endif

83
#ifdef __BEOS__
84
#include <time.h>
85 86 87 88 89
/* For bigtime_t, snooze(). - [cjh] */
#include <support/SupportDefs.h>
#include <kernel/OS.h>
#endif

90 91 92 93
#ifdef RISCOS
extern int riscos_sleep(double);
#endif

94
/* Forward declarations */
95
static int floatsleep(double);
96
static double floattime(void);
Guido van Rossum's avatar
Guido van Rossum committed
97

98 99 100
/* For Y2K check */
static PyObject *moddict;

101 102
/* Exposed in timefuncs.h. */
time_t
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
_PyTime_DoubleToTimet(double x)
{
	time_t result;
	double diff;

	result = (time_t)x;
	/* How much info did we lose?  time_t may be an integral or
	 * floating type, and we don't know which.  If it's integral,
	 * we don't know whether C truncates, rounds, returns the floor,
	 * etc.  If we lost a second or more, the C rounding is
	 * unreasonable, or the input just doesn't fit in a time_t;
	 * call it an error regardless.  Note that the original cast to
	 * time_t can cause a C error too, but nothing we can do to
	 * worm around that.
	 */
	diff = x - (double)result;
	if (diff <= -1.0 || diff >= 1.0) {
		PyErr_SetString(PyExc_ValueError,
		                "timestamp out of range for platform time_t");
		result = (time_t)-1;
	}
	return result;
}

Barry Warsaw's avatar
Barry Warsaw committed
127
static PyObject *
128
time_time(PyObject *self, PyObject *unused)
Guido van Rossum's avatar
Guido van Rossum committed
129
{
130 131 132
	double secs;
	secs = floattime();
	if (secs == 0.0) {
Barry Warsaw's avatar
Barry Warsaw committed
133
		PyErr_SetFromErrno(PyExc_IOError);
134 135
		return NULL;
	}
Barry Warsaw's avatar
Barry Warsaw committed
136
	return PyFloat_FromDouble(secs);
Guido van Rossum's avatar
Guido van Rossum committed
137 138
}

139
PyDoc_STRVAR(time_doc,
Guido van Rossum's avatar
Guido van Rossum committed
140 141 142
"time() -> floating point number\n\
\n\
Return the current time in seconds since the Epoch.\n\
143
Fractions of a second may be present if the system clock provides them.");
Guido van Rossum's avatar
Guido van Rossum committed
144

145
#ifdef HAVE_CLOCK
Guido van Rossum's avatar
Guido van Rossum committed
146

147
#ifndef CLOCKS_PER_SEC
148 149 150
#ifdef CLK_TCK
#define CLOCKS_PER_SEC CLK_TCK
#else
151 152
#define CLOCKS_PER_SEC 1000000
#endif
153
#endif
Guido van Rossum's avatar
Guido van Rossum committed
154

Barry Warsaw's avatar
Barry Warsaw committed
155
static PyObject *
156
time_clock(PyObject *self, PyObject *unused)
Guido van Rossum's avatar
Guido van Rossum committed
157
{
Barry Warsaw's avatar
Barry Warsaw committed
158
	return PyFloat_FromDouble(((double)clock()) / CLOCKS_PER_SEC);
Guido van Rossum's avatar
Guido van Rossum committed
159
}
160
#endif /* HAVE_CLOCK */
Guido van Rossum's avatar
Guido van Rossum committed
161

162
#if defined(MS_WINDOWS) && !defined(__BORLANDC__)
163
/* Due to Mark Hammond and Tim Peters */
164
static PyObject *
165
time_clock(PyObject *self, PyObject *unused)
166
{
167
	static LARGE_INTEGER ctrStart;
168
	static double divisor = 0.0;
169
	LARGE_INTEGER now;
170
	double diff;
171

172
	if (divisor == 0.0) {
173 174 175
		LARGE_INTEGER freq;
		QueryPerformanceCounter(&ctrStart);
		if (!QueryPerformanceFrequency(&freq) || freq.QuadPart == 0) {
176 177
			/* Unlikely to happen - this works on all intel
			   machines at least!  Revert to clock() */
178 179
			return PyFloat_FromDouble(((double)clock()) /
						  CLOCKS_PER_SEC);
180
		}
181
		divisor = (double)freq.QuadPart;
182
	}
183 184
	QueryPerformanceCounter(&now);
	diff = (double)(now.QuadPart - ctrStart.QuadPart);
185
	return PyFloat_FromDouble(diff / divisor);
186
}
Guido van Rossum's avatar
Guido van Rossum committed
187

188
#define HAVE_CLOCK /* So it gets included in the methods */
189
#endif /* MS_WINDOWS && !defined(__BORLANDC__) */
190

Guido van Rossum's avatar
Guido van Rossum committed
191
#ifdef HAVE_CLOCK
192
PyDoc_STRVAR(clock_doc,
Guido van Rossum's avatar
Guido van Rossum committed
193 194 195
"clock() -> floating point number\n\
\n\
Return the CPU time or real time since the start of the process or since\n\
196 197
the first call to clock().  This has as much precision as the system\n\
records.");
Guido van Rossum's avatar
Guido van Rossum committed
198 199
#endif

Barry Warsaw's avatar
Barry Warsaw committed
200
static PyObject *
Peter Schneider-Kamp's avatar
Peter Schneider-Kamp committed
201
time_sleep(PyObject *self, PyObject *args)
Guido van Rossum's avatar
Guido van Rossum committed
202
{
203
	double secs;
204
	if (!PyArg_ParseTuple(args, "d:sleep", &secs))
Guido van Rossum's avatar
Guido van Rossum committed
205
		return NULL;
206 207 208
	if (floatsleep(secs) != 0)
		return NULL;
	Py_INCREF(Py_None);
Barry Warsaw's avatar
Barry Warsaw committed
209
	return Py_None;
Guido van Rossum's avatar
Guido van Rossum committed
210 211
}

212
PyDoc_STRVAR(sleep_doc,
Guido van Rossum's avatar
Guido van Rossum committed
213 214 215
"sleep(seconds)\n\
\n\
Delay execution for a given number of seconds.  The argument may be\n\
216
a floating point number for subsecond precision.");
Guido van Rossum's avatar
Guido van Rossum committed
217

218 219 220 221 222 223 224 225 226 227 228 229 230 231
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 = {
232
	"time.struct_time",
233 234 235 236
	NULL,
	struct_time_type_fields,
	9,
};
237

238
static int initialized;
239 240
static PyTypeObject StructTimeType;

241
static PyObject *
Peter Schneider-Kamp's avatar
Peter Schneider-Kamp committed
242
tmtotuple(struct tm *p)
243
{
244 245 246
	PyObject *v = PyStructSequence_New(&StructTimeType);
	if (v == NULL)
		return NULL;
247

248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265
#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;
266 267
}

Barry Warsaw's avatar
Barry Warsaw committed
268
static PyObject *
269
time_convert(double when, struct tm * (*function)(const time_t *))
270
{
271
	struct tm *p;
272 273 274 275
	time_t whent = _PyTime_DoubleToTimet(when);

	if (whent == (time_t)-1 && PyErr_Occurred())
		return NULL;
276
	errno = 0;
277
	p = function(&whent);
278 279
	if (p == NULL) {
#ifdef EINVAL
280
		if (errno == 0)
281 282
			errno = EINVAL;
#endif
283
		return PyErr_SetFromErrno(PyExc_ValueError);
284
	}
285
	return tmtotuple(p);
286 287
}

288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309
/* Parse arg tuple that can contain an optional float-or-None value;
   format needs to be "|O:name".
   Returns non-zero on success (parallels PyArg_ParseTuple).
*/
static int
parse_time_double_args(PyObject *args, char *format, double *pwhen)
{
	PyObject *ot = NULL;

	if (!PyArg_ParseTuple(args, format, &ot))
		return 0;
	if (ot == NULL || ot == Py_None)
		*pwhen = floattime();
	else {
		double when = PyFloat_AsDouble(ot);
		if (PyErr_Occurred())
			return 0;
		*pwhen = when;
	}
	return 1;
}

Barry Warsaw's avatar
Barry Warsaw committed
310
static PyObject *
Peter Schneider-Kamp's avatar
Peter Schneider-Kamp committed
311
time_gmtime(PyObject *self, PyObject *args)
312 313
{
	double when;
314
	if (!parse_time_double_args(args, "|O:gmtime", &when))
315
		return NULL;
316
	return time_convert(when, gmtime);
317 318
}

319
PyDoc_STRVAR(gmtime_doc,
320
"gmtime([seconds]) -> (tm_year, tm_mon, tm_mday, tm_hour, tm_min,\n\
321
                       tm_sec, tm_wday, tm_yday, tm_isdst)\n\
Guido van Rossum's avatar
Guido van Rossum committed
322
\n\
323
Convert seconds since the Epoch to a time tuple expressing UTC (a.k.a.\n\
324
GMT).  When 'seconds' is not passed in, convert the current time instead.");
Guido van Rossum's avatar
Guido van Rossum committed
325

Barry Warsaw's avatar
Barry Warsaw committed
326
static PyObject *
Peter Schneider-Kamp's avatar
Peter Schneider-Kamp committed
327
time_localtime(PyObject *self, PyObject *args)
328 329
{
	double when;
330
	if (!parse_time_double_args(args, "|O:localtime", &when))
331
		return NULL;
332
	return time_convert(when, localtime);
333 334
}

335
PyDoc_STRVAR(localtime_doc,
336 337
"localtime([seconds]) -> (tm_year,tm_mon,tm_mday,tm_hour,tm_min,\n\
			  tm_sec,tm_wday,tm_yday,tm_isdst)\n\
338
\n\
339
Convert seconds since the Epoch to a time tuple expressing local time.\n\
340
When 'seconds' is not passed in, convert the current time instead.");
Guido van Rossum's avatar
Guido van Rossum committed
341

342
static int
Peter Schneider-Kamp's avatar
Peter Schneider-Kamp committed
343
gettmarg(PyObject *args, struct tm *p)
344
{
345
	int y;
346
	memset((void *) p, '\0', sizeof(struct tm));
347

Barry Warsaw's avatar
Barry Warsaw committed
348
	if (!PyArg_Parse(args, "(iiiiiiiii)",
349
			 &y,
350 351 352 353 354 355 356 357
			 &p->tm_mon,
			 &p->tm_mday,
			 &p->tm_hour,
			 &p->tm_min,
			 &p->tm_sec,
			 &p->tm_wday,
			 &p->tm_yday,
			 &p->tm_isdst))
358
		return 0;
359 360 361 362 363 364 365 366 367 368 369 370 371 372 373
	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,
374
					"year out of range");
375 376 377 378
			return 0;
		}
	}
	p->tm_year = y - 1900;
379 380 381 382 383 384
	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
385
#ifdef HAVE_STRFTIME
Barry Warsaw's avatar
Barry Warsaw committed
386
static PyObject *
Peter Schneider-Kamp's avatar
Peter Schneider-Kamp committed
387
time_strftime(PyObject *self, PyObject *args)
Guido van Rossum's avatar
Guido van Rossum committed
388
{
389
	PyObject *tup = NULL;
Guido van Rossum's avatar
Guido van Rossum committed
390 391
	struct tm buf;
	const char *fmt;
392
	size_t fmtlen, buflen;
Guido van Rossum's avatar
Guido van Rossum committed
393
	char *outbuf = 0;
394
	size_t i;
Guido van Rossum's avatar
Guido van Rossum committed
395

396
	memset((void *) &buf, '\0', sizeof(buf));
397

398 399 400 401 402 403 404
	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
405
		return NULL;
406

Brett Cannon's avatar
Brett Cannon committed
407 408 409
	/* 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).
410

411 412
	    Also support values of zero from Python code for arguments in which
	    that is out of range by forcing that value to the lowest value that
413
	    is valid (fixed bug #1520914).
414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429

	    Valid ranges based on what is allowed in struct tm:

	    - tm_year: [0, max(int)] (1)
	    - tm_mon: [0, 11] (2)
	    - tm_mday: [1, 31]
	    - tm_hour: [0, 23]
	    - tm_min: [0, 59]
	    - tm_sec: [0, 60]
	    - tm_wday: [0, 6] (1)
	    - tm_yday: [0, 365] (2)
	    - tm_isdst: [-max(int), max(int)]

	    (1) gettmarg() handles bounds-checking.
	    (2) Python's acceptable range is one greater than the range in C,
	        thus need to check against automatic decrement by gettmarg().
Brett Cannon's avatar
Brett Cannon committed
430
	*/
431 432 433
	if (buf.tm_mon == -1)
	    buf.tm_mon = 0;
	else if (buf.tm_mon < 0 || buf.tm_mon > 11) {
Brett Cannon's avatar
Brett Cannon committed
434 435 436
		PyErr_SetString(PyExc_ValueError, "month out of range");
			return NULL;
	}
437 438 439
	if (buf.tm_mday == 0)
	    buf.tm_mday = 1;
	else if (buf.tm_mday < 0 || buf.tm_mday > 31) {
Brett Cannon's avatar
Brett Cannon committed
440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460
		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;
	}
461 462 463
	if (buf.tm_yday == -1)
	    buf.tm_yday = 0;
	else if (buf.tm_yday < 0 || buf.tm_yday > 365) {
Brett Cannon's avatar
Brett Cannon committed
464 465 466
		PyErr_SetString(PyExc_ValueError, "day of year out of range");
		return NULL;
	}
467 468 469
	/* Normalize tm_isdst just in case someone foolishly implements %Z
	   based on the assumption that tm_isdst falls within the range of
	   [-1, 1] */
Brett Cannon's avatar
Brett Cannon committed
470 471
	if (buf.tm_isdst < -1)
		buf.tm_isdst = -1;
472
	else if (buf.tm_isdst > 1)
Brett Cannon's avatar
Brett Cannon committed
473
		buf.tm_isdst = 1;
474

475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491
#ifdef MS_WINDOWS
	/* check that the format string contains only valid directives */
	for(outbuf = strchr(fmt, '%');
		outbuf != NULL;
		outbuf = strchr(outbuf+2, '%'))
	{
		if (outbuf[1]=='#')
			++outbuf; /* not documented by python, */
		if (outbuf[1]=='\0' ||
			!strchr("aAbBcdfHIjmMpSUwWxXyYzZ%", outbuf[1]))
		{
			PyErr_SetString(PyExc_ValueError, "Invalid format string");
			return 0;
		}
	}
#endif

492 493
	fmtlen = strlen(fmt);

494 495 496
	/* I hate these functions that presume you know how big the output
	 * will be ahead of time...
	 */
497
	for (i = 1024; ; i += i) {
498
		outbuf = (char *)malloc(i);
Guido van Rossum's avatar
Guido van Rossum committed
499
		if (outbuf == NULL) {
Barry Warsaw's avatar
Barry Warsaw committed
500
			return PyErr_NoMemory();
Guido van Rossum's avatar
Guido van Rossum committed
501
		}
502 503 504 505 506 507 508
		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
509
			PyObject *ret;
510
			ret = PyString_FromStringAndSize(outbuf, buflen);
Guido van Rossum's avatar
Guido van Rossum committed
511 512 513 514
			free(outbuf);
			return ret;
		}
		free(outbuf);
515
#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
516 517 518 519 520 521 522
		/* VisualStudio .NET 2005 does this properly */
		if (buflen == 0 && errno == EINVAL) {
			PyErr_SetString(PyExc_ValueError, "Invalid format string");
			return 0;
		}
#endif
		
Guido van Rossum's avatar
Guido van Rossum committed
523 524
	}
}
Guido van Rossum's avatar
Guido van Rossum committed
525

526
PyDoc_STRVAR(strftime_doc,
527
"strftime(format[, tuple]) -> string\n\
Guido van Rossum's avatar
Guido van Rossum committed
528 529
\n\
Convert a time tuple to a string according to a format specification.\n\
530
See the library reference manual for formatting codes. When the time tuple\n\
531
is not present, current time as returned by localtime() is used.");
Guido van Rossum's avatar
Guido van Rossum committed
532 533
#endif /* HAVE_STRFTIME */

534 535 536
static PyObject *
time_strptime(PyObject *self, PyObject *args)
{
Brett Cannon's avatar
Brett Cannon committed
537 538 539 540 541 542 543 544 545
	PyObject *strptime_module = PyImport_ImportModuleNoBlock("_strptime");
	PyObject *strptime_result;

	if (!strptime_module)
		return NULL;
	strptime_result = PyObject_CallMethod(strptime_module,
						"_strptime_time", "O", args);
	Py_DECREF(strptime_module);
	return strptime_result;
546 547
}

548
PyDoc_STRVAR(strptime_doc,
549
"strptime(string, format) -> struct_time\n\
550
\n\
Guido van Rossum's avatar
Guido van Rossum committed
551
Parse a string to a time tuple according to a format specification.\n\
552
See the library reference manual for formatting codes (same as strftime()).");
553

554

Barry Warsaw's avatar
Barry Warsaw committed
555
static PyObject *
Peter Schneider-Kamp's avatar
Peter Schneider-Kamp committed
556
time_asctime(PyObject *self, PyObject *args)
557
{
558
	PyObject *tup = NULL;
559 560
	struct tm buf;
	char *p;
561
	if (!PyArg_UnpackTuple(args, "asctime", 0, 1, &tup))
562
		return NULL;
563 564 565 566
	if (tup == NULL) {
		time_t tt = time(NULL);
		buf = *localtime(&tt);
	} else if (!gettmarg(tup, &buf))
567 568 569 570
		return NULL;
	p = asctime(&buf);
	if (p[24] == '\n')
		p[24] = '\0';
571
	return PyString_FromString(p);
572 573
}

574
PyDoc_STRVAR(asctime_doc,
575
"asctime([tuple]) -> string\n\
Guido van Rossum's avatar
Guido van Rossum committed
576
\n\
577 578
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\
579
is used.");
Guido van Rossum's avatar
Guido van Rossum committed
580

Barry Warsaw's avatar
Barry Warsaw committed
581
static PyObject *
Peter Schneider-Kamp's avatar
Peter Schneider-Kamp committed
582
time_ctime(PyObject *self, PyObject *args)
583
{
584
	PyObject *ot = NULL;
585 586
	time_t tt;
	char *p;
587

588
	if (!PyArg_UnpackTuple(args, "ctime", 0, 1, &ot))
589 590
		return NULL;
	if (ot == NULL || ot == Py_None)
591 592
		tt = time(NULL);
	else {
593 594
		double dt = PyFloat_AsDouble(ot);
		if (PyErr_Occurred())
595
			return NULL;
596 597 598
		tt = _PyTime_DoubleToTimet(dt);
		if (tt == (time_t)-1 && PyErr_Occurred())
			return NULL;
599
	}
600
	p = ctime(&tt);
601 602 603 604
	if (p == NULL) {
		PyErr_SetString(PyExc_ValueError, "unconvertible time");
		return NULL;
	}
605 606
	if (p[24] == '\n')
		p[24] = '\0';
607
	return PyString_FromString(p);
608 609
}

610
PyDoc_STRVAR(ctime_doc,
Guido van Rossum's avatar
Guido van Rossum committed
611 612 613
"ctime(seconds) -> string\n\
\n\
Convert a time in seconds since the Epoch to a string in local time.\n\
614
This is equivalent to asctime(localtime(seconds)). When the time tuple is\n\
615
not present, current time as returned by localtime() is used.");
Guido van Rossum's avatar
Guido van Rossum committed
616

617
#ifdef HAVE_MKTIME
Barry Warsaw's avatar
Barry Warsaw committed
618
static PyObject *
619
time_mktime(PyObject *self, PyObject *tup)
620 621
{
	struct tm buf;
Guido van Rossum's avatar
Guido van Rossum committed
622
	time_t tt;
623
	if (!gettmarg(tup, &buf))
624
		return NULL;
Guido van Rossum's avatar
Guido van Rossum committed
625 626
	tt = mktime(&buf);
	if (tt == (time_t)(-1)) {
Barry Warsaw's avatar
Barry Warsaw committed
627
		PyErr_SetString(PyExc_OverflowError,
628
				"mktime argument out of range");
Guido van Rossum's avatar
Guido van Rossum committed
629 630
		return NULL;
	}
Barry Warsaw's avatar
Barry Warsaw committed
631
	return PyFloat_FromDouble((double)tt);
632
}
Guido van Rossum's avatar
Guido van Rossum committed
633

634
PyDoc_STRVAR(mktime_doc,
Guido van Rossum's avatar
Guido van Rossum committed
635 636
"mktime(tuple) -> floating point number\n\
\n\
637
Convert a time tuple in local time to seconds since the Epoch.");
638
#endif /* HAVE_MKTIME */
639

640
#ifdef HAVE_WORKING_TZSET
641
static void inittimezone(PyObject *module);
Guido van Rossum's avatar
Guido van Rossum committed
642

643
static PyObject *
644
time_tzset(PyObject *self, PyObject *unused)
645 646
{
	PyObject* m;
647

648
	m = PyImport_ImportModuleNoBlock("time");
649 650 651
	if (m == NULL) {
	    return NULL;
	}
Guido van Rossum's avatar
Guido van Rossum committed
652

653
	tzset();
654

655 656 657
	/* Reset timezone, altzone, daylight and tzname */
	inittimezone(m);
	Py_DECREF(m);
658

659 660 661 662 663 664 665 666 667
	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\
668
standard Unix timezone format as documented in the tzset man page\n\
669 670 671 672 673 674 675 676
(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 */

677 678
static void
inittimezone(PyObject *m) {
679 680 681
    /* 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
Skip Montanaro's avatar
Skip Montanaro committed
682
	are), and the extraneous calls to tzset(3) should be removed.
Walter Dörwald's avatar
Walter Dörwald committed
683
	I haven't done this yet, as I don't want to change this code as
684 685 686 687 688 689 690 691 692 693 694
	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.
     */
695
#if defined(HAVE_TZNAME) && !defined(__GLIBC__) && !defined(__CYGWIN__)
696
	tzset();
697
#ifdef PYOS_OS2
698
	PyModule_AddIntConstant(m, "timezone", _timezone);
699
#else /* !PYOS_OS2 */
700
	PyModule_AddIntConstant(m, "timezone", timezone);
701
#endif /* PYOS_OS2 */
702
#ifdef HAVE_ALTZONE
703
	PyModule_AddIntConstant(m, "altzone", altzone);
704
#else
705
#ifdef PYOS_OS2
706
	PyModule_AddIntConstant(m, "altzone", _timezone-3600);
707
#else /* !PYOS_OS2 */
708
	PyModule_AddIntConstant(m, "altzone", timezone-3600);
709
#endif /* PYOS_OS2 */
710
#endif
711 712 713
	PyModule_AddIntConstant(m, "daylight", daylight);
	PyModule_AddObject(m, "tzname",
			   Py_BuildValue("(zz)", tzname[0], tzname[1]));
714
#else /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/
715
#ifdef HAVE_STRUCT_TM_TM_ZONE
716 717 718 719
	{
#define YEAR ((time_t)((365 * 24 + 6) * 3600))
		time_t t;
		struct tm *p;
720 721
		long janzone, julyzone;
		char janname[10], julyname[10];
722 723
		t = (time((time_t *)0) / YEAR) * YEAR;
		p = localtime(&t);
724 725 726
		janzone = -p->tm_gmtoff;
		strncpy(janname, p->tm_zone ? p->tm_zone : "   ", 9);
		janname[9] = '\0';
727 728
		t += YEAR/2;
		p = localtime(&t);
729 730 731
		julyzone = -p->tm_gmtoff;
		strncpy(julyname, p->tm_zone ? p->tm_zone : "   ", 9);
		julyname[9] = '\0';
732

733 734
		if( janzone < julyzone ) {
			/* DST is reversed in the southern hemisphere */
735 736 737 738 739 740 741
			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));
742
		} else {
743 744 745 746 747 748 749
			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));
750
		}
751
	}
752
#else
753
#endif /* HAVE_STRUCT_TM_TM_ZONE */
754 755
#ifdef __CYGWIN__
	tzset();
756
	PyModule_AddIntConstant(m, "timezone", _timezone);
757
	PyModule_AddIntConstant(m, "altzone", _timezone-3600);
758 759 760
	PyModule_AddIntConstant(m, "daylight", _daylight);
	PyModule_AddObject(m, "tzname",
			   Py_BuildValue("(zz)", _tzname[0], _tzname[1]));
761
#endif /* __CYGWIN__ */
762
#endif /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/
763 764 765 766
}


static PyMethodDef time_methods[] = {
767
	{"time",	time_time, METH_NOARGS, time_doc},
768
#ifdef HAVE_CLOCK
769
	{"clock",	time_clock, METH_NOARGS, clock_doc},
770 771 772 773 774 775 776
#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
777
	{"mktime",	time_mktime, METH_O, mktime_doc},
778 779 780 781 782 783
#endif
#ifdef HAVE_STRFTIME
	{"strftime",	time_strftime, METH_VARARGS, strftime_doc},
#endif
	{"strptime",	time_strptime, METH_VARARGS, strptime_doc},
#ifdef HAVE_WORKING_TZSET
784
	{"tzset",	time_tzset, METH_NOARGS, tzset_doc},
785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841
#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);
842 843
	if (m == NULL)
		return;
844 845 846 847 848 849 850 851 852 853 854

	/* 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);

855 856 857 858 859 860 861 862 863
#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 */
864
	if (!initialized) {
865
		PyStructSequence_InitType(&StructTimeType,
866 867
					  &struct_time_type_desc);
	}
868 869
	Py_INCREF(&StructTimeType);
	PyModule_AddObject(m, "struct_time", (PyObject*) &StructTimeType);
870
	initialized = 1;
Guido van Rossum's avatar
Guido van Rossum committed
871 872 873
}


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

876
static double
877
floattime(void)
Guido van Rossum's avatar
Guido van Rossum committed
878
{
879
	/* There are three ways to get the time:
880 881 882 883 884 885 886
	  (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! */
887
#ifdef HAVE_GETTIMEOFDAY
888 889
	{
		struct timeval t;
890
#ifdef GETTIMEOFDAY_NO_TZ
891 892
		if (gettimeofday(&t) == 0)
			return (double)t.tv_sec + t.tv_usec*0.000001;
893
#else /* !GETTIMEOFDAY_NO_TZ */
894 895
		if (gettimeofday(&t, (struct timezone *)NULL) == 0)
			return (double)t.tv_sec + t.tv_usec*0.000001;
896
#endif /* !GETTIMEOFDAY_NO_TZ */
897
	}
898

899
#endif /* !HAVE_GETTIMEOFDAY */
900
	{
901
#if defined(HAVE_FTIME)
902 903 904
		struct timeb t;
		ftime(&t);
		return (double)t.time + (double)t.millitm * (double)0.001;
905
#else /* !HAVE_FTIME */
906 907 908
		time_t secs;
		time(&secs);
		return (double)secs;
909
#endif /* !HAVE_FTIME */
910
	}
Guido van Rossum's avatar
Guido van Rossum committed
911 912
}

913

914 915 916
/* Implement floatsleep() for various platforms.
   When interrupted (or when another error occurs), return -1 and
   set an exception; else return 0. */
917

918
static int
Guido van Rossum's avatar
Guido van Rossum committed
919
floatsleep(double secs)
Guido van Rossum's avatar
Guido van Rossum committed
920
{
921
/* XXX Should test for MS_WINDOWS first! */
922
#if defined(HAVE_SELECT) && !defined(__BEOS__) && !defined(__EMX__)
Guido van Rossum's avatar
Guido van Rossum committed
923
	struct timeval t;
924 925 926 927 928
	double frac;
	frac = fmod(secs, 1.0);
	secs = floor(secs);
	t.tv_sec = (long)secs;
	t.tv_usec = (long)(frac*1000000.0);
929
	Py_BEGIN_ALLOW_THREADS
930
	if (select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &t) != 0) {
931
#ifdef EINTR
932
		if (errno != EINTR) {
933 934 935
#else
		if (1) {
#endif
936
			Py_BLOCK_THREADS
937 938 939
			PyErr_SetFromErrno(PyExc_IOError);
			return -1;
		}
940
	}
941
	Py_END_ALLOW_THREADS
942
#elif defined(__WATCOMC__) && !defined(__QNX__)
Guido van Rossum's avatar
Guido van Rossum committed
943
	/* XXX Can't interrupt this sleep */
944
	Py_BEGIN_ALLOW_THREADS
Guido van Rossum's avatar
Guido van Rossum committed
945
	delay((int)(secs * 1000 + 0.5));  /* delay() uses milliseconds */
946
	Py_END_ALLOW_THREADS
947
#elif defined(MS_WINDOWS)
948 949
	{
		double millisecs = secs * 1000.0;
950 951
		unsigned long ul_millis;

952
		if (millisecs > (double)ULONG_MAX) {
953 954
			PyErr_SetString(PyExc_OverflowError,
					"sleep length is too large");
955 956 957
			return -1;
		}
		Py_BEGIN_ALLOW_THREADS
958 959 960 961 962 963 964
		/* 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);
965 966 967
		else {
			DWORD rc;
			ResetEvent(hInterruptEvent);
968 969 970 971 972
			rc = WaitForSingleObject(hInterruptEvent, ul_millis);
			if (rc == WAIT_OBJECT_0) {
				/* Yield to make sure real Python signal
				 * handler called.
				 */
973 974 975 976 977 978 979
				Sleep(1);
				Py_BLOCK_THREADS
				errno = EINTR;
				PyErr_SetFromErrno(PyExc_IOError);
				return -1;
			}
		}
980 981
		Py_END_ALLOW_THREADS
	}
982
#elif defined(PYOS_OS2)
983
	/* This Sleep *IS* Interruptable by Exceptions */
984
	Py_BEGIN_ALLOW_THREADS
985
	if (DosSleep(secs * 1000) != NO_ERROR) {
986
		Py_BLOCK_THREADS
987 988 989
		PyErr_SetFromErrno(PyExc_IOError);
		return -1;
	}
990
	Py_END_ALLOW_THREADS
991
#elif defined(__BEOS__)
992 993 994 995 996
	/* This sleep *CAN BE* interrupted. */
	{
		if( secs <= 0.0 ) {
			return;
		}
997

998
		Py_BEGIN_ALLOW_THREADS
999 1000
		/* BeOS snooze() is in microseconds... */
		if( snooze( (bigtime_t)( secs * 1000.0 * 1000.0 ) ) == B_INTERRUPTED ) {
1001 1002 1003 1004 1005 1006
			Py_BLOCK_THREADS
			PyErr_SetFromErrno( PyExc_IOError );
			return -1;
		}
		Py_END_ALLOW_THREADS
	}
1007
#elif defined(RISCOS)
1008 1009 1010 1011
	if (secs <= 0.0)
		return 0;
	Py_BEGIN_ALLOW_THREADS
	/* This sleep *CAN BE* interrupted. */
1012
	if ( riscos_sleep(secs) )
1013 1014
		return -1;
	Py_END_ALLOW_THREADS
1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031
#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
1032
	/* XXX Can't interrupt this sleep */
1033
	Py_BEGIN_ALLOW_THREADS
1034
	sleep((int)secs);
1035
	Py_END_ALLOW_THREADS
1036
#endif
1037

1038
	return 0;
1039
}
1040 1041