12 /* GUSI, the I/O library which has the time() function and such uses the
13 ** Mac epoch of 1904. MSL, the C library which has localtime() and so uses
14 ** the ANSI epoch of 1900.
16 #define GUSI_TO_MSL_EPOCH (4*365*24*60*60)
17 #endif /* USE_GUSI2 */
19 #include <sys/types.h>
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 */
37 #if defined(__WATCOMC__) && !defined(__QNX__)
43 /* These overrides not needed for Win32 */
44 #define timezone _timezone
45 #define tzname _tzname
46 #define daylight _daylight
47 #define altzone _altzone
49 #endif /* MS_WINDOWS */
50 #endif /* !__WATCOMC__ || __QNX__ */
52 #if defined(MS_WIN32) && !defined(MS_WIN64)
53 /* Win32 has better clock replacement
54 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_WIN32 && !MS_WIN64 */
59 #if defined(PYCC_VACPP)
65 /* For bigtime_t, snooze(). - [cjh] */
66 #include <support/SupportDefs.h>
67 #include <kernel/OS.h>
70 /* Forward declarations */
71 static int floatsleep(double);
72 static double floattime(void);
75 static PyObject
*moddict
;
78 /* Our own timezone. We have enough information to deduce whether
79 ** DST is on currently, but unfortunately we cannot put it to good
80 ** use because we don't know the rules (and that is needed to have
81 ** localtime() return correct tm_isdst values for times other than
82 ** the current time. So, we cop out and only tell the user the current
95 if (loc
.latitude
== 0 && loc
.longitude
== 0 && loc
.u
.gmtDelta
== 0)
98 delta
= loc
.u
.gmtDelta
& 0x00FFFFFF;
100 if (delta
& 0x00800000)
105 #endif /* macintosh */
109 time_time(PyObject
*self
, PyObject
*args
)
112 if (!PyArg_NoArgs(args
))
116 PyErr_SetFromErrno(PyExc_IOError
);
119 return PyFloat_FromDouble(secs
);
122 static char time_doc
[] =
123 "time() -> floating point number\n\
125 Return the current time in seconds since the Epoch.\n\
126 Fractions of a second may be present if the system clock provides them.";
130 #ifndef CLOCKS_PER_SEC
132 #define CLOCKS_PER_SEC CLK_TCK
134 #define CLOCKS_PER_SEC 1000000
139 time_clock(PyObject
*self
, PyObject
*args
)
141 if (!PyArg_NoArgs(args
))
143 return PyFloat_FromDouble(((double)clock()) / CLOCKS_PER_SEC
);
145 #endif /* HAVE_CLOCK */
147 #if defined(MS_WIN32) && !defined(MS_WIN64)
148 /* Due to Mark Hammond */
150 time_clock(PyObject
*self
, PyObject
*args
)
152 static LARGE_INTEGER ctrStart
;
153 static LARGE_INTEGER divisor
= {0,0};
154 LARGE_INTEGER now
, diff
, rem
;
156 if (!PyArg_NoArgs(args
))
159 if (LargeIntegerEqualToZero(divisor
)) {
160 QueryPerformanceCounter(&ctrStart
);
161 if (!QueryPerformanceFrequency(&divisor
) ||
162 LargeIntegerEqualToZero(divisor
)) {
163 /* Unlikely to happen -
164 this works on all intel machines at least!
166 return PyFloat_FromDouble(clock());
169 QueryPerformanceCounter(&now
);
170 diff
= LargeIntegerSubtract(now
, ctrStart
);
171 diff
= LargeIntegerDivide(diff
, divisor
, &rem
);
172 /* XXX - we assume both divide results fit in 32 bits. This is
173 true on Intels. First person who can afford a machine that
174 doesnt deserves to fix it :-)
176 return PyFloat_FromDouble((double)diff
.LowPart
+
177 ((double)rem
.LowPart
/ (double)divisor
.LowPart
));
180 #define HAVE_CLOCK /* So it gets included in the methods */
181 #endif /* MS_WIN32 && !MS_WIN64 */
184 static char clock_doc
[] =
185 "clock() -> floating point number\n\
187 Return the CPU time or real time since the start of the process or since\n\
188 the first call to clock(). This has as much precision as the system records.";
192 time_sleep(PyObject
*self
, PyObject
*args
)
195 if (!PyArg_Parse(args
, "d", &secs
))
197 if (floatsleep(secs
) != 0)
203 static char sleep_doc
[] =
206 Delay execution for a given number of seconds. The argument may be\n\
207 a floating point number for subsecond precision.";
210 tmtotuple(struct tm
*p
)
212 return Py_BuildValue("(iiiiiiiii)",
214 p
->tm_mon
+ 1, /* Want January == 1 */
219 (p
->tm_wday
+ 6) % 7, /* Want Monday == 0 */
220 p
->tm_yday
+ 1, /* Want January, 1 == 1 */
225 time_convert(time_t when
, struct tm
* (*function
)(const time_t *))
229 #if defined(macintosh) && defined(USE_GUSI204)
230 when
= when
+ GUSI_TO_MSL_EPOCH
;
238 return PyErr_SetFromErrno(PyExc_IOError
);
244 time_gmtime(PyObject
*self
, PyObject
*args
)
247 if (!PyArg_Parse(args
, "d", &when
))
249 return time_convert((time_t)when
, gmtime
);
252 static char gmtime_doc
[] =
253 "gmtime(seconds) -> tuple\n\
255 Convert seconds since the Epoch to a time tuple expressing UTC (a.k.a. GMT).";
258 time_localtime(PyObject
*self
, PyObject
*args
)
261 if (!PyArg_Parse(args
, "d", &when
))
263 return time_convert((time_t)when
, localtime
);
266 static char localtime_doc
[] =
267 "localtime(seconds) -> tuple\n\
268 Convert seconds since the Epoch to a time tuple expressing local time.";
271 gettmarg(PyObject
*args
, struct tm
*p
)
274 memset((void *) p
, '\0', sizeof(struct tm
));
276 if (!PyArg_Parse(args
, "(iiiiiiiii)",
288 PyObject
*accept
= PyDict_GetItemString(moddict
,
290 if (accept
== NULL
|| !PyInt_Check(accept
) ||
291 PyInt_AsLong(accept
) == 0) {
292 PyErr_SetString(PyExc_ValueError
,
293 "year >= 1900 required");
296 if (69 <= y
&& y
<= 99)
298 else if (0 <= y
&& y
<= 68)
301 PyErr_SetString(PyExc_ValueError
,
302 "year out of range (00-99, 1900-*)");
306 p
->tm_year
= y
- 1900;
308 p
->tm_wday
= (p
->tm_wday
+ 1) % 7;
315 time_strftime(PyObject
*self
, PyObject
*args
)
320 size_t fmtlen
, buflen
;
324 memset((void *) &buf
, '\0', sizeof(buf
));
326 if (!PyArg_ParseTuple(args
, "sO:strftime", &fmt
, &tup
)
327 || !gettmarg(tup
, &buf
))
329 fmtlen
= strlen(fmt
);
331 /* I hate these functions that presume you know how big the output
332 * will be ahead of time...
334 for (i
= 1024; ; i
+= i
) {
336 if (outbuf
== NULL
) {
337 return PyErr_NoMemory();
339 buflen
= strftime(outbuf
, i
, fmt
, &buf
);
340 if (buflen
> 0 || i
>= 256 * fmtlen
) {
341 /* If the buffer is 256 times as long as the format,
342 it's probably not failing for lack of room!
343 More likely, the format yields an empty result,
344 e.g. an empty format, or %Z when the timezone
347 ret
= PyString_FromStringAndSize(outbuf
, buflen
);
355 static char strftime_doc
[] =
356 "strftime(format, tuple) -> string\n\
358 Convert a time tuple to a string according to a format specification.\n\
359 See the library reference manual for formatting codes.";
360 #endif /* HAVE_STRFTIME */
365 /* Enable this if it's not declared in <time.h> */
366 extern char *strptime(const char *, const char *, struct tm
*);
370 time_strptime(PyObject
*self
, PyObject
*args
)
373 char *fmt
= "%a %b %d %H:%M:%S %Y";
377 if (!PyArg_ParseTuple(args
, "s|s:strptime", &buf
, &fmt
))
379 memset((void *) &tm
, '\0', sizeof(tm
));
380 s
= strptime(buf
, fmt
, &tm
);
382 PyErr_SetString(PyExc_ValueError
, "format mismatch");
385 while (*s
&& isspace(*s
))
388 PyErr_Format(PyExc_ValueError
,
389 "unconverted data remains: '%.400s'", s
);
392 return tmtotuple(&tm
);
395 static char strptime_doc
[] =
396 "strptime(string, format) -> tuple\n\
397 Parse a string to a time tuple according to a format specification.\n\
398 See the library reference manual for formatting codes (same as strftime()).";
399 #endif /* HAVE_STRPTIME */
402 time_asctime(PyObject
*self
, PyObject
*args
)
407 if (!PyArg_ParseTuple(args
, "O:asctime", &tup
))
409 if (!gettmarg(tup
, &buf
))
414 return PyString_FromString(p
);
417 static char asctime_doc
[] =
418 "asctime(tuple) -> string\n\
420 Convert a time tuple to a string, e.g. 'Sat Jun 06 16:26:11 1998'.";
423 time_ctime(PyObject
*self
, PyObject
*args
)
428 if (!PyArg_Parse(args
, "d", &dt
))
431 #if defined(macintosh) && defined(USE_GUSI204)
432 tt
= tt
+ GUSI_TO_MSL_EPOCH
;
436 PyErr_SetString(PyExc_ValueError
, "unconvertible time");
441 return PyString_FromString(p
);
444 static char ctime_doc
[] =
445 "ctime(seconds) -> string\n\
447 Convert a time in seconds since the Epoch to a string in local time.\n\
448 This is equivalent to asctime(localtime(seconds)).";
452 time_mktime(PyObject
*self
, PyObject
*args
)
457 if (!PyArg_ParseTuple(args
, "O:mktime", &tup
))
460 buf
= *localtime(&tt
);
461 if (!gettmarg(tup
, &buf
))
464 if (tt
== (time_t)(-1)) {
465 PyErr_SetString(PyExc_OverflowError
,
466 "mktime argument out of range");
469 #if defined(macintosh) && defined(USE_GUSI2)
470 tt
= tt
- GUSI_TO_MSL_EPOCH
;
472 return PyFloat_FromDouble((double)tt
);
475 static char mktime_doc
[] =
476 "mktime(tuple) -> floating point number\n\
478 Convert a time tuple in local time to seconds since the Epoch.";
479 #endif /* HAVE_MKTIME */
481 static PyMethodDef time_methods
[] = {
482 {"time", time_time
, METH_OLDARGS
, time_doc
},
484 {"clock", time_clock
, METH_OLDARGS
, clock_doc
},
486 {"sleep", time_sleep
, METH_OLDARGS
, sleep_doc
},
487 {"gmtime", time_gmtime
, METH_OLDARGS
, gmtime_doc
},
488 {"localtime", time_localtime
, METH_OLDARGS
, localtime_doc
},
489 {"asctime", time_asctime
, METH_VARARGS
, asctime_doc
},
490 {"ctime", time_ctime
, METH_OLDARGS
, ctime_doc
},
492 {"mktime", time_mktime
, METH_VARARGS
, mktime_doc
},
495 {"strftime", time_strftime
, METH_VARARGS
, strftime_doc
},
498 {"strptime", time_strptime
, METH_VARARGS
, strptime_doc
},
500 {NULL
, NULL
} /* sentinel */
504 ins(PyObject
*d
, char *name
, PyObject
*v
)
506 /* Don't worry too much about errors, they'll be caught by the
507 * caller of inittime().
510 PyDict_SetItemString(d
, name
, v
);
515 static char module_doc
[] =
516 "This module provides various functions to manipulate time values.\n\
518 There are two standard representations of time. One is the number\n\
519 of seconds since the Epoch, in UTC (a.k.a. GMT). It may be an integer\n\
520 or a floating point number (to represent fractions of seconds).\n\
521 The Epoch is system-defined; on Unix, it is generally January 1st, 1970.\n\
522 The actual value can be retrieved by calling gmtime(0).\n\
524 The other representation is a tuple of 9 integers giving local time.\n\
525 The tuple items are:\n\
526 year (four digits, e.g. 1998)\n\
532 weekday (0-6, Monday is 0)\n\
533 Julian day (day in the year, 1-366)\n\
534 DST (Daylight Savings Time) flag (-1, 0 or 1)\n\
535 If the DST flag is 0, the time is given in the regular time zone;\n\
536 if it is 1, the time is given in the DST time zone;\n\
537 if it is -1, mktime() should guess based on the date and time.\n\
541 timezone -- difference in seconds between UTC and local standard time\n\
542 altzone -- difference in seconds between UTC and local DST time\n\
543 daylight -- whether local time should reflect DST\n\
544 tzname -- tuple of (standard time zone name, DST time zone name)\n\
548 time() -- return current time in seconds since the Epoch as a float\n\
549 clock() -- return CPU time since process start as a float\n\
550 sleep() -- delay for a number of seconds given as a float\n\
551 gmtime() -- convert seconds since Epoch to UTC tuple\n\
552 localtime() -- convert seconds since Epoch to local time tuple\n\
553 asctime() -- convert time tuple to string\n\
554 ctime() -- convert time in seconds to string\n\
555 mktime() -- convert local time tuple to seconds since Epoch\n\
556 strftime() -- convert time tuple to string according to format specification\n\
557 strptime() -- parse string to time tuple according to format specification\n\
566 m
= Py_InitModule3("time", time_methods
, module_doc
);
567 d
= PyModule_GetDict(m
);
568 /* Accept 2-digit dates unless PYTHONY2K is set and non-empty */
569 p
= getenv("PYTHONY2K");
570 ins(d
, "accept2dyear", PyInt_FromLong((long) (!p
|| !*p
)));
571 /* Squirrel away the module's dictionary for the y2k check */
574 #if defined(HAVE_TZNAME) && !defined(__GLIBC__)
577 ins(d
, "timezone", PyInt_FromLong((long)_timezone
));
578 #else /* !PYOS_OS2 */
579 ins(d
, "timezone", PyInt_FromLong((long)timezone
));
580 #endif /* PYOS_OS2 */
582 ins(d
, "altzone", PyInt_FromLong((long)altzone
));
585 ins(d
, "altzone", PyInt_FromLong((long)_timezone
-3600));
586 #else /* !PYOS_OS2 */
587 ins(d
, "altzone", PyInt_FromLong((long)timezone
-3600));
588 #endif /* PYOS_OS2 */
590 ins(d
, "daylight", PyInt_FromLong((long)daylight
));
591 ins(d
, "tzname", Py_BuildValue("(zz)", tzname
[0], tzname
[1]));
592 #else /* !HAVE_TZNAME || __GLIBC__ */
595 #define YEAR ((time_t)((365 * 24 + 6) * 3600))
598 long janzone
, julyzone
;
599 char janname
[10], julyname
[10];
600 t
= (time((time_t *)0) / YEAR
) * YEAR
;
602 janzone
= -p
->tm_gmtoff
;
603 strncpy(janname
, p
->tm_zone
? p
->tm_zone
: " ", 9);
607 julyzone
= -p
->tm_gmtoff
;
608 strncpy(julyname
, p
->tm_zone
? p
->tm_zone
: " ", 9);
611 if( janzone
< julyzone
) {
612 /* DST is reversed in the southern hemisphere */
613 ins(d
, "timezone", PyInt_FromLong(julyzone
));
614 ins(d
, "altzone", PyInt_FromLong(janzone
));
616 PyInt_FromLong((long)(janzone
!= julyzone
)));
618 Py_BuildValue("(zz)", julyname
, janname
));
620 ins(d
, "timezone", PyInt_FromLong(janzone
));
621 ins(d
, "altzone", PyInt_FromLong(julyzone
));
623 PyInt_FromLong((long)(janzone
!= julyzone
)));
625 Py_BuildValue("(zz)", janname
, julyname
));
630 /* The only thing we can obtain is the current timezone
631 ** (and whether dst is currently _active_, but that is not what
632 ** we're looking for:-( )
635 ins(d
, "timezone", PyInt_FromLong(timezone
));
636 ins(d
, "altzone", PyInt_FromLong(timezone
));
637 ins(d
, "daylight", PyInt_FromLong((long)0));
638 ins(d
, "tzname", Py_BuildValue("(zz)", "", ""));
639 #endif /* macintosh */
640 #endif /* HAVE_TM_ZONE */
641 #endif /* !HAVE_TZNAME || __GLIBC__ */
645 /* Implement floattime() for various platforms */
650 /* There are three ways to get the time:
651 (1) gettimeofday() -- resolution in microseconds
652 (2) ftime() -- resolution in milliseconds
653 (3) time() -- resolution in seconds
654 In all cases the return value is a float in seconds.
655 Since on some systems (e.g. SCO ODT 3.0) gettimeofday() may
656 fail, so we fall back on ftime() or time().
657 Note: clock resolution does not imply clock accuracy! */
658 #ifdef HAVE_GETTIMEOFDAY
661 #ifdef GETTIMEOFDAY_NO_TZ
662 if (gettimeofday(&t
) == 0)
663 return (double)t
.tv_sec
+ t
.tv_usec
*0.000001;
664 #else /* !GETTIMEOFDAY_NO_TZ */
665 if (gettimeofday(&t
, (struct timezone
*)NULL
) == 0)
666 return (double)t
.tv_sec
+ t
.tv_usec
*0.000001;
667 #endif /* !GETTIMEOFDAY_NO_TZ */
669 #endif /* !HAVE_GETTIMEOFDAY */
671 #if defined(HAVE_FTIME)
674 return (double)t
.time
+ (double)t
.millitm
* (double)0.001;
675 #else /* !HAVE_FTIME */
679 #endif /* !HAVE_FTIME */
684 /* Implement floatsleep() for various platforms.
685 When interrupted (or when another error occurs), return -1 and
686 set an exception; else return 0. */
689 floatsleep(double secs
)
691 /* XXX Should test for MS_WIN32 first! */
692 #if defined(HAVE_SELECT) && !defined(__BEOS__)
695 frac
= fmod(secs
, 1.0);
697 t
.tv_sec
= (long)secs
;
698 t
.tv_usec
= (long)(frac
*1000000.0);
699 Py_BEGIN_ALLOW_THREADS
700 if (select(0, (fd_set
*)0, (fd_set
*)0, (fd_set
*)0, &t
) != 0) {
702 if (errno
!= EINTR
) {
707 PyErr_SetFromErrno(PyExc_IOError
);
712 #else /* !HAVE_SELECT || __BEOS__ */
714 #define MacTicks (* (long *)0x16A)
716 deadline
= MacTicks
+ (long)(secs
* 60.0);
717 while (MacTicks
< deadline
) {
718 /* XXX Should call some yielding function here */
719 if (PyErr_CheckSignals())
722 #else /* !macintosh */
723 #if defined(__WATCOMC__) && !defined(__QNX__)
724 /* XXX Can't interrupt this sleep */
725 Py_BEGIN_ALLOW_THREADS
726 delay((int)(secs
* 1000 + 0.5)); /* delay() uses milliseconds */
728 #else /* !__WATCOMC__ || __QNX__ */
732 extern double fmod(double, double);
733 extern double floor(double);
736 frac
= fmod(secs
, 1.0);
739 t2
.time
= t1
.time
+ (int)secs
;
740 t2
.millitm
= t1
.millitm
+ (int)(frac
*1000.0);
741 while (t2
.millitm
>= 1000) {
747 Py_BEGIN_ALLOW_THREADS
751 if (PyErr_CheckSignals())
754 if (t1
.time
> t2
.time
||
755 t1
.time
== t2
.time
&& t1
.millitm
>= t2
.millitm
)
761 double millisecs
= secs
* 1000.0;
762 if (millisecs
> (double)ULONG_MAX
) {
763 PyErr_SetString(PyExc_OverflowError
, "sleep length is too large");
766 /* XXX Can't interrupt this sleep */
767 Py_BEGIN_ALLOW_THREADS
768 Sleep((unsigned long)millisecs
);
771 #else /* !MS_WIN32 */
773 /* This Sleep *IS* Interruptable by Exceptions */
774 Py_BEGIN_ALLOW_THREADS
775 if (DosSleep(secs
* 1000) != NO_ERROR
) {
777 PyErr_SetFromErrno(PyExc_IOError
);
781 #else /* !PYOS_OS2 */
783 /* This sleep *CAN BE* interrupted. */
789 Py_BEGIN_ALLOW_THREADS
790 /* BeOS snooze() is in microseconds... */
791 if( snooze( (bigtime_t
)( secs
* 1000.0 * 1000.0 ) ) == B_INTERRUPTED
) {
793 PyErr_SetFromErrno( PyExc_IOError
);
798 #else /* !__BEOS__ */
799 /* XXX Can't interrupt this sleep */
800 Py_BEGIN_ALLOW_THREADS
803 #endif /* !__BEOS__ */
804 #endif /* !PYOS_OS2 */
805 #endif /* !MS_WIN32 */
807 #endif /* !__WATCOMC__ || __QNX__ */
808 #endif /* !macintosh */
809 #endif /* !HAVE_SELECT */