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