blob: 87e543f788e9894b0127b55d45e020c62b266f7d [file] [log] [blame]
Guido van Rossumf70e43a1991-02-19 12:39:46 +00001
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002/* Time module */
3
Barry Warsaw9a2a8a81996-12-06 23:32:14 +00004#include "Python.h"
Guido van Rossum98bf58f2001-10-18 20:34:25 +00005#include "structseq.h"
Tim Peters1b6f7a92004-06-20 02:50:16 +00006#include "timefuncs.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +00007
Ronald Oussorend06b6f22006-04-23 11:59:25 +00008#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
Guido van Rossum87ce7bb1998-06-09 16:30:31 +000020#include <ctype.h>
21
Guido van Rossumb6775db1994-08-01 11:34:53 +000022#include <sys/types.h>
Guido van Rossum6d946f91992-08-14 13:49:30 +000023
Guido van Rossumb6775db1994-08-01 11:34:53 +000024#ifdef QUICKWIN
25#include <io.h>
26#endif
27
Guido van Rossumb6775db1994-08-01 11:34:53 +000028#ifdef HAVE_FTIME
29#include <sys/timeb.h>
Guido van Rossum8e9ebfd1997-11-22 21:53:48 +000030#if !defined(MS_WINDOWS) && !defined(PYOS_OS2)
Thomas Woutersbd4bc4e2000-07-22 23:57:55 +000031extern int ftime(struct timeb *);
Guido van Rossum52174571996-12-09 18:38:52 +000032#endif /* MS_WINDOWS */
33#endif /* HAVE_FTIME */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000034
Guido van Rossum7bf22de1997-12-02 20:34:19 +000035#if defined(__WATCOMC__) && !defined(__QNX__)
Guido van Rossumbceeac81996-05-23 22:53:47 +000036#include <i86.h>
37#else
Guido van Rossumcac6c721996-09-06 13:34:02 +000038#ifdef MS_WINDOWS
Mark Hammond975e3922002-07-16 01:29:19 +000039#define WIN32_LEAN_AND_MEAN
Guido van Rossum258ccd42001-03-02 06:53:29 +000040#include <windows.h>
Mark Hammond975e3922002-07-16 01:29:19 +000041#include "pythread.h"
42
43/* helper to allow us to interrupt sleep() on Windows*/
44static HANDLE hInterruptEvent = NULL;
45static BOOL WINAPI PyCtrlHandler(DWORD dwCtrlType)
46{
47 SetEvent(hInterruptEvent);
48 /* allow other default handlers to be called.
49 Default Python handler will setup the
50 KeyboardInterrupt exception.
51 */
52 return FALSE;
53}
54static long main_thread;
55
56
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000057#if defined(__BORLANDC__)
Guido van Rossumb2fb3641996-09-07 00:47:35 +000058/* These overrides not needed for Win32 */
Guido van Rossumb6775db1994-08-01 11:34:53 +000059#define timezone _timezone
Guido van Rossumcc081121995-03-14 15:05:41 +000060#define tzname _tzname
61#define daylight _daylight
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000062#endif /* __BORLANDC__ */
Guido van Rossumcac6c721996-09-06 13:34:02 +000063#endif /* MS_WINDOWS */
Guido van Rossum7bf22de1997-12-02 20:34:19 +000064#endif /* !__WATCOMC__ || __QNX__ */
Guido van Rossum234f9421993-06-17 12:35:49 +000065
Tim Peters7a822da2006-05-25 21:50:17 +000066#if defined(MS_WINDOWS) && !defined(__BORLANDC__)
Tim Petersc285e622006-05-25 22:25:25 +000067/* Win32 has better clock replacement; we have our own version below. */
68#undef HAVE_CLOCK
Tim Peters7a822da2006-05-25 21:50:17 +000069#endif /* MS_WINDOWS && !defined(__BORLANDC__) */
Guido van Rossum3917c221997-04-02 05:35:28 +000070
Andrew MacIntyre7bf68332002-03-03 02:59:16 +000071#if defined(PYOS_OS2)
72#define INCL_DOS
73#define INCL_ERRORS
74#include <os2.h>
75#endif
76
Guido van Rossum8e9ebfd1997-11-22 21:53:48 +000077#if defined(PYCC_VACPP)
Guido van Rossum26452411998-09-28 22:07:11 +000078#include <sys/time.h>
Guido van Rossum8e9ebfd1997-11-22 21:53:48 +000079#endif
80
Guido van Rossumbcc20741998-08-04 22:53:56 +000081#ifdef __BEOS__
Fred Drake56221a72000-08-15 18:52:33 +000082#include <time.h>
Guido van Rossumbcc20741998-08-04 22:53:56 +000083/* For bigtime_t, snooze(). - [cjh] */
84#include <support/SupportDefs.h>
85#include <kernel/OS.h>
86#endif
87
Martin v. Löwisa94568a2003-05-10 07:36:56 +000088#ifdef RISCOS
89extern int riscos_sleep(double);
90#endif
91
Guido van Rossum234f9421993-06-17 12:35:49 +000092/* Forward declarations */
Tim Petersdbd9ba62000-07-09 03:09:57 +000093static int floatsleep(double);
Thomas Woutersed77bac2000-07-24 15:26:39 +000094static double floattime(void);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000095
Guido van Rossumcfbaecc1998-08-25 14:51:12 +000096/* For Y2K check */
97static PyObject *moddict;
98
Tim Peters1b6f7a92004-06-20 02:50:16 +000099/* Exposed in timefuncs.h. */
100time_t
Brett Cannon298c3802004-06-19 20:48:43 +0000101_PyTime_DoubleToTimet(double x)
102{
103 time_t result;
104 double diff;
105
106 result = (time_t)x;
107 /* How much info did we lose? time_t may be an integral or
108 * floating type, and we don't know which. If it's integral,
109 * we don't know whether C truncates, rounds, returns the floor,
110 * etc. If we lost a second or more, the C rounding is
111 * unreasonable, or the input just doesn't fit in a time_t;
112 * call it an error regardless. Note that the original cast to
113 * time_t can cause a C error too, but nothing we can do to
114 * worm around that.
115 */
116 diff = x - (double)result;
117 if (diff <= -1.0 || diff >= 1.0) {
118 PyErr_SetString(PyExc_ValueError,
119 "timestamp out of range for platform time_t");
120 result = (time_t)-1;
121 }
122 return result;
123}
124
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000125static PyObject *
Georg Brandl96a8c392006-05-29 21:04:52 +0000126time_time(PyObject *self, PyObject *unused)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000127{
Guido van Rossumb6775db1994-08-01 11:34:53 +0000128 double secs;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000129 secs = floattime();
130 if (secs == 0.0) {
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000131 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossuma2b7f401993-01-04 09:09:59 +0000132 return NULL;
133 }
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000134 return PyFloat_FromDouble(secs);
Guido van Rossumb6775db1994-08-01 11:34:53 +0000135}
136
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000137PyDoc_STRVAR(time_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000138"time() -> floating point number\n\
139\n\
140Return the current time in seconds since the Epoch.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000141Fractions of a second may be present if the system clock provides them.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000142
Guido van Rossumb6775db1994-08-01 11:34:53 +0000143#ifdef HAVE_CLOCK
144
145#ifndef CLOCKS_PER_SEC
Guido van Rossum1b66a4f1996-02-25 04:50:33 +0000146#ifdef CLK_TCK
147#define CLOCKS_PER_SEC CLK_TCK
148#else
Guido van Rossumb6775db1994-08-01 11:34:53 +0000149#define CLOCKS_PER_SEC 1000000
150#endif
Guido van Rossum1b66a4f1996-02-25 04:50:33 +0000151#endif
Guido van Rossumb6775db1994-08-01 11:34:53 +0000152
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000153static PyObject *
Georg Brandl96a8c392006-05-29 21:04:52 +0000154time_clock(PyObject *self, PyObject *unused)
Guido van Rossumb6775db1994-08-01 11:34:53 +0000155{
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000156 return PyFloat_FromDouble(((double)clock()) / CLOCKS_PER_SEC);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000157}
Guido van Rossumb6775db1994-08-01 11:34:53 +0000158#endif /* HAVE_CLOCK */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000159
Tim Petersc285e622006-05-25 22:25:25 +0000160#if defined(MS_WINDOWS) && !defined(__BORLANDC__)
Mark Hammond7ba5e812002-02-12 04:02:33 +0000161/* Due to Mark Hammond and Tim Peters */
Guido van Rossum3917c221997-04-02 05:35:28 +0000162static PyObject *
Georg Brandl96a8c392006-05-29 21:04:52 +0000163time_clock(PyObject *self, PyObject *unused)
Guido van Rossum3917c221997-04-02 05:35:28 +0000164{
Tim Peters9ad4b682002-02-13 05:14:18 +0000165 static LARGE_INTEGER ctrStart;
Mark Hammond7ba5e812002-02-12 04:02:33 +0000166 static double divisor = 0.0;
Tim Peters9ad4b682002-02-13 05:14:18 +0000167 LARGE_INTEGER now;
Mark Hammond7ba5e812002-02-12 04:02:33 +0000168 double diff;
Guido van Rossum3917c221997-04-02 05:35:28 +0000169
Mark Hammond7ba5e812002-02-12 04:02:33 +0000170 if (divisor == 0.0) {
Tim Peters9ad4b682002-02-13 05:14:18 +0000171 LARGE_INTEGER freq;
172 QueryPerformanceCounter(&ctrStart);
173 if (!QueryPerformanceFrequency(&freq) || freq.QuadPart == 0) {
Mark Hammond7ba5e812002-02-12 04:02:33 +0000174 /* Unlikely to happen - this works on all intel
175 machines at least! Revert to clock() */
Guido van Rossum3917c221997-04-02 05:35:28 +0000176 return PyFloat_FromDouble(clock());
177 }
Tim Peters9ad4b682002-02-13 05:14:18 +0000178 divisor = (double)freq.QuadPart;
Guido van Rossum3917c221997-04-02 05:35:28 +0000179 }
Tim Peters9ad4b682002-02-13 05:14:18 +0000180 QueryPerformanceCounter(&now);
181 diff = (double)(now.QuadPart - ctrStart.QuadPart);
Mark Hammond7ba5e812002-02-12 04:02:33 +0000182 return PyFloat_FromDouble(diff / divisor);
Guido van Rossum3917c221997-04-02 05:35:28 +0000183}
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000184
Guido van Rossum3917c221997-04-02 05:35:28 +0000185#define HAVE_CLOCK /* So it gets included in the methods */
Tim Petersc285e622006-05-25 22:25:25 +0000186#endif /* MS_WINDOWS && !defined(__BORLANDC__) */
Guido van Rossum3917c221997-04-02 05:35:28 +0000187
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000188#ifdef HAVE_CLOCK
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000189PyDoc_STRVAR(clock_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000190"clock() -> floating point number\n\
191\n\
192Return the CPU time or real time since the start of the process or since\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000193the first call to clock(). This has as much precision as the system\n\
194records.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000195#endif
196
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000197static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000198time_sleep(PyObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000199{
Guido van Rossum775f4da1993-01-09 17:18:52 +0000200 double secs;
Thomas Woutersfe385252001-01-19 23:16:56 +0000201 if (!PyArg_ParseTuple(args, "d:sleep", &secs))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000202 return NULL;
Guido van Rossum8607ae21997-11-03 22:04:46 +0000203 if (floatsleep(secs) != 0)
204 return NULL;
205 Py_INCREF(Py_None);
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000206 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000207}
208
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000209PyDoc_STRVAR(sleep_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000210"sleep(seconds)\n\
211\n\
212Delay execution for a given number of seconds. The argument may be\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000213a floating point number for subsecond precision.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000214
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000215static PyStructSequence_Field struct_time_type_fields[] = {
216 {"tm_year", NULL},
217 {"tm_mon", NULL},
218 {"tm_mday", NULL},
219 {"tm_hour", NULL},
220 {"tm_min", NULL},
221 {"tm_sec", NULL},
222 {"tm_wday", NULL},
223 {"tm_yday", NULL},
224 {"tm_isdst", NULL},
225 {0}
226};
227
228static PyStructSequence_Desc struct_time_type_desc = {
Guido van Rossum14648392001-12-08 18:02:58 +0000229 "time.struct_time",
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000230 NULL,
231 struct_time_type_fields,
232 9,
233};
Tim Peters9ad4b682002-02-13 05:14:18 +0000234
Martin v. Löwis19ab6c92006-04-16 18:55:50 +0000235static int initialized;
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000236static PyTypeObject StructTimeType;
237
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000238static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000239tmtotuple(struct tm *p)
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000240{
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000241 PyObject *v = PyStructSequence_New(&StructTimeType);
242 if (v == NULL)
243 return NULL;
Tim Peters9ad4b682002-02-13 05:14:18 +0000244
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000245#define SET(i,val) PyStructSequence_SET_ITEM(v, i, PyInt_FromLong((long) val))
246
247 SET(0, p->tm_year + 1900);
248 SET(1, p->tm_mon + 1); /* Want January == 1 */
249 SET(2, p->tm_mday);
250 SET(3, p->tm_hour);
251 SET(4, p->tm_min);
252 SET(5, p->tm_sec);
253 SET(6, (p->tm_wday + 6) % 7); /* Want Monday == 0 */
254 SET(7, p->tm_yday + 1); /* Want January, 1 == 1 */
255 SET(8, p->tm_isdst);
256#undef SET
257 if (PyErr_Occurred()) {
258 Py_XDECREF(v);
259 return NULL;
260 }
261
262 return v;
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000263}
264
265static PyObject *
Brett Cannon298c3802004-06-19 20:48:43 +0000266time_convert(double when, struct tm * (*function)(const time_t *))
Guido van Rossum234f9421993-06-17 12:35:49 +0000267{
Guido van Rossum6e8583d1996-10-08 14:19:52 +0000268 struct tm *p;
Brett Cannon298c3802004-06-19 20:48:43 +0000269 time_t whent = _PyTime_DoubleToTimet(when);
270
271 if (whent == (time_t)-1 && PyErr_Occurred())
272 return NULL;
Guido van Rossum6e8583d1996-10-08 14:19:52 +0000273 errno = 0;
Brett Cannon298c3802004-06-19 20:48:43 +0000274 p = function(&whent);
Guido van Rossum6e8583d1996-10-08 14:19:52 +0000275 if (p == NULL) {
276#ifdef EINVAL
Guido van Rossum0b1ff661996-11-02 17:31:22 +0000277 if (errno == 0)
Guido van Rossum6e8583d1996-10-08 14:19:52 +0000278 errno = EINVAL;
279#endif
Tim Peters8b19a932003-01-17 20:08:54 +0000280 return PyErr_SetFromErrno(PyExc_ValueError);
Guido van Rossum6e8583d1996-10-08 14:19:52 +0000281 }
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000282 return tmtotuple(p);
Guido van Rossum234f9421993-06-17 12:35:49 +0000283}
284
Fred Drakef901abd2004-08-03 17:58:55 +0000285/* Parse arg tuple that can contain an optional float-or-None value;
286 format needs to be "|O:name".
287 Returns non-zero on success (parallels PyArg_ParseTuple).
288*/
289static int
290parse_time_double_args(PyObject *args, char *format, double *pwhen)
291{
292 PyObject *ot = NULL;
293
294 if (!PyArg_ParseTuple(args, format, &ot))
295 return 0;
296 if (ot == NULL || ot == Py_None)
297 *pwhen = floattime();
298 else {
299 double when = PyFloat_AsDouble(ot);
300 if (PyErr_Occurred())
301 return 0;
302 *pwhen = when;
303 }
304 return 1;
305}
306
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000307static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000308time_gmtime(PyObject *self, PyObject *args)
Guido van Rossum234f9421993-06-17 12:35:49 +0000309{
310 double when;
Fred Drakef901abd2004-08-03 17:58:55 +0000311 if (!parse_time_double_args(args, "|O:gmtime", &when))
Guido van Rossum234f9421993-06-17 12:35:49 +0000312 return NULL;
Brett Cannon298c3802004-06-19 20:48:43 +0000313 return time_convert(when, gmtime);
Guido van Rossum234f9421993-06-17 12:35:49 +0000314}
315
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000316PyDoc_STRVAR(gmtime_doc,
Fred Drake193a3f62002-03-12 21:38:49 +0000317"gmtime([seconds]) -> (tm_year, tm_mon, tm_day, tm_hour, tm_min,\n\
318 tm_sec, tm_wday, tm_yday, tm_isdst)\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000319\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000320Convert seconds since the Epoch to a time tuple expressing UTC (a.k.a.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000321GMT). When 'seconds' is not passed in, convert the current time instead.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000322
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000323static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000324time_localtime(PyObject *self, PyObject *args)
Guido van Rossum234f9421993-06-17 12:35:49 +0000325{
326 double when;
Fred Drakef901abd2004-08-03 17:58:55 +0000327 if (!parse_time_double_args(args, "|O:localtime", &when))
Guido van Rossum234f9421993-06-17 12:35:49 +0000328 return NULL;
Brett Cannon298c3802004-06-19 20:48:43 +0000329 return time_convert(when, localtime);
Guido van Rossum234f9421993-06-17 12:35:49 +0000330}
331
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000332PyDoc_STRVAR(localtime_doc,
Fred Drake193a3f62002-03-12 21:38:49 +0000333"localtime([seconds]) -> (tm_year,tm_mon,tm_day,tm_hour,tm_min,tm_sec,tm_wday,tm_yday,tm_isdst)\n\
Martin v. Löwisb3cfc1d2001-12-02 12:27:43 +0000334\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000335Convert seconds since the Epoch to a time tuple expressing local time.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000336When 'seconds' is not passed in, convert the current time instead.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000337
Guido van Rossum9e90a671993-06-24 11:10:19 +0000338static int
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000339gettmarg(PyObject *args, struct tm *p)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000340{
Guido van Rossumcfbaecc1998-08-25 14:51:12 +0000341 int y;
Thomas Wouters334fb892000-07-25 12:56:38 +0000342 memset((void *) p, '\0', sizeof(struct tm));
Guido van Rossumcfbaecc1998-08-25 14:51:12 +0000343
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000344 if (!PyArg_Parse(args, "(iiiiiiiii)",
Guido van Rossumcfbaecc1998-08-25 14:51:12 +0000345 &y,
Barry Warsaw4a6cf411997-01-13 22:44:55 +0000346 &p->tm_mon,
347 &p->tm_mday,
348 &p->tm_hour,
349 &p->tm_min,
350 &p->tm_sec,
351 &p->tm_wday,
352 &p->tm_yday,
353 &p->tm_isdst))
Guido van Rossum9e90a671993-06-24 11:10:19 +0000354 return 0;
Guido van Rossumcfbaecc1998-08-25 14:51:12 +0000355 if (y < 1900) {
356 PyObject *accept = PyDict_GetItemString(moddict,
357 "accept2dyear");
358 if (accept == NULL || !PyInt_Check(accept) ||
359 PyInt_AsLong(accept) == 0) {
360 PyErr_SetString(PyExc_ValueError,
361 "year >= 1900 required");
362 return 0;
363 }
364 if (69 <= y && y <= 99)
365 y += 1900;
366 else if (0 <= y && y <= 68)
367 y += 2000;
368 else {
369 PyErr_SetString(PyExc_ValueError,
Skip Montanaro1a10aac2001-08-22 12:39:16 +0000370 "year out of range");
Guido van Rossumcfbaecc1998-08-25 14:51:12 +0000371 return 0;
372 }
373 }
374 p->tm_year = y - 1900;
Guido van Rossum9e90a671993-06-24 11:10:19 +0000375 p->tm_mon--;
376 p->tm_wday = (p->tm_wday + 1) % 7;
377 p->tm_yday--;
378 return 1;
379}
380
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000381#ifdef HAVE_STRFTIME
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000382static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000383time_strftime(PyObject *self, PyObject *args)
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000384{
Thomas Woutersfe385252001-01-19 23:16:56 +0000385 PyObject *tup = NULL;
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000386 struct tm buf;
387 const char *fmt;
Guido van Rossumfa481162000-06-28 21:33:59 +0000388 size_t fmtlen, buflen;
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000389 char *outbuf = 0;
Guido van Rossumfa481162000-06-28 21:33:59 +0000390 size_t i;
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000391
Thomas Wouters334fb892000-07-25 12:56:38 +0000392 memset((void *) &buf, '\0', sizeof(buf));
Guido van Rossum1f41f841998-04-27 19:04:26 +0000393
Thomas Woutersfe385252001-01-19 23:16:56 +0000394 if (!PyArg_ParseTuple(args, "s|O:strftime", &fmt, &tup))
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000395 return NULL;
Thomas Woutersfe385252001-01-19 23:16:56 +0000396
397 if (tup == NULL) {
398 time_t tt = time(NULL);
399 buf = *localtime(&tt);
400 } else if (!gettmarg(tup, &buf))
401 return NULL;
Guido van Rossum10b164a2001-09-25 13:59:01 +0000402
Brett Cannond1080a32004-03-02 04:38:10 +0000403 /* Checks added to make sure strftime() does not crash Python by
404 indexing blindly into some array for a textual representation
405 by some bad index (fixes bug #897625).
Tim Peters1b6f7a92004-06-20 02:50:16 +0000406
Brett Cannond1080a32004-03-02 04:38:10 +0000407 No check for year since handled in gettmarg().
408 */
409 if (buf.tm_mon < 0 || buf.tm_mon > 11) {
410 PyErr_SetString(PyExc_ValueError, "month out of range");
411 return NULL;
412 }
413 if (buf.tm_mday < 1 || buf.tm_mday > 31) {
414 PyErr_SetString(PyExc_ValueError, "day of month out of range");
415 return NULL;
416 }
417 if (buf.tm_hour < 0 || buf.tm_hour > 23) {
418 PyErr_SetString(PyExc_ValueError, "hour out of range");
419 return NULL;
420 }
421 if (buf.tm_min < 0 || buf.tm_min > 59) {
422 PyErr_SetString(PyExc_ValueError, "minute out of range");
423 return NULL;
424 }
425 if (buf.tm_sec < 0 || buf.tm_sec > 61) {
426 PyErr_SetString(PyExc_ValueError, "seconds out of range");
427 return NULL;
428 }
429 /* tm_wday does not need checking of its upper-bound since taking
430 ``% 7`` in gettmarg() automatically restricts the range. */
431 if (buf.tm_wday < 0) {
432 PyErr_SetString(PyExc_ValueError, "day of week out of range");
433 return NULL;
434 }
435 if (buf.tm_yday < 0 || buf.tm_yday > 365) {
436 PyErr_SetString(PyExc_ValueError, "day of year out of range");
437 return NULL;
438 }
439 if (buf.tm_isdst < -1 || buf.tm_isdst > 1) {
440 PyErr_SetString(PyExc_ValueError,
441 "daylight savings flag out of range");
442 return NULL;
443 }
444
Guido van Rossumc222ec21999-02-23 00:00:10 +0000445 fmtlen = strlen(fmt);
446
Barry Warsaw4a6cf411997-01-13 22:44:55 +0000447 /* I hate these functions that presume you know how big the output
448 * will be ahead of time...
449 */
Guido van Rossumc222ec21999-02-23 00:00:10 +0000450 for (i = 1024; ; i += i) {
Anthony Baxter7cbc0f52006-04-13 07:19:01 +0000451 outbuf = (char *)malloc(i);
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000452 if (outbuf == NULL) {
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000453 return PyErr_NoMemory();
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000454 }
Guido van Rossumc222ec21999-02-23 00:00:10 +0000455 buflen = strftime(outbuf, i, fmt, &buf);
456 if (buflen > 0 || i >= 256 * fmtlen) {
457 /* If the buffer is 256 times as long as the format,
458 it's probably not failing for lack of room!
459 More likely, the format yields an empty result,
460 e.g. an empty format, or %Z when the timezone
461 is unknown. */
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000462 PyObject *ret;
Guido van Rossumc222ec21999-02-23 00:00:10 +0000463 ret = PyString_FromStringAndSize(outbuf, buflen);
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000464 free(outbuf);
465 return ret;
466 }
467 free(outbuf);
468 }
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000469}
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000470
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000471PyDoc_STRVAR(strftime_doc,
Thomas Woutersfe385252001-01-19 23:16:56 +0000472"strftime(format[, tuple]) -> string\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000473\n\
474Convert a time tuple to a string according to a format specification.\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000475See the library reference manual for formatting codes. When the time tuple\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000476is not present, current time as returned by localtime() is used.");
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000477#endif /* HAVE_STRFTIME */
478
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000479static PyObject *
480time_strptime(PyObject *self, PyObject *args)
481{
482 PyObject *strptime_module = PyImport_ImportModule("_strptime");
Raymond Hettinger502168a2003-04-10 16:03:22 +0000483 PyObject *strptime_result;
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000484
Tim Peters513a1cd2003-01-19 04:54:58 +0000485 if (!strptime_module)
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000486 return NULL;
Raymond Hettinger502168a2003-04-10 16:03:22 +0000487 strptime_result = PyObject_CallMethod(strptime_module, "strptime", "O", args);
488 Py_DECREF(strptime_module);
489 return strptime_result;
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000490}
491
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000492PyDoc_STRVAR(strptime_doc,
Brett Cannon20def8b2003-07-01 05:16:08 +0000493"strptime(string, format) -> struct_time\n\
Martin v. Löwisb3cfc1d2001-12-02 12:27:43 +0000494\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000495Parse a string to a time tuple according to a format specification.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000496See the library reference manual for formatting codes (same as strftime()).");
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000497
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000498
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000499static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000500time_asctime(PyObject *self, PyObject *args)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000501{
Thomas Woutersfe385252001-01-19 23:16:56 +0000502 PyObject *tup = NULL;
Guido van Rossum9e90a671993-06-24 11:10:19 +0000503 struct tm buf;
504 char *p;
Georg Brandl96a8c392006-05-29 21:04:52 +0000505 if (!PyArg_UnpackTuple(args, "asctime", 0, 1, &tup))
Guido van Rossumb2b42dd2000-01-12 16:38:20 +0000506 return NULL;
Thomas Woutersfe385252001-01-19 23:16:56 +0000507 if (tup == NULL) {
508 time_t tt = time(NULL);
509 buf = *localtime(&tt);
510 } else if (!gettmarg(tup, &buf))
Guido van Rossum9e90a671993-06-24 11:10:19 +0000511 return NULL;
512 p = asctime(&buf);
513 if (p[24] == '\n')
514 p[24] = '\0';
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000515 return PyString_FromString(p);
Guido van Rossum9e90a671993-06-24 11:10:19 +0000516}
517
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000518PyDoc_STRVAR(asctime_doc,
Thomas Woutersfe385252001-01-19 23:16:56 +0000519"asctime([tuple]) -> string\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000520\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000521Convert a time tuple to a string, e.g. 'Sat Jun 06 16:26:11 1998'.\n\
522When the time tuple is not present, current time as returned by localtime()\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000523is used.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000524
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000525static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000526time_ctime(PyObject *self, PyObject *args)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000527{
Fred Drakef901abd2004-08-03 17:58:55 +0000528 PyObject *ot = NULL;
Guido van Rossum9e90a671993-06-24 11:10:19 +0000529 time_t tt;
530 char *p;
Guido van Rossum10b164a2001-09-25 13:59:01 +0000531
Georg Brandl96a8c392006-05-29 21:04:52 +0000532 if (!PyArg_UnpackTuple(args, "ctime", 0, 1, &ot))
Fred Drakef901abd2004-08-03 17:58:55 +0000533 return NULL;
534 if (ot == NULL || ot == Py_None)
Thomas Woutersfe385252001-01-19 23:16:56 +0000535 tt = time(NULL);
536 else {
Fred Drakef901abd2004-08-03 17:58:55 +0000537 double dt = PyFloat_AsDouble(ot);
538 if (PyErr_Occurred())
Thomas Woutersfe385252001-01-19 23:16:56 +0000539 return NULL;
Brett Cannon298c3802004-06-19 20:48:43 +0000540 tt = _PyTime_DoubleToTimet(dt);
541 if (tt == (time_t)-1 && PyErr_Occurred())
542 return NULL;
Thomas Woutersfe385252001-01-19 23:16:56 +0000543 }
Guido van Rossum9e90a671993-06-24 11:10:19 +0000544 p = ctime(&tt);
Guido van Rossum78535701998-03-03 22:19:10 +0000545 if (p == NULL) {
546 PyErr_SetString(PyExc_ValueError, "unconvertible time");
547 return NULL;
548 }
Guido van Rossum9e90a671993-06-24 11:10:19 +0000549 if (p[24] == '\n')
550 p[24] = '\0';
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000551 return PyString_FromString(p);
Guido van Rossum9e90a671993-06-24 11:10:19 +0000552}
553
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000554PyDoc_STRVAR(ctime_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000555"ctime(seconds) -> string\n\
556\n\
557Convert a time in seconds since the Epoch to a string in local time.\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000558This is equivalent to asctime(localtime(seconds)). When the time tuple is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000559not present, current time as returned by localtime() is used.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000560
Guido van Rossum60cd8131998-03-06 17:16:21 +0000561#ifdef HAVE_MKTIME
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000562static PyObject *
Georg Brandl96a8c392006-05-29 21:04:52 +0000563time_mktime(PyObject *self, PyObject *tup)
Guido van Rossum234f9421993-06-17 12:35:49 +0000564{
565 struct tm buf;
Guido van Rossumbceeac81996-05-23 22:53:47 +0000566 time_t tt;
567 tt = time(&tt);
568 buf = *localtime(&tt);
Guido van Rossumb2b42dd2000-01-12 16:38:20 +0000569 if (!gettmarg(tup, &buf))
Guido van Rossum234f9421993-06-17 12:35:49 +0000570 return NULL;
Guido van Rossumbceeac81996-05-23 22:53:47 +0000571 tt = mktime(&buf);
572 if (tt == (time_t)(-1)) {
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000573 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum10b164a2001-09-25 13:59:01 +0000574 "mktime argument out of range");
Guido van Rossumbceeac81996-05-23 22:53:47 +0000575 return NULL;
576 }
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000577 return PyFloat_FromDouble((double)tt);
Guido van Rossum234f9421993-06-17 12:35:49 +0000578}
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000579
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000580PyDoc_STRVAR(mktime_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000581"mktime(tuple) -> floating point number\n\
582\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000583Convert a time tuple in local time to seconds since the Epoch.");
Guido van Rossum60cd8131998-03-06 17:16:21 +0000584#endif /* HAVE_MKTIME */
Guido van Rossum234f9421993-06-17 12:35:49 +0000585
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000586#ifdef HAVE_WORKING_TZSET
587void inittimezone(PyObject *module);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000588
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000589static PyObject *
Georg Brandl96a8c392006-05-29 21:04:52 +0000590time_tzset(PyObject *self, PyObject *unused)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000591{
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000592 PyObject* m;
Fred Drake9bb74322002-04-01 14:49:59 +0000593
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000594 m = PyImport_ImportModule("time");
595 if (m == NULL) {
596 return NULL;
597 }
598
599 tzset();
600
601 /* Reset timezone, altzone, daylight and tzname */
602 inittimezone(m);
603 Py_DECREF(m);
Tim Peters1b6f7a92004-06-20 02:50:16 +0000604
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000605 Py_INCREF(Py_None);
606 return Py_None;
607}
608
609PyDoc_STRVAR(tzset_doc,
610"tzset(zone)\n\
611\n\
612Initialize, or reinitialize, the local timezone to the value stored in\n\
613os.environ['TZ']. The TZ environment variable should be specified in\n\
Neal Norwitzdc8e1942004-07-20 22:34:37 +0000614standard Unix timezone format as documented in the tzset man page\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000615(eg. 'US/Eastern', 'Europe/Amsterdam'). Unknown timezones will silently\n\
616fall back to UTC. If the TZ environment variable is not set, the local\n\
617timezone is set to the systems best guess of wallclock time.\n\
618Changing the TZ environment variable without calling tzset *may* change\n\
619the local timezone used by methods such as localtime, but this behaviour\n\
620should not be relied on.");
621#endif /* HAVE_WORKING_TZSET */
622
623void inittimezone(PyObject *m) {
624 /* This code moved from inittime wholesale to allow calling it from
625 time_tzset. In the future, some parts of it can be moved back
626 (for platforms that don't HAVE_WORKING_TZSET, when we know what they
627 are), and the extranious calls to tzset(3) should be removed.
628 I havn't done this yet, as I don't want to change this code as
629 little as possible when introducing the time.tzset and time.tzsetwall
630 methods. This should simply be a method of doing the following once,
631 at the top of this function and removing the call to tzset() from
632 time_tzset():
633
634 #ifdef HAVE_TZSET
635 tzset()
636 #endif
637
638 And I'm lazy and hate C so nyer.
639 */
Guido van Rossum10b164a2001-09-25 13:59:01 +0000640#if defined(HAVE_TZNAME) && !defined(__GLIBC__) && !defined(__CYGWIN__)
Guido van Rossum234f9421993-06-17 12:35:49 +0000641 tzset();
Guido van Rossum26452411998-09-28 22:07:11 +0000642#ifdef PYOS_OS2
Fred Drake9bb74322002-04-01 14:49:59 +0000643 PyModule_AddIntConstant(m, "timezone", _timezone);
Guido van Rossum26452411998-09-28 22:07:11 +0000644#else /* !PYOS_OS2 */
Fred Drake9bb74322002-04-01 14:49:59 +0000645 PyModule_AddIntConstant(m, "timezone", timezone);
Guido van Rossum26452411998-09-28 22:07:11 +0000646#endif /* PYOS_OS2 */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000647#ifdef HAVE_ALTZONE
Fred Drake9bb74322002-04-01 14:49:59 +0000648 PyModule_AddIntConstant(m, "altzone", altzone);
Guido van Rossumb6775db1994-08-01 11:34:53 +0000649#else
Guido van Rossum26452411998-09-28 22:07:11 +0000650#ifdef PYOS_OS2
Fred Drake9bb74322002-04-01 14:49:59 +0000651 PyModule_AddIntConstant(m, "altzone", _timezone-3600);
Guido van Rossum26452411998-09-28 22:07:11 +0000652#else /* !PYOS_OS2 */
Fred Drake9bb74322002-04-01 14:49:59 +0000653 PyModule_AddIntConstant(m, "altzone", timezone-3600);
Guido van Rossum26452411998-09-28 22:07:11 +0000654#endif /* PYOS_OS2 */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000655#endif
Fred Drake9bb74322002-04-01 14:49:59 +0000656 PyModule_AddIntConstant(m, "daylight", daylight);
657 PyModule_AddObject(m, "tzname",
658 Py_BuildValue("(zz)", tzname[0], tzname[1]));
Guido van Rossum10b164a2001-09-25 13:59:01 +0000659#else /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/
Martin v. Löwis60a5d722002-10-16 20:28:25 +0000660#ifdef HAVE_STRUCT_TM_TM_ZONE
Guido van Rossum234f9421993-06-17 12:35:49 +0000661 {
662#define YEAR ((time_t)((365 * 24 + 6) * 3600))
663 time_t t;
664 struct tm *p;
Guido van Rossum57731601999-03-29 19:12:04 +0000665 long janzone, julyzone;
666 char janname[10], julyname[10];
Guido van Rossum234f9421993-06-17 12:35:49 +0000667 t = (time((time_t *)0) / YEAR) * YEAR;
668 p = localtime(&t);
Guido van Rossum57731601999-03-29 19:12:04 +0000669 janzone = -p->tm_gmtoff;
670 strncpy(janname, p->tm_zone ? p->tm_zone : " ", 9);
671 janname[9] = '\0';
Guido van Rossum234f9421993-06-17 12:35:49 +0000672 t += YEAR/2;
673 p = localtime(&t);
Guido van Rossum57731601999-03-29 19:12:04 +0000674 julyzone = -p->tm_gmtoff;
675 strncpy(julyname, p->tm_zone ? p->tm_zone : " ", 9);
676 julyname[9] = '\0';
Guido van Rossum10b164a2001-09-25 13:59:01 +0000677
Guido van Rossum57731601999-03-29 19:12:04 +0000678 if( janzone < julyzone ) {
679 /* DST is reversed in the southern hemisphere */
Fred Drake9bb74322002-04-01 14:49:59 +0000680 PyModule_AddIntConstant(m, "timezone", julyzone);
681 PyModule_AddIntConstant(m, "altzone", janzone);
682 PyModule_AddIntConstant(m, "daylight",
683 janzone != julyzone);
684 PyModule_AddObject(m, "tzname",
685 Py_BuildValue("(zz)",
686 julyname, janname));
Guido van Rossum57731601999-03-29 19:12:04 +0000687 } else {
Fred Drake9bb74322002-04-01 14:49:59 +0000688 PyModule_AddIntConstant(m, "timezone", janzone);
689 PyModule_AddIntConstant(m, "altzone", julyzone);
690 PyModule_AddIntConstant(m, "daylight",
691 janzone != julyzone);
692 PyModule_AddObject(m, "tzname",
693 Py_BuildValue("(zz)",
694 janname, julyname));
Guido van Rossum57731601999-03-29 19:12:04 +0000695 }
Guido van Rossum234f9421993-06-17 12:35:49 +0000696 }
Guido van Rossume6a4b7b1997-10-08 15:27:56 +0000697#else
Martin v. Löwis60a5d722002-10-16 20:28:25 +0000698#endif /* HAVE_STRUCT_TM_TM_ZONE */
Tim Peters26ae7cd2001-03-20 03:26:49 +0000699#ifdef __CYGWIN__
700 tzset();
Fred Drake9bb74322002-04-01 14:49:59 +0000701 PyModule_AddIntConstant(m, "timezone", _timezone);
Georg Brandl378d5922006-05-17 14:26:50 +0000702 PyModule_AddIntConstant(m, "altzone", _timezone-3600);
Fred Drake9bb74322002-04-01 14:49:59 +0000703 PyModule_AddIntConstant(m, "daylight", _daylight);
704 PyModule_AddObject(m, "tzname",
705 Py_BuildValue("(zz)", _tzname[0], _tzname[1]));
Tim Peters26ae7cd2001-03-20 03:26:49 +0000706#endif /* __CYGWIN__ */
Guido van Rossum10b164a2001-09-25 13:59:01 +0000707#endif /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000708}
709
710
711static PyMethodDef time_methods[] = {
Georg Brandl96a8c392006-05-29 21:04:52 +0000712 {"time", time_time, METH_NOARGS, time_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000713#ifdef HAVE_CLOCK
Georg Brandl96a8c392006-05-29 21:04:52 +0000714 {"clock", time_clock, METH_NOARGS, clock_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000715#endif
716 {"sleep", time_sleep, METH_VARARGS, sleep_doc},
717 {"gmtime", time_gmtime, METH_VARARGS, gmtime_doc},
718 {"localtime", time_localtime, METH_VARARGS, localtime_doc},
719 {"asctime", time_asctime, METH_VARARGS, asctime_doc},
720 {"ctime", time_ctime, METH_VARARGS, ctime_doc},
721#ifdef HAVE_MKTIME
Georg Brandl96a8c392006-05-29 21:04:52 +0000722 {"mktime", time_mktime, METH_O, mktime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000723#endif
724#ifdef HAVE_STRFTIME
725 {"strftime", time_strftime, METH_VARARGS, strftime_doc},
726#endif
727 {"strptime", time_strptime, METH_VARARGS, strptime_doc},
728#ifdef HAVE_WORKING_TZSET
Georg Brandl96a8c392006-05-29 21:04:52 +0000729 {"tzset", time_tzset, METH_NOARGS, tzset_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000730#endif
731 {NULL, NULL} /* sentinel */
732};
733
734
735PyDoc_STRVAR(module_doc,
736"This module provides various functions to manipulate time values.\n\
737\n\
738There are two standard representations of time. One is the number\n\
739of seconds since the Epoch, in UTC (a.k.a. GMT). It may be an integer\n\
740or a floating point number (to represent fractions of seconds).\n\
741The Epoch is system-defined; on Unix, it is generally January 1st, 1970.\n\
742The actual value can be retrieved by calling gmtime(0).\n\
743\n\
744The other representation is a tuple of 9 integers giving local time.\n\
745The tuple items are:\n\
746 year (four digits, e.g. 1998)\n\
747 month (1-12)\n\
748 day (1-31)\n\
749 hours (0-23)\n\
750 minutes (0-59)\n\
751 seconds (0-59)\n\
752 weekday (0-6, Monday is 0)\n\
753 Julian day (day in the year, 1-366)\n\
754 DST (Daylight Savings Time) flag (-1, 0 or 1)\n\
755If the DST flag is 0, the time is given in the regular time zone;\n\
756if it is 1, the time is given in the DST time zone;\n\
757if it is -1, mktime() should guess based on the date and time.\n\
758\n\
759Variables:\n\
760\n\
761timezone -- difference in seconds between UTC and local standard time\n\
762altzone -- difference in seconds between UTC and local DST time\n\
763daylight -- whether local time should reflect DST\n\
764tzname -- tuple of (standard time zone name, DST time zone name)\n\
765\n\
766Functions:\n\
767\n\
768time() -- return current time in seconds since the Epoch as a float\n\
769clock() -- return CPU time since process start as a float\n\
770sleep() -- delay for a number of seconds given as a float\n\
771gmtime() -- convert seconds since Epoch to UTC tuple\n\
772localtime() -- convert seconds since Epoch to local time tuple\n\
773asctime() -- convert time tuple to string\n\
774ctime() -- convert time in seconds to string\n\
775mktime() -- convert local time tuple to seconds since Epoch\n\
776strftime() -- convert time tuple to string according to format specification\n\
777strptime() -- parse string to time tuple according to format specification\n\
778tzset() -- change the local timezone");
779
780
781PyMODINIT_FUNC
782inittime(void)
783{
784 PyObject *m;
785 char *p;
786 m = Py_InitModule3("time", time_methods, module_doc);
Neal Norwitz1ac754f2006-01-19 06:09:39 +0000787 if (m == NULL)
788 return;
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000789
790 /* Accept 2-digit dates unless PYTHONY2K is set and non-empty */
791 p = Py_GETENV("PYTHONY2K");
792 PyModule_AddIntConstant(m, "accept2dyear", (long) (!p || !*p));
793 /* Squirrel away the module's dictionary for the y2k check */
794 moddict = PyModule_GetDict(m);
795 Py_INCREF(moddict);
796
797 /* Set, or reset, module variables like time.timezone */
798 inittimezone(m);
799
Mark Hammond975e3922002-07-16 01:29:19 +0000800#ifdef MS_WINDOWS
801 /* Helper to allow interrupts for Windows.
802 If Ctrl+C event delivered while not sleeping
803 it will be ignored.
804 */
805 main_thread = PyThread_get_thread_ident();
806 hInterruptEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
807 SetConsoleCtrlHandler( PyCtrlHandler, TRUE);
808#endif /* MS_WINDOWS */
Martin v. Löwis19ab6c92006-04-16 18:55:50 +0000809 if (!initialized) {
Tim Peters7a822da2006-05-25 21:50:17 +0000810 PyStructSequence_InitType(&StructTimeType,
Martin v. Löwis19ab6c92006-04-16 18:55:50 +0000811 &struct_time_type_desc);
812 }
Fred Drake9bb74322002-04-01 14:49:59 +0000813 Py_INCREF(&StructTimeType);
814 PyModule_AddObject(m, "struct_time", (PyObject*) &StructTimeType);
Martin v. Löwis19ab6c92006-04-16 18:55:50 +0000815 initialized = 1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000816}
817
818
Guido van Rossumb6775db1994-08-01 11:34:53 +0000819/* Implement floattime() for various platforms */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000820
Guido van Rossumb6775db1994-08-01 11:34:53 +0000821static double
Thomas Woutersf3f33dc2000-07-21 06:00:07 +0000822floattime(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000823{
Guido van Rossumb6775db1994-08-01 11:34:53 +0000824 /* There are three ways to get the time:
Barry Warsaw4a6cf411997-01-13 22:44:55 +0000825 (1) gettimeofday() -- resolution in microseconds
826 (2) ftime() -- resolution in milliseconds
827 (3) time() -- resolution in seconds
828 In all cases the return value is a float in seconds.
829 Since on some systems (e.g. SCO ODT 3.0) gettimeofday() may
830 fail, so we fall back on ftime() or time().
831 Note: clock resolution does not imply clock accuracy! */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000832#ifdef HAVE_GETTIMEOFDAY
Barry Warsaw4a6cf411997-01-13 22:44:55 +0000833 {
834 struct timeval t;
Guido van Rossum3bbc62e1995-01-02 19:30:30 +0000835#ifdef GETTIMEOFDAY_NO_TZ
Barry Warsaw4a6cf411997-01-13 22:44:55 +0000836 if (gettimeofday(&t) == 0)
837 return (double)t.tv_sec + t.tv_usec*0.000001;
Guido van Rossum3bbc62e1995-01-02 19:30:30 +0000838#else /* !GETTIMEOFDAY_NO_TZ */
Barry Warsaw4a6cf411997-01-13 22:44:55 +0000839 if (gettimeofday(&t, (struct timezone *)NULL) == 0)
840 return (double)t.tv_sec + t.tv_usec*0.000001;
Guido van Rossum3bbc62e1995-01-02 19:30:30 +0000841#endif /* !GETTIMEOFDAY_NO_TZ */
Barry Warsaw4a6cf411997-01-13 22:44:55 +0000842 }
Ronald Oussorend06b6f22006-04-23 11:59:25 +0000843
Guido van Rossumb6775db1994-08-01 11:34:53 +0000844#endif /* !HAVE_GETTIMEOFDAY */
Barry Warsaw4a6cf411997-01-13 22:44:55 +0000845 {
Guido van Rossumd3eb5771999-03-09 16:07:23 +0000846#if defined(HAVE_FTIME)
Barry Warsaw4a6cf411997-01-13 22:44:55 +0000847 struct timeb t;
848 ftime(&t);
849 return (double)t.time + (double)t.millitm * (double)0.001;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000850#else /* !HAVE_FTIME */
Barry Warsaw4a6cf411997-01-13 22:44:55 +0000851 time_t secs;
852 time(&secs);
853 return (double)secs;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000854#endif /* !HAVE_FTIME */
Barry Warsaw4a6cf411997-01-13 22:44:55 +0000855 }
Guido van Rossum426035c1991-02-19 12:27:35 +0000856}
857
Guido van Rossumb6775db1994-08-01 11:34:53 +0000858
859/* Implement floatsleep() for various platforms.
860 When interrupted (or when another error occurs), return -1 and
861 set an exception; else return 0. */
862
863static int
Guido van Rossuma320fd31995-03-09 12:14:15 +0000864floatsleep(double secs)
Guido van Rossum426035c1991-02-19 12:27:35 +0000865{
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000866/* XXX Should test for MS_WINDOWS first! */
Andrew MacIntyre7bf68332002-03-03 02:59:16 +0000867#if defined(HAVE_SELECT) && !defined(__BEOS__) && !defined(__EMX__)
Guido van Rossum426035c1991-02-19 12:27:35 +0000868 struct timeval t;
Guido van Rossum775f4da1993-01-09 17:18:52 +0000869 double frac;
Guido van Rossum775f4da1993-01-09 17:18:52 +0000870 frac = fmod(secs, 1.0);
871 secs = floor(secs);
872 t.tv_sec = (long)secs;
873 t.tv_usec = (long)(frac*1000000.0);
Guido van Rossum8607ae21997-11-03 22:04:46 +0000874 Py_BEGIN_ALLOW_THREADS
Guido van Rossumb6775db1994-08-01 11:34:53 +0000875 if (select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &t) != 0) {
Guido van Rossum09cbb011999-11-08 15:32:27 +0000876#ifdef EINTR
Guido van Rossuma5456d51999-08-19 14:40:27 +0000877 if (errno != EINTR) {
Guido van Rossum09cbb011999-11-08 15:32:27 +0000878#else
879 if (1) {
880#endif
Andrew M. Kuchlingc24ca4b2000-03-24 20:35:20 +0000881 Py_BLOCK_THREADS
Guido van Rossuma5456d51999-08-19 14:40:27 +0000882 PyErr_SetFromErrno(PyExc_IOError);
883 return -1;
884 }
Guido van Rossumb6775db1994-08-01 11:34:53 +0000885 }
Guido van Rossum8607ae21997-11-03 22:04:46 +0000886 Py_END_ALLOW_THREADS
Martin v. Löwis02af9642002-01-16 11:04:06 +0000887#elif defined(__WATCOMC__) && !defined(__QNX__)
Guido van Rossumbceeac81996-05-23 22:53:47 +0000888 /* XXX Can't interrupt this sleep */
Guido van Rossum8607ae21997-11-03 22:04:46 +0000889 Py_BEGIN_ALLOW_THREADS
Guido van Rossumbceeac81996-05-23 22:53:47 +0000890 delay((int)(secs * 1000 + 0.5)); /* delay() uses milliseconds */
Guido van Rossum8607ae21997-11-03 22:04:46 +0000891 Py_END_ALLOW_THREADS
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000892#elif defined(MS_WINDOWS)
Fred Drake0e123952000-06-29 21:31:02 +0000893 {
894 double millisecs = secs * 1000.0;
Tim Peters513a1cd2003-01-19 04:54:58 +0000895 unsigned long ul_millis;
896
Fred Drake0e123952000-06-29 21:31:02 +0000897 if (millisecs > (double)ULONG_MAX) {
Tim Peters513a1cd2003-01-19 04:54:58 +0000898 PyErr_SetString(PyExc_OverflowError,
899 "sleep length is too large");
Fred Drake0e123952000-06-29 21:31:02 +0000900 return -1;
901 }
Fred Drake0e123952000-06-29 21:31:02 +0000902 Py_BEGIN_ALLOW_THREADS
Tim Peters513a1cd2003-01-19 04:54:58 +0000903 /* Allow sleep(0) to maintain win32 semantics, and as decreed
904 * by Guido, only the main thread can be interrupted.
905 */
906 ul_millis = (unsigned long)millisecs;
907 if (ul_millis == 0 ||
908 main_thread != PyThread_get_thread_ident())
909 Sleep(ul_millis);
Mark Hammond975e3922002-07-16 01:29:19 +0000910 else {
911 DWORD rc;
912 ResetEvent(hInterruptEvent);
Tim Peters513a1cd2003-01-19 04:54:58 +0000913 rc = WaitForSingleObject(hInterruptEvent, ul_millis);
914 if (rc == WAIT_OBJECT_0) {
915 /* Yield to make sure real Python signal
916 * handler called.
917 */
Mark Hammond975e3922002-07-16 01:29:19 +0000918 Sleep(1);
919 Py_BLOCK_THREADS
Mark Hammond975e3922002-07-16 01:29:19 +0000920 errno = EINTR;
921 PyErr_SetFromErrno(PyExc_IOError);
922 return -1;
923 }
924 }
Fred Drake0e123952000-06-29 21:31:02 +0000925 Py_END_ALLOW_THREADS
926 }
Martin v. Löwis02af9642002-01-16 11:04:06 +0000927#elif defined(PYOS_OS2)
Guido van Rossum8e9ebfd1997-11-22 21:53:48 +0000928 /* This Sleep *IS* Interruptable by Exceptions */
Guido van Rossum1d0d7e41997-12-29 20:03:10 +0000929 Py_BEGIN_ALLOW_THREADS
Guido van Rossum8e9ebfd1997-11-22 21:53:48 +0000930 if (DosSleep(secs * 1000) != NO_ERROR) {
Guido van Rossum1d0d7e41997-12-29 20:03:10 +0000931 Py_BLOCK_THREADS
Guido van Rossum8e9ebfd1997-11-22 21:53:48 +0000932 PyErr_SetFromErrno(PyExc_IOError);
933 return -1;
934 }
Guido van Rossum1d0d7e41997-12-29 20:03:10 +0000935 Py_END_ALLOW_THREADS
Martin v. Löwis02af9642002-01-16 11:04:06 +0000936#elif defined(__BEOS__)
Guido van Rossumbcc20741998-08-04 22:53:56 +0000937 /* This sleep *CAN BE* interrupted. */
938 {
Guido van Rossumbcc20741998-08-04 22:53:56 +0000939 if( secs <= 0.0 ) {
940 return;
941 }
Guido van Rossum10b164a2001-09-25 13:59:01 +0000942
Guido van Rossumbcc20741998-08-04 22:53:56 +0000943 Py_BEGIN_ALLOW_THREADS
Guido van Rossumd3eb5771999-03-09 16:07:23 +0000944 /* BeOS snooze() is in microseconds... */
945 if( snooze( (bigtime_t)( secs * 1000.0 * 1000.0 ) ) == B_INTERRUPTED ) {
Guido van Rossumbcc20741998-08-04 22:53:56 +0000946 Py_BLOCK_THREADS
947 PyErr_SetFromErrno( PyExc_IOError );
948 return -1;
949 }
950 Py_END_ALLOW_THREADS
951 }
Martin v. Löwis02af9642002-01-16 11:04:06 +0000952#elif defined(RISCOS)
Guido van Rossumbceccf52001-04-10 22:07:43 +0000953 if (secs <= 0.0)
954 return 0;
955 Py_BEGIN_ALLOW_THREADS
956 /* This sleep *CAN BE* interrupted. */
Martin v. Löwisa94568a2003-05-10 07:36:56 +0000957 if ( riscos_sleep(secs) )
Guido van Rossumbceccf52001-04-10 22:07:43 +0000958 return -1;
959 Py_END_ALLOW_THREADS
Martin v. Löwis02af9642002-01-16 11:04:06 +0000960#elif defined(PLAN9)
961 {
962 double millisecs = secs * 1000.0;
963 if (millisecs > (double)LONG_MAX) {
964 PyErr_SetString(PyExc_OverflowError, "sleep length is too large");
965 return -1;
966 }
967 /* This sleep *CAN BE* interrupted. */
968 Py_BEGIN_ALLOW_THREADS
969 if(sleep((long)millisecs) < 0){
970 Py_BLOCK_THREADS
971 PyErr_SetFromErrno(PyExc_IOError);
972 return -1;
973 }
974 Py_END_ALLOW_THREADS
975 }
976#else
Guido van Rossumb6775db1994-08-01 11:34:53 +0000977 /* XXX Can't interrupt this sleep */
Guido van Rossum8607ae21997-11-03 22:04:46 +0000978 Py_BEGIN_ALLOW_THREADS
Guido van Rossumb6775db1994-08-01 11:34:53 +0000979 sleep((int)secs);
Guido van Rossum8607ae21997-11-03 22:04:46 +0000980 Py_END_ALLOW_THREADS
Martin v. Löwis02af9642002-01-16 11:04:06 +0000981#endif
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000982
Guido van Rossumb6775db1994-08-01 11:34:53 +0000983 return 0;
Guido van Rossum80c9d881991-04-16 08:47:51 +0000984}
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000985
986