1 /***********************************************************
2 Copyright (c) 2000, BeOpen.com.
3 Copyright (c) 1995-2000, Corporation for National Research Initiatives.
4 Copyright (c) 1990-1995, Stichting Mathematisch Centrum.
7 See the file "Misc/COPYRIGHT" for information on usage and
8 redistribution of this file, and for a DISCLAIMER OF ALL WARRANTIES.
9 ******************************************************************/
21 /* GUSI, the I/O library which has the time() function and such uses the
22 ** Mac epoch of 1904. MSL, the C library which has localtime() and so uses
23 ** the ANSI epoch of 1900.
25 #define GUSI_TO_MSL_EPOCH (4*365*24*60*60)
26 #endif /* USE_GUSI2 */
28 #include <sys/types.h>
40 #include <sys/timeb.h>
41 #if !defined(MS_WINDOWS) && !defined(PYOS_OS2)
42 extern int ftime(struct timeb
*);
43 #endif /* MS_WINDOWS */
44 #endif /* HAVE_FTIME */
46 #if defined(__WATCOMC__) && !defined(__QNX__)
52 /* These overrides not needed for Win32 */
53 #define timezone _timezone
54 #define tzname _tzname
55 #define daylight _daylight
56 #define altzone _altzone
58 #endif /* MS_WINDOWS */
59 #endif /* !__WATCOMC__ || __QNX__ */
61 #if defined(MS_WIN32) && !defined(MS_WIN64)
62 /* Win32 has better clock replacement
63 XXX Win64 does not yet, but might when the platform matures. */
65 #undef HAVE_CLOCK /* We have our own version down below */
66 #endif /* MS_WIN32 && !MS_WIN64 */
68 #if defined(PYCC_VACPP)
73 /* For bigtime_t, snooze(). - [cjh] */
74 #include <support/SupportDefs.h>
75 #include <kernel/OS.h>
76 #ifndef CLOCKS_PER_SEC
77 /* C'mon, fix the bloody headers... - [cjh] */
78 #define CLOCKS_PER_SEC 1000
82 /* Forward declarations */
83 static int floatsleep(double);
84 static double floattime(void);
87 static PyObject
*moddict
;
90 /* Our own timezone. We have enough information to deduce whether
91 ** DST is on currently, but unfortunately we cannot put it to good
92 ** use because we don't know the rules (and that is needed to have
93 ** localtime() return correct tm_isdst values for times other than
94 ** the current time. So, we cop out and only tell the user the current
100 initmactimezone(void)
107 if (loc
.latitude
== 0 && loc
.longitude
== 0 && loc
.u
.gmtDelta
== 0)
110 delta
= loc
.u
.gmtDelta
& 0x00FFFFFF;
112 if (delta
& 0x00800000)
117 #endif /* macintosh */
121 time_time(PyObject
*self
, PyObject
*args
)
124 if (!PyArg_NoArgs(args
))
128 PyErr_SetFromErrno(PyExc_IOError
);
131 return PyFloat_FromDouble(secs
);
134 static char time_doc
[] =
135 "time() -> floating point number\n\
137 Return the current time in seconds since the Epoch.\n\
138 Fractions of a second may be present if the system clock provides them.";
142 #ifndef CLOCKS_PER_SEC
144 #define CLOCKS_PER_SEC CLK_TCK
146 #define CLOCKS_PER_SEC 1000000
151 time_clock(PyObject
*self
, PyObject
*args
)
153 if (!PyArg_NoArgs(args
))
155 return PyFloat_FromDouble(((double)clock()) / CLOCKS_PER_SEC
);
157 #endif /* HAVE_CLOCK */
159 #if defined(MS_WIN32) && !defined(MS_WIN64)
160 /* Due to Mark Hammond */
162 time_clock(PyObject
*self
, PyObject
*args
)
164 static LARGE_INTEGER ctrStart
;
165 static LARGE_INTEGER divisor
= {0,0};
166 LARGE_INTEGER now
, diff
, rem
;
168 if (!PyArg_NoArgs(args
))
171 if (LargeIntegerEqualToZero(divisor
)) {
172 QueryPerformanceCounter(&ctrStart
);
173 if (!QueryPerformanceFrequency(&divisor
) ||
174 LargeIntegerEqualToZero(divisor
)) {
175 /* Unlikely to happen -
176 this works on all intel machines at least!
178 return PyFloat_FromDouble(clock());
181 QueryPerformanceCounter(&now
);
182 diff
= LargeIntegerSubtract(now
, ctrStart
);
183 diff
= LargeIntegerDivide(diff
, divisor
, &rem
);
184 /* XXX - we assume both divide results fit in 32 bits. This is
185 true on Intels. First person who can afford a machine that
186 doesnt deserves to fix it :-)
188 return PyFloat_FromDouble((double)diff
.LowPart
+
189 ((double)rem
.LowPart
/ (double)divisor
.LowPart
));
192 #define HAVE_CLOCK /* So it gets included in the methods */
193 #endif /* MS_WIN32 && !MS_WIN64 */
196 static char clock_doc
[] =
197 "clock() -> floating point number\n\
199 Return the CPU time or real time since the start of the process or since\n\
200 the first call to clock(). This has as much precision as the system records.";
204 time_sleep(PyObject
*self
, PyObject
*args
)
207 if (!PyArg_Parse(args
, "d", &secs
))
209 if (floatsleep(secs
) != 0)
215 static char sleep_doc
[] =
218 Delay execution for a given number of seconds. The argument may be\n\
219 a floating point number for subsecond precision.";
222 tmtotuple(struct tm
*p
)
224 return Py_BuildValue("(iiiiiiiii)",
226 p
->tm_mon
+ 1, /* Want January == 1 */
231 (p
->tm_wday
+ 6) % 7, /* Want Monday == 0 */
232 p
->tm_yday
+ 1, /* Want January, 1 == 1 */
237 time_convert(time_t when
, struct tm
* (*function
)(const time_t *))
241 #if defined(macintosh) && defined(USE_GUSI204)
242 when
= when
+ GUSI_TO_MSL_EPOCH
;
250 return PyErr_SetFromErrno(PyExc_IOError
);
256 time_gmtime(PyObject
*self
, PyObject
*args
)
259 if (!PyArg_Parse(args
, "d", &when
))
261 return time_convert((time_t)when
, gmtime
);
264 static char gmtime_doc
[] =
265 "gmtime(seconds) -> tuple\n\
267 Convert seconds since the Epoch to a time tuple expressing UTC (a.k.a. GMT).";
270 time_localtime(PyObject
*self
, PyObject
*args
)
273 if (!PyArg_Parse(args
, "d", &when
))
275 return time_convert((time_t)when
, localtime
);
278 static char localtime_doc
[] =
279 "localtime(seconds) -> tuple\n\
280 Convert seconds since the Epoch to a time tuple expressing local time.";
283 gettmarg(PyObject
*args
, struct tm
*p
)
286 memset((void *) p
, '\0', sizeof(struct tm
));
288 if (!PyArg_Parse(args
, "(iiiiiiiii)",
300 PyObject
*accept
= PyDict_GetItemString(moddict
,
302 if (accept
== NULL
|| !PyInt_Check(accept
) ||
303 PyInt_AsLong(accept
) == 0) {
304 PyErr_SetString(PyExc_ValueError
,
305 "year >= 1900 required");
308 if (69 <= y
&& y
<= 99)
310 else if (0 <= y
&& y
<= 68)
313 PyErr_SetString(PyExc_ValueError
,
314 "year out of range (00-99, 1900-*)");
318 p
->tm_year
= y
- 1900;
320 p
->tm_wday
= (p
->tm_wday
+ 1) % 7;
327 time_strftime(PyObject
*self
, PyObject
*args
)
332 size_t fmtlen
, buflen
;
336 memset((void *) &buf
, '\0', sizeof(buf
));
338 if (!PyArg_ParseTuple(args
, "sO:strftime", &fmt
, &tup
)
339 || !gettmarg(tup
, &buf
))
341 fmtlen
= strlen(fmt
);
343 /* I hate these functions that presume you know how big the output
344 * will be ahead of time...
346 for (i
= 1024; ; i
+= i
) {
348 if (outbuf
== NULL
) {
349 return PyErr_NoMemory();
351 buflen
= strftime(outbuf
, i
, fmt
, &buf
);
352 if (buflen
> 0 || i
>= 256 * fmtlen
) {
353 /* If the buffer is 256 times as long as the format,
354 it's probably not failing for lack of room!
355 More likely, the format yields an empty result,
356 e.g. an empty format, or %Z when the timezone
359 ret
= PyString_FromStringAndSize(outbuf
, buflen
);
367 static char strftime_doc
[] =
368 "strftime(format, tuple) -> string\n\
370 Convert a time tuple to a string according to a format specification.\n\
371 See the library reference manual for formatting codes.";
372 #endif /* HAVE_STRFTIME */
377 /* Enable this if it's not declared in <time.h> */
378 extern char *strptime(const char *, const char *, struct tm
*);
382 time_strptime(PyObject
*self
, PyObject
*args
)
385 char *fmt
= "%a %b %d %H:%M:%S %Y";
389 if (!PyArg_ParseTuple(args
, "s|s:strptime", &buf
, &fmt
))
391 memset((void *) &tm
, '\0', sizeof(tm
));
392 s
= strptime(buf
, fmt
, &tm
);
394 PyErr_SetString(PyExc_ValueError
, "format mismatch");
397 while (*s
&& isspace(*s
))
400 PyErr_Format(PyExc_ValueError
,
401 "unconverted data remains: '%.400s'", s
);
404 return tmtotuple(&tm
);
407 static char strptime_doc
[] =
408 "strptime(string, format) -> tuple\n\
409 Parse a string to a time tuple according to a format specification.\n\
410 See the library reference manual for formatting codes (same as strftime()).";
411 #endif /* HAVE_STRPTIME */
414 time_asctime(PyObject
*self
, PyObject
*args
)
419 if (!PyArg_ParseTuple(args
, "O:asctime", &tup
))
421 if (!gettmarg(tup
, &buf
))
426 return PyString_FromString(p
);
429 static char asctime_doc
[] =
430 "asctime(tuple) -> string\n\
432 Convert a time tuple to a string, e.g. 'Sat Jun 06 16:26:11 1998'.";
435 time_ctime(PyObject
*self
, PyObject
*args
)
440 if (!PyArg_Parse(args
, "d", &dt
))
443 #if defined(macintosh) && defined(USE_GUSI204)
444 tt
= tt
+ GUSI_TO_MSL_EPOCH
;
448 PyErr_SetString(PyExc_ValueError
, "unconvertible time");
453 return PyString_FromString(p
);
456 static char ctime_doc
[] =
457 "ctime(seconds) -> string\n\
459 Convert a time in seconds since the Epoch to a string in local time.\n\
460 This is equivalent to asctime(localtime(seconds)).";
464 time_mktime(PyObject
*self
, PyObject
*args
)
469 if (!PyArg_ParseTuple(args
, "O:mktime", &tup
))
472 buf
= *localtime(&tt
);
473 if (!gettmarg(tup
, &buf
))
476 if (tt
== (time_t)(-1)) {
477 PyErr_SetString(PyExc_OverflowError
,
478 "mktime argument out of range");
481 #if defined(macintosh) && defined(USE_GUSI2)
482 tt
= tt
- GUSI_TO_MSL_EPOCH
;
484 return PyFloat_FromDouble((double)tt
);
487 static char mktime_doc
[] =
488 "mktime(tuple) -> floating point number\n\
490 Convert a time tuple in local time to seconds since the Epoch.";
491 #endif /* HAVE_MKTIME */
493 static PyMethodDef time_methods
[] = {
494 {"time", time_time
, METH_OLDARGS
, time_doc
},
496 {"clock", time_clock
, METH_OLDARGS
, clock_doc
},
498 {"sleep", time_sleep
, METH_OLDARGS
, sleep_doc
},
499 {"gmtime", time_gmtime
, METH_OLDARGS
, gmtime_doc
},
500 {"localtime", time_localtime
, METH_OLDARGS
, localtime_doc
},
501 {"asctime", time_asctime
, METH_VARARGS
, asctime_doc
},
502 {"ctime", time_ctime
, METH_OLDARGS
, ctime_doc
},
504 {"mktime", time_mktime
, METH_VARARGS
, mktime_doc
},
507 {"strftime", time_strftime
, METH_VARARGS
, strftime_doc
},
510 {"strptime", time_strptime
, METH_VARARGS
, strptime_doc
},
512 {NULL
, NULL
} /* sentinel */
516 ins(PyObject
*d
, char *name
, PyObject
*v
)
519 Py_FatalError("Can't initialize time module -- NULL value");
520 if (PyDict_SetItemString(d
, name
, v
) != 0)
522 "Can't initialize time module -- PyDict_SetItemString failed");
526 static char module_doc
[] =
527 "This module provides various functions to manipulate time values.\n\
529 There are two standard representations of time. One is the number\n\
530 of seconds since the Epoch, in UTC (a.k.a. GMT). It may be an integer\n\
531 or a floating point number (to represent fractions of seconds).\n\
532 The Epoch is system-defined; on Unix, it is generally January 1st, 1970.\n\
533 The actual value can be retrieved by calling gmtime(0).\n\
535 The other representation is a tuple of 9 integers giving local time.\n\
536 The tuple items are:\n\
537 year (four digits, e.g. 1998)\n\
543 weekday (0-6, Monday is 0)\n\
544 Julian day (day in the year, 1-366)\n\
545 DST (Daylight Savings Time) flag (-1, 0 or 1)\n\
546 If the DST flag is 0, the time is given in the regular time zone;\n\
547 if it is 1, the time is given in the DST time zone;\n\
548 if it is -1, mktime() should guess based on the date and time.\n\
552 timezone -- difference in seconds between UTC and local standard time\n\
553 altzone -- difference in seconds between UTC and local DST time\n\
554 daylight -- whether local time should reflect DST\n\
555 tzname -- tuple of (standard time zone name, DST time zone name)\n\
559 time() -- return current time in seconds since the Epoch as a float\n\
560 clock() -- return CPU time since process start as a float\n\
561 sleep() -- delay for a number of seconds given as a float\n\
562 gmtime() -- convert seconds since Epoch to UTC tuple\n\
563 localtime() -- convert seconds since Epoch to local time tuple\n\
564 asctime() -- convert time tuple to string\n\
565 ctime() -- convert time in seconds to string\n\
566 mktime() -- convert local time tuple to seconds since Epoch\n\
567 strftime() -- convert time tuple to string according to format specification\n\
568 strptime() -- parse string to time tuple according to format specification\n\
577 m
= Py_InitModule3("time", time_methods
, module_doc
);
578 d
= PyModule_GetDict(m
);
579 /* Accept 2-digit dates unless PYTHONY2K is set and non-empty */
580 p
= getenv("PYTHONY2K");
581 ins(d
, "accept2dyear", PyInt_FromLong((long) (!p
|| !*p
)));
582 /* Squirrel away the module's dictionary for the y2k check */
585 #if defined(HAVE_TZNAME) && !defined(__GLIBC__)
588 ins(d
, "timezone", PyInt_FromLong((long)_timezone
));
589 #else /* !PYOS_OS2 */
590 ins(d
, "timezone", PyInt_FromLong((long)timezone
));
591 #endif /* PYOS_OS2 */
593 ins(d
, "altzone", PyInt_FromLong((long)altzone
));
596 ins(d
, "altzone", PyInt_FromLong((long)_timezone
-3600));
597 #else /* !PYOS_OS2 */
598 ins(d
, "altzone", PyInt_FromLong((long)timezone
-3600));
599 #endif /* PYOS_OS2 */
601 ins(d
, "daylight", PyInt_FromLong((long)daylight
));
602 ins(d
, "tzname", Py_BuildValue("(zz)", tzname
[0], tzname
[1]));
603 #else /* !HAVE_TZNAME || __GLIBC__ */
606 #define YEAR ((time_t)((365 * 24 + 6) * 3600))
609 long janzone
, julyzone
;
610 char janname
[10], julyname
[10];
611 t
= (time((time_t *)0) / YEAR
) * YEAR
;
613 janzone
= -p
->tm_gmtoff
;
614 strncpy(janname
, p
->tm_zone
? p
->tm_zone
: " ", 9);
618 julyzone
= -p
->tm_gmtoff
;
619 strncpy(julyname
, p
->tm_zone
? p
->tm_zone
: " ", 9);
622 if( janzone
< julyzone
) {
623 /* DST is reversed in the southern hemisphere */
624 ins(d
, "timezone", PyInt_FromLong(julyzone
));
625 ins(d
, "altzone", PyInt_FromLong(janzone
));
627 PyInt_FromLong((long)(janzone
!= julyzone
)));
629 Py_BuildValue("(zz)", julyname
, janname
));
631 ins(d
, "timezone", PyInt_FromLong(janzone
));
632 ins(d
, "altzone", PyInt_FromLong(julyzone
));
634 PyInt_FromLong((long)(janzone
!= julyzone
)));
636 Py_BuildValue("(zz)", janname
, julyname
));
641 /* The only thing we can obtain is the current timezone
642 ** (and whether dst is currently _active_, but that is not what
643 ** we're looking for:-( )
646 ins(d
, "timezone", PyInt_FromLong(timezone
));
647 ins(d
, "altzone", PyInt_FromLong(timezone
));
648 ins(d
, "daylight", PyInt_FromLong((long)0));
649 ins(d
, "tzname", Py_BuildValue("(zz)", "", ""));
650 #endif /* macintosh */
651 #endif /* HAVE_TM_ZONE */
652 #endif /* !HAVE_TZNAME || __GLIBC__ */
653 if (PyErr_Occurred())
654 Py_FatalError("Can't initialize time module");
658 /* Implement floattime() for various platforms */
663 /* There are three ways to get the time:
664 (1) gettimeofday() -- resolution in microseconds
665 (2) ftime() -- resolution in milliseconds
666 (3) time() -- resolution in seconds
667 In all cases the return value is a float in seconds.
668 Since on some systems (e.g. SCO ODT 3.0) gettimeofday() may
669 fail, so we fall back on ftime() or time().
670 Note: clock resolution does not imply clock accuracy! */
671 #ifdef HAVE_GETTIMEOFDAY
674 #ifdef GETTIMEOFDAY_NO_TZ
675 if (gettimeofday(&t
) == 0)
676 return (double)t
.tv_sec
+ t
.tv_usec
*0.000001;
677 #else /* !GETTIMEOFDAY_NO_TZ */
678 if (gettimeofday(&t
, (struct timezone
*)NULL
) == 0)
679 return (double)t
.tv_sec
+ t
.tv_usec
*0.000001;
680 #endif /* !GETTIMEOFDAY_NO_TZ */
682 #endif /* !HAVE_GETTIMEOFDAY */
684 #if defined(HAVE_FTIME)
687 return (double)t
.time
+ (double)t
.millitm
* (double)0.001;
688 #else /* !HAVE_FTIME */
692 #endif /* !HAVE_FTIME */
697 /* Implement floatsleep() for various platforms.
698 When interrupted (or when another error occurs), return -1 and
699 set an exception; else return 0. */
702 floatsleep(double secs
)
704 /* XXX Should test for MS_WIN32 first! */
705 #if defined(HAVE_SELECT) && !defined(__BEOS__)
708 frac
= fmod(secs
, 1.0);
710 t
.tv_sec
= (long)secs
;
711 t
.tv_usec
= (long)(frac
*1000000.0);
712 Py_BEGIN_ALLOW_THREADS
713 if (select(0, (fd_set
*)0, (fd_set
*)0, (fd_set
*)0, &t
) != 0) {
715 if (errno
!= EINTR
) {
720 PyErr_SetFromErrno(PyExc_IOError
);
725 #else /* !HAVE_SELECT || __BEOS__ */
727 #define MacTicks (* (long *)0x16A)
729 deadline
= MacTicks
+ (long)(secs
* 60.0);
730 while (MacTicks
< deadline
) {
731 /* XXX Should call some yielding function here */
732 if (PyErr_CheckSignals())
735 #else /* !macintosh */
736 #if defined(__WATCOMC__) && !defined(__QNX__)
737 /* XXX Can't interrupt this sleep */
738 Py_BEGIN_ALLOW_THREADS
739 delay((int)(secs
* 1000 + 0.5)); /* delay() uses milliseconds */
741 #else /* !__WATCOMC__ || __QNX__ */
745 extern double fmod(double, double);
746 extern double floor(double);
749 frac
= fmod(secs
, 1.0);
752 t2
.time
= t1
.time
+ (int)secs
;
753 t2
.millitm
= t1
.millitm
+ (int)(frac
*1000.0);
754 while (t2
.millitm
>= 1000) {
760 Py_BEGIN_ALLOW_THREADS
764 if (PyErr_CheckSignals())
767 if (t1
.time
> t2
.time
||
768 t1
.time
== t2
.time
&& t1
.millitm
>= t2
.millitm
)
774 double millisecs
= secs
* 1000.0;
775 if (millisecs
> (double)ULONG_MAX
) {
776 PyErr_SetString(PyExc_OverflowError
, "sleep length is too large");
779 /* XXX Can't interrupt this sleep */
780 Py_BEGIN_ALLOW_THREADS
781 Sleep((unsigned long)millisecs
);
784 #else /* !MS_WIN32 */
786 /* This Sleep *IS* Interruptable by Exceptions */
787 Py_BEGIN_ALLOW_THREADS
788 if (DosSleep(secs
* 1000) != NO_ERROR
) {
790 PyErr_SetFromErrno(PyExc_IOError
);
794 #else /* !PYOS_OS2 */
796 /* This sleep *CAN BE* interrupted. */
802 Py_BEGIN_ALLOW_THREADS
803 /* BeOS snooze() is in microseconds... */
804 if( snooze( (bigtime_t
)( secs
* 1000.0 * 1000.0 ) ) == B_INTERRUPTED
) {
806 PyErr_SetFromErrno( PyExc_IOError
);
811 #else /* !__BEOS__ */
812 /* XXX Can't interrupt this sleep */
813 Py_BEGIN_ALLOW_THREADS
816 #endif /* !__BEOS__ */
817 #endif /* !PYOS_OS2 */
818 #endif /* !MS_WIN32 */
820 #endif /* !__WATCOMC__ || __QNX__ */
821 #endif /* !macintosh */
822 #endif /* !HAVE_SELECT */