blob: 08d28a103c3a30bd6e2c302a48e41771b05d9468 [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
Guido van Rossum87ce7bb1998-06-09 16:30:31 +00008#include <ctype.h>
9
Guido van Rossumb6775db1994-08-01 11:34:53 +000010#include <sys/types.h>
Guido van Rossum6d946f91992-08-14 13:49:30 +000011
Guido van Rossumb6775db1994-08-01 11:34:53 +000012#ifdef QUICKWIN
13#include <io.h>
14#endif
15
Guido van Rossumb6775db1994-08-01 11:34:53 +000016#ifdef HAVE_FTIME
17#include <sys/timeb.h>
Guido van Rossum8e9ebfd1997-11-22 21:53:48 +000018#if !defined(MS_WINDOWS) && !defined(PYOS_OS2)
Thomas Woutersbd4bc4e2000-07-22 23:57:55 +000019extern int ftime(struct timeb *);
Guido van Rossum52174571996-12-09 18:38:52 +000020#endif /* MS_WINDOWS */
21#endif /* HAVE_FTIME */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000022
Guido van Rossum7bf22de1997-12-02 20:34:19 +000023#if defined(__WATCOMC__) && !defined(__QNX__)
Guido van Rossumbceeac81996-05-23 22:53:47 +000024#include <i86.h>
25#else
Guido van Rossumcac6c721996-09-06 13:34:02 +000026#ifdef MS_WINDOWS
Mark Hammond975e3922002-07-16 01:29:19 +000027#define WIN32_LEAN_AND_MEAN
Guido van Rossum258ccd42001-03-02 06:53:29 +000028#include <windows.h>
Mark Hammond975e3922002-07-16 01:29:19 +000029#include "pythread.h"
30
31/* helper to allow us to interrupt sleep() on Windows*/
32static HANDLE hInterruptEvent = NULL;
33static BOOL WINAPI PyCtrlHandler(DWORD dwCtrlType)
34{
35 SetEvent(hInterruptEvent);
36 /* allow other default handlers to be called.
37 Default Python handler will setup the
38 KeyboardInterrupt exception.
39 */
40 return FALSE;
41}
42static long main_thread;
43
44
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000045#if defined(__BORLANDC__)
Guido van Rossumb2fb3641996-09-07 00:47:35 +000046/* These overrides not needed for Win32 */
Guido van Rossumb6775db1994-08-01 11:34:53 +000047#define timezone _timezone
Guido van Rossumcc081121995-03-14 15:05:41 +000048#define tzname _tzname
49#define daylight _daylight
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000050#endif /* __BORLANDC__ */
Guido van Rossumcac6c721996-09-06 13:34:02 +000051#endif /* MS_WINDOWS */
Guido van Rossum7bf22de1997-12-02 20:34:19 +000052#endif /* !__WATCOMC__ || __QNX__ */
Guido van Rossum234f9421993-06-17 12:35:49 +000053
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000054#if defined(MS_WINDOWS) && !defined(MS_WIN64) && !defined(__BORLANDC__)
Fred Drakedfb4ebd2000-06-29 20:56:28 +000055/* Win32 has better clock replacement
56 XXX Win64 does not yet, but might when the platform matures. */
Guido van Rossum3917c221997-04-02 05:35:28 +000057#undef HAVE_CLOCK /* We have our own version down below */
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000058#endif /* MS_WINDOWS && !MS_WIN64 */
Guido van Rossum3917c221997-04-02 05:35:28 +000059
Andrew MacIntyre7bf68332002-03-03 02:59:16 +000060#if defined(PYOS_OS2)
61#define INCL_DOS
62#define INCL_ERRORS
63#include <os2.h>
64#endif
65
Guido van Rossum8e9ebfd1997-11-22 21:53:48 +000066#if defined(PYCC_VACPP)
Guido van Rossum26452411998-09-28 22:07:11 +000067#include <sys/time.h>
Guido van Rossum8e9ebfd1997-11-22 21:53:48 +000068#endif
69
Guido van Rossumbcc20741998-08-04 22:53:56 +000070#ifdef __BEOS__
Fred Drake56221a72000-08-15 18:52:33 +000071#include <time.h>
Guido van Rossumbcc20741998-08-04 22:53:56 +000072/* For bigtime_t, snooze(). - [cjh] */
73#include <support/SupportDefs.h>
74#include <kernel/OS.h>
75#endif
76
Martin v. Löwisa94568a2003-05-10 07:36:56 +000077#ifdef RISCOS
78extern int riscos_sleep(double);
79#endif
80
Guido van Rossum234f9421993-06-17 12:35:49 +000081/* Forward declarations */
Tim Petersdbd9ba62000-07-09 03:09:57 +000082static int floatsleep(double);
Thomas Woutersed77bac2000-07-24 15:26:39 +000083static double floattime(void);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000084
Guido van Rossumcfbaecc1998-08-25 14:51:12 +000085/* For Y2K check */
86static PyObject *moddict;
87
Tim Peters1b6f7a92004-06-20 02:50:16 +000088/* Exposed in timefuncs.h. */
89time_t
Brett Cannon298c3802004-06-19 20:48:43 +000090_PyTime_DoubleToTimet(double x)
91{
92 time_t result;
93 double diff;
94
95 result = (time_t)x;
96 /* How much info did we lose? time_t may be an integral or
97 * floating type, and we don't know which. If it's integral,
98 * we don't know whether C truncates, rounds, returns the floor,
99 * etc. If we lost a second or more, the C rounding is
100 * unreasonable, or the input just doesn't fit in a time_t;
101 * call it an error regardless. Note that the original cast to
102 * time_t can cause a C error too, but nothing we can do to
103 * worm around that.
104 */
105 diff = x - (double)result;
106 if (diff <= -1.0 || diff >= 1.0) {
107 PyErr_SetString(PyExc_ValueError,
108 "timestamp out of range for platform time_t");
109 result = (time_t)-1;
110 }
111 return result;
112}
113
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000114static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000115time_time(PyObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000116{
Guido van Rossumb6775db1994-08-01 11:34:53 +0000117 double secs;
Thomas Woutersfe385252001-01-19 23:16:56 +0000118 if (!PyArg_ParseTuple(args, ":time"))
Guido van Rossuma2b7f401993-01-04 09:09:59 +0000119 return NULL;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000120 secs = floattime();
121 if (secs == 0.0) {
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000122 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossuma2b7f401993-01-04 09:09:59 +0000123 return NULL;
124 }
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000125 return PyFloat_FromDouble(secs);
Guido van Rossumb6775db1994-08-01 11:34:53 +0000126}
127
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000128PyDoc_STRVAR(time_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000129"time() -> floating point number\n\
130\n\
131Return the current time in seconds since the Epoch.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000132Fractions of a second may be present if the system clock provides them.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000133
Guido van Rossumb6775db1994-08-01 11:34:53 +0000134#ifdef HAVE_CLOCK
135
136#ifndef CLOCKS_PER_SEC
Guido van Rossum1b66a4f1996-02-25 04:50:33 +0000137#ifdef CLK_TCK
138#define CLOCKS_PER_SEC CLK_TCK
139#else
Guido van Rossumb6775db1994-08-01 11:34:53 +0000140#define CLOCKS_PER_SEC 1000000
141#endif
Guido van Rossum1b66a4f1996-02-25 04:50:33 +0000142#endif
Guido van Rossumb6775db1994-08-01 11:34:53 +0000143
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000144static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000145time_clock(PyObject *self, PyObject *args)
Guido van Rossumb6775db1994-08-01 11:34:53 +0000146{
Thomas Woutersfe385252001-01-19 23:16:56 +0000147 if (!PyArg_ParseTuple(args, ":clock"))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000148 return NULL;
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000149 return PyFloat_FromDouble(((double)clock()) / CLOCKS_PER_SEC);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000150}
Guido van Rossumb6775db1994-08-01 11:34:53 +0000151#endif /* HAVE_CLOCK */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000152
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000153#if defined(MS_WINDOWS) && !defined(MS_WIN64) && !defined(__BORLANDC__)
Mark Hammond7ba5e812002-02-12 04:02:33 +0000154/* Due to Mark Hammond and Tim Peters */
Guido van Rossum3917c221997-04-02 05:35:28 +0000155static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000156time_clock(PyObject *self, PyObject *args)
Guido van Rossum3917c221997-04-02 05:35:28 +0000157{
Tim Peters9ad4b682002-02-13 05:14:18 +0000158 static LARGE_INTEGER ctrStart;
Mark Hammond7ba5e812002-02-12 04:02:33 +0000159 static double divisor = 0.0;
Tim Peters9ad4b682002-02-13 05:14:18 +0000160 LARGE_INTEGER now;
Mark Hammond7ba5e812002-02-12 04:02:33 +0000161 double diff;
Guido van Rossum3917c221997-04-02 05:35:28 +0000162
Thomas Woutersfe385252001-01-19 23:16:56 +0000163 if (!PyArg_ParseTuple(args, ":clock"))
Guido van Rossum3917c221997-04-02 05:35:28 +0000164 return NULL;
165
Mark Hammond7ba5e812002-02-12 04:02:33 +0000166 if (divisor == 0.0) {
Tim Peters9ad4b682002-02-13 05:14:18 +0000167 LARGE_INTEGER freq;
168 QueryPerformanceCounter(&ctrStart);
169 if (!QueryPerformanceFrequency(&freq) || freq.QuadPart == 0) {
Mark Hammond7ba5e812002-02-12 04:02:33 +0000170 /* Unlikely to happen - this works on all intel
171 machines at least! Revert to clock() */
Guido van Rossum3917c221997-04-02 05:35:28 +0000172 return PyFloat_FromDouble(clock());
173 }
Tim Peters9ad4b682002-02-13 05:14:18 +0000174 divisor = (double)freq.QuadPart;
Guido van Rossum3917c221997-04-02 05:35:28 +0000175 }
Tim Peters9ad4b682002-02-13 05:14:18 +0000176 QueryPerformanceCounter(&now);
177 diff = (double)(now.QuadPart - ctrStart.QuadPart);
Mark Hammond7ba5e812002-02-12 04:02:33 +0000178 return PyFloat_FromDouble(diff / divisor);
Guido van Rossum3917c221997-04-02 05:35:28 +0000179}
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000180
Guido van Rossum3917c221997-04-02 05:35:28 +0000181#define HAVE_CLOCK /* So it gets included in the methods */
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000182#endif /* MS_WINDOWS && !MS_WIN64 */
Guido van Rossum3917c221997-04-02 05:35:28 +0000183
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000184#ifdef HAVE_CLOCK
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000185PyDoc_STRVAR(clock_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000186"clock() -> floating point number\n\
187\n\
188Return the CPU time or real time since the start of the process or since\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000189the first call to clock(). This has as much precision as the system\n\
190records.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000191#endif
192
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000193static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000194time_sleep(PyObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000195{
Guido van Rossum775f4da1993-01-09 17:18:52 +0000196 double secs;
Thomas Woutersfe385252001-01-19 23:16:56 +0000197 if (!PyArg_ParseTuple(args, "d:sleep", &secs))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000198 return NULL;
Guido van Rossum8607ae21997-11-03 22:04:46 +0000199 if (floatsleep(secs) != 0)
200 return NULL;
201 Py_INCREF(Py_None);
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000202 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000203}
204
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000205PyDoc_STRVAR(sleep_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000206"sleep(seconds)\n\
207\n\
208Delay execution for a given number of seconds. The argument may be\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000209a floating point number for subsecond precision.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000210
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000211static PyStructSequence_Field struct_time_type_fields[] = {
212 {"tm_year", NULL},
213 {"tm_mon", NULL},
214 {"tm_mday", NULL},
215 {"tm_hour", NULL},
216 {"tm_min", NULL},
217 {"tm_sec", NULL},
218 {"tm_wday", NULL},
219 {"tm_yday", NULL},
220 {"tm_isdst", NULL},
221 {0}
222};
223
224static PyStructSequence_Desc struct_time_type_desc = {
Guido van Rossum14648392001-12-08 18:02:58 +0000225 "time.struct_time",
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000226 NULL,
227 struct_time_type_fields,
228 9,
229};
Tim Peters9ad4b682002-02-13 05:14:18 +0000230
Martin v. Löwis19ab6c92006-04-16 18:55:50 +0000231static int initialized;
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000232static PyTypeObject StructTimeType;
233
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000234static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000235tmtotuple(struct tm *p)
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000236{
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000237 PyObject *v = PyStructSequence_New(&StructTimeType);
238 if (v == NULL)
239 return NULL;
Tim Peters9ad4b682002-02-13 05:14:18 +0000240
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000241#define SET(i,val) PyStructSequence_SET_ITEM(v, i, PyInt_FromLong((long) val))
242
243 SET(0, p->tm_year + 1900);
244 SET(1, p->tm_mon + 1); /* Want January == 1 */
245 SET(2, p->tm_mday);
246 SET(3, p->tm_hour);
247 SET(4, p->tm_min);
248 SET(5, p->tm_sec);
249 SET(6, (p->tm_wday + 6) % 7); /* Want Monday == 0 */
250 SET(7, p->tm_yday + 1); /* Want January, 1 == 1 */
251 SET(8, p->tm_isdst);
252#undef SET
253 if (PyErr_Occurred()) {
254 Py_XDECREF(v);
255 return NULL;
256 }
257
258 return v;
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000259}
260
261static PyObject *
Brett Cannon298c3802004-06-19 20:48:43 +0000262time_convert(double when, struct tm * (*function)(const time_t *))
Guido van Rossum234f9421993-06-17 12:35:49 +0000263{
Guido van Rossum6e8583d1996-10-08 14:19:52 +0000264 struct tm *p;
Brett Cannon298c3802004-06-19 20:48:43 +0000265 time_t whent = _PyTime_DoubleToTimet(when);
266
267 if (whent == (time_t)-1 && PyErr_Occurred())
268 return NULL;
Guido van Rossum6e8583d1996-10-08 14:19:52 +0000269 errno = 0;
Brett Cannon298c3802004-06-19 20:48:43 +0000270 p = function(&whent);
Guido van Rossum6e8583d1996-10-08 14:19:52 +0000271 if (p == NULL) {
272#ifdef EINVAL
Guido van Rossum0b1ff661996-11-02 17:31:22 +0000273 if (errno == 0)
Guido van Rossum6e8583d1996-10-08 14:19:52 +0000274 errno = EINVAL;
275#endif
Tim Peters8b19a932003-01-17 20:08:54 +0000276 return PyErr_SetFromErrno(PyExc_ValueError);
Guido van Rossum6e8583d1996-10-08 14:19:52 +0000277 }
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000278 return tmtotuple(p);
Guido van Rossum234f9421993-06-17 12:35:49 +0000279}
280
Fred Drakef901abd2004-08-03 17:58:55 +0000281/* Parse arg tuple that can contain an optional float-or-None value;
282 format needs to be "|O:name".
283 Returns non-zero on success (parallels PyArg_ParseTuple).
284*/
285static int
286parse_time_double_args(PyObject *args, char *format, double *pwhen)
287{
288 PyObject *ot = NULL;
289
290 if (!PyArg_ParseTuple(args, format, &ot))
291 return 0;
292 if (ot == NULL || ot == Py_None)
293 *pwhen = floattime();
294 else {
295 double when = PyFloat_AsDouble(ot);
296 if (PyErr_Occurred())
297 return 0;
298 *pwhen = when;
299 }
300 return 1;
301}
302
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000303static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000304time_gmtime(PyObject *self, PyObject *args)
Guido van Rossum234f9421993-06-17 12:35:49 +0000305{
306 double when;
Fred Drakef901abd2004-08-03 17:58:55 +0000307 if (!parse_time_double_args(args, "|O:gmtime", &when))
Guido van Rossum234f9421993-06-17 12:35:49 +0000308 return NULL;
Brett Cannon298c3802004-06-19 20:48:43 +0000309 return time_convert(when, gmtime);
Guido van Rossum234f9421993-06-17 12:35:49 +0000310}
311
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000312PyDoc_STRVAR(gmtime_doc,
Fred Drake193a3f62002-03-12 21:38:49 +0000313"gmtime([seconds]) -> (tm_year, tm_mon, tm_day, tm_hour, tm_min,\n\
314 tm_sec, tm_wday, tm_yday, tm_isdst)\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000315\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000316Convert seconds since the Epoch to a time tuple expressing UTC (a.k.a.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000317GMT). When 'seconds' is not passed in, convert the current time instead.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000318
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000319static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000320time_localtime(PyObject *self, PyObject *args)
Guido van Rossum234f9421993-06-17 12:35:49 +0000321{
322 double when;
Fred Drakef901abd2004-08-03 17:58:55 +0000323 if (!parse_time_double_args(args, "|O:localtime", &when))
Guido van Rossum234f9421993-06-17 12:35:49 +0000324 return NULL;
Brett Cannon298c3802004-06-19 20:48:43 +0000325 return time_convert(when, localtime);
Guido van Rossum234f9421993-06-17 12:35:49 +0000326}
327
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000328PyDoc_STRVAR(localtime_doc,
Fred Drake193a3f62002-03-12 21:38:49 +0000329"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 +0000330\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000331Convert seconds since the Epoch to a time tuple expressing local time.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000332When 'seconds' is not passed in, convert the current time instead.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000333
Guido van Rossum9e90a671993-06-24 11:10:19 +0000334static int
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000335gettmarg(PyObject *args, struct tm *p)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000336{
Guido van Rossumcfbaecc1998-08-25 14:51:12 +0000337 int y;
Thomas Wouters334fb892000-07-25 12:56:38 +0000338 memset((void *) p, '\0', sizeof(struct tm));
Guido van Rossumcfbaecc1998-08-25 14:51:12 +0000339
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000340 if (!PyArg_Parse(args, "(iiiiiiiii)",
Guido van Rossumcfbaecc1998-08-25 14:51:12 +0000341 &y,
Barry Warsaw4a6cf411997-01-13 22:44:55 +0000342 &p->tm_mon,
343 &p->tm_mday,
344 &p->tm_hour,
345 &p->tm_min,
346 &p->tm_sec,
347 &p->tm_wday,
348 &p->tm_yday,
349 &p->tm_isdst))
Guido van Rossum9e90a671993-06-24 11:10:19 +0000350 return 0;
Guido van Rossumcfbaecc1998-08-25 14:51:12 +0000351 if (y < 1900) {
352 PyObject *accept = PyDict_GetItemString(moddict,
353 "accept2dyear");
354 if (accept == NULL || !PyInt_Check(accept) ||
355 PyInt_AsLong(accept) == 0) {
356 PyErr_SetString(PyExc_ValueError,
357 "year >= 1900 required");
358 return 0;
359 }
360 if (69 <= y && y <= 99)
361 y += 1900;
362 else if (0 <= y && y <= 68)
363 y += 2000;
364 else {
365 PyErr_SetString(PyExc_ValueError,
Skip Montanaro1a10aac2001-08-22 12:39:16 +0000366 "year out of range");
Guido van Rossumcfbaecc1998-08-25 14:51:12 +0000367 return 0;
368 }
369 }
370 p->tm_year = y - 1900;
Guido van Rossum9e90a671993-06-24 11:10:19 +0000371 p->tm_mon--;
372 p->tm_wday = (p->tm_wday + 1) % 7;
373 p->tm_yday--;
374 return 1;
375}
376
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000377#ifdef HAVE_STRFTIME
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000378static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000379time_strftime(PyObject *self, PyObject *args)
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000380{
Thomas Woutersfe385252001-01-19 23:16:56 +0000381 PyObject *tup = NULL;
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000382 struct tm buf;
383 const char *fmt;
Guido van Rossumfa481162000-06-28 21:33:59 +0000384 size_t fmtlen, buflen;
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000385 char *outbuf = 0;
Guido van Rossumfa481162000-06-28 21:33:59 +0000386 size_t i;
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000387
Thomas Wouters334fb892000-07-25 12:56:38 +0000388 memset((void *) &buf, '\0', sizeof(buf));
Guido van Rossum1f41f841998-04-27 19:04:26 +0000389
Thomas Woutersfe385252001-01-19 23:16:56 +0000390 if (!PyArg_ParseTuple(args, "s|O:strftime", &fmt, &tup))
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000391 return NULL;
Thomas Woutersfe385252001-01-19 23:16:56 +0000392
393 if (tup == NULL) {
394 time_t tt = time(NULL);
395 buf = *localtime(&tt);
396 } else if (!gettmarg(tup, &buf))
397 return NULL;
Guido van Rossum10b164a2001-09-25 13:59:01 +0000398
Brett Cannond1080a32004-03-02 04:38:10 +0000399 /* Checks added to make sure strftime() does not crash Python by
400 indexing blindly into some array for a textual representation
401 by some bad index (fixes bug #897625).
Tim Peters1b6f7a92004-06-20 02:50:16 +0000402
Brett Cannond1080a32004-03-02 04:38:10 +0000403 No check for year since handled in gettmarg().
404 */
405 if (buf.tm_mon < 0 || buf.tm_mon > 11) {
406 PyErr_SetString(PyExc_ValueError, "month out of range");
407 return NULL;
408 }
409 if (buf.tm_mday < 1 || buf.tm_mday > 31) {
410 PyErr_SetString(PyExc_ValueError, "day of month out of range");
411 return NULL;
412 }
413 if (buf.tm_hour < 0 || buf.tm_hour > 23) {
414 PyErr_SetString(PyExc_ValueError, "hour out of range");
415 return NULL;
416 }
417 if (buf.tm_min < 0 || buf.tm_min > 59) {
418 PyErr_SetString(PyExc_ValueError, "minute out of range");
419 return NULL;
420 }
421 if (buf.tm_sec < 0 || buf.tm_sec > 61) {
422 PyErr_SetString(PyExc_ValueError, "seconds out of range");
423 return NULL;
424 }
425 /* tm_wday does not need checking of its upper-bound since taking
426 ``% 7`` in gettmarg() automatically restricts the range. */
427 if (buf.tm_wday < 0) {
428 PyErr_SetString(PyExc_ValueError, "day of week out of range");
429 return NULL;
430 }
431 if (buf.tm_yday < 0 || buf.tm_yday > 365) {
432 PyErr_SetString(PyExc_ValueError, "day of year out of range");
433 return NULL;
434 }
435 if (buf.tm_isdst < -1 || buf.tm_isdst > 1) {
436 PyErr_SetString(PyExc_ValueError,
437 "daylight savings flag out of range");
438 return NULL;
439 }
440
Guido van Rossumc222ec21999-02-23 00:00:10 +0000441 fmtlen = strlen(fmt);
442
Barry Warsaw4a6cf411997-01-13 22:44:55 +0000443 /* I hate these functions that presume you know how big the output
444 * will be ahead of time...
445 */
Guido van Rossumc222ec21999-02-23 00:00:10 +0000446 for (i = 1024; ; i += i) {
Anthony Baxter7cbc0f52006-04-13 07:19:01 +0000447 outbuf = (char *)malloc(i);
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000448 if (outbuf == NULL) {
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000449 return PyErr_NoMemory();
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000450 }
Guido van Rossumc222ec21999-02-23 00:00:10 +0000451 buflen = strftime(outbuf, i, fmt, &buf);
452 if (buflen > 0 || i >= 256 * fmtlen) {
453 /* If the buffer is 256 times as long as the format,
454 it's probably not failing for lack of room!
455 More likely, the format yields an empty result,
456 e.g. an empty format, or %Z when the timezone
457 is unknown. */
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000458 PyObject *ret;
Guido van Rossumc222ec21999-02-23 00:00:10 +0000459 ret = PyString_FromStringAndSize(outbuf, buflen);
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000460 free(outbuf);
461 return ret;
462 }
463 free(outbuf);
464 }
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000465}
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000466
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000467PyDoc_STRVAR(strftime_doc,
Thomas Woutersfe385252001-01-19 23:16:56 +0000468"strftime(format[, tuple]) -> string\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000469\n\
470Convert a time tuple to a string according to a format specification.\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000471See the library reference manual for formatting codes. When the time tuple\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000472is not present, current time as returned by localtime() is used.");
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000473#endif /* HAVE_STRFTIME */
474
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000475static PyObject *
476time_strptime(PyObject *self, PyObject *args)
477{
478 PyObject *strptime_module = PyImport_ImportModule("_strptime");
Raymond Hettinger502168a2003-04-10 16:03:22 +0000479 PyObject *strptime_result;
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000480
Tim Peters513a1cd2003-01-19 04:54:58 +0000481 if (!strptime_module)
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000482 return NULL;
Raymond Hettinger502168a2003-04-10 16:03:22 +0000483 strptime_result = PyObject_CallMethod(strptime_module, "strptime", "O", args);
484 Py_DECREF(strptime_module);
485 return strptime_result;
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000486}
487
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000488PyDoc_STRVAR(strptime_doc,
Brett Cannon20def8b2003-07-01 05:16:08 +0000489"strptime(string, format) -> struct_time\n\
Martin v. Löwisb3cfc1d2001-12-02 12:27:43 +0000490\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000491Parse a string to a time tuple according to a format specification.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000492See the library reference manual for formatting codes (same as strftime()).");
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000493
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000494
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000495static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000496time_asctime(PyObject *self, PyObject *args)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000497{
Thomas Woutersfe385252001-01-19 23:16:56 +0000498 PyObject *tup = NULL;
Guido van Rossum9e90a671993-06-24 11:10:19 +0000499 struct tm buf;
500 char *p;
Thomas Woutersfe385252001-01-19 23:16:56 +0000501 if (!PyArg_ParseTuple(args, "|O:asctime", &tup))
Guido van Rossumb2b42dd2000-01-12 16:38:20 +0000502 return NULL;
Thomas Woutersfe385252001-01-19 23:16:56 +0000503 if (tup == NULL) {
504 time_t tt = time(NULL);
505 buf = *localtime(&tt);
506 } else if (!gettmarg(tup, &buf))
Guido van Rossum9e90a671993-06-24 11:10:19 +0000507 return NULL;
508 p = asctime(&buf);
509 if (p[24] == '\n')
510 p[24] = '\0';
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000511 return PyString_FromString(p);
Guido van Rossum9e90a671993-06-24 11:10:19 +0000512}
513
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000514PyDoc_STRVAR(asctime_doc,
Thomas Woutersfe385252001-01-19 23:16:56 +0000515"asctime([tuple]) -> string\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000516\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000517Convert a time tuple to a string, e.g. 'Sat Jun 06 16:26:11 1998'.\n\
518When the time tuple is not present, current time as returned by localtime()\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000519is used.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000520
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000521static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000522time_ctime(PyObject *self, PyObject *args)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000523{
Fred Drakef901abd2004-08-03 17:58:55 +0000524 PyObject *ot = NULL;
Guido van Rossum9e90a671993-06-24 11:10:19 +0000525 time_t tt;
526 char *p;
Guido van Rossum10b164a2001-09-25 13:59:01 +0000527
Fred Drakef901abd2004-08-03 17:58:55 +0000528 if (!PyArg_ParseTuple(args, "|O:ctime", &ot))
529 return NULL;
530 if (ot == NULL || ot == Py_None)
Thomas Woutersfe385252001-01-19 23:16:56 +0000531 tt = time(NULL);
532 else {
Fred Drakef901abd2004-08-03 17:58:55 +0000533 double dt = PyFloat_AsDouble(ot);
534 if (PyErr_Occurred())
Thomas Woutersfe385252001-01-19 23:16:56 +0000535 return NULL;
Brett Cannon298c3802004-06-19 20:48:43 +0000536 tt = _PyTime_DoubleToTimet(dt);
537 if (tt == (time_t)-1 && PyErr_Occurred())
538 return NULL;
Thomas Woutersfe385252001-01-19 23:16:56 +0000539 }
Guido van Rossum9e90a671993-06-24 11:10:19 +0000540 p = ctime(&tt);
Guido van Rossum78535701998-03-03 22:19:10 +0000541 if (p == NULL) {
542 PyErr_SetString(PyExc_ValueError, "unconvertible time");
543 return NULL;
544 }
Guido van Rossum9e90a671993-06-24 11:10:19 +0000545 if (p[24] == '\n')
546 p[24] = '\0';
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000547 return PyString_FromString(p);
Guido van Rossum9e90a671993-06-24 11:10:19 +0000548}
549
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000550PyDoc_STRVAR(ctime_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000551"ctime(seconds) -> string\n\
552\n\
553Convert a time in seconds since the Epoch to a string in local time.\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000554This is equivalent to asctime(localtime(seconds)). When the time tuple is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000555not present, current time as returned by localtime() is used.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000556
Guido van Rossum60cd8131998-03-06 17:16:21 +0000557#ifdef HAVE_MKTIME
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000558static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000559time_mktime(PyObject *self, PyObject *args)
Guido van Rossum234f9421993-06-17 12:35:49 +0000560{
Guido van Rossumb2b42dd2000-01-12 16:38:20 +0000561 PyObject *tup;
Guido van Rossum234f9421993-06-17 12:35:49 +0000562 struct tm buf;
Guido van Rossumbceeac81996-05-23 22:53:47 +0000563 time_t tt;
Guido van Rossum43713e52000-02-29 13:59:29 +0000564 if (!PyArg_ParseTuple(args, "O:mktime", &tup))
Guido van Rossumb2b42dd2000-01-12 16:38:20 +0000565 return NULL;
Guido van Rossumbceeac81996-05-23 22:53:47 +0000566 tt = time(&tt);
567 buf = *localtime(&tt);
Guido van Rossumb2b42dd2000-01-12 16:38:20 +0000568 if (!gettmarg(tup, &buf))
Guido van Rossum234f9421993-06-17 12:35:49 +0000569 return NULL;
Guido van Rossumbceeac81996-05-23 22:53:47 +0000570 tt = mktime(&buf);
571 if (tt == (time_t)(-1)) {
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000572 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum10b164a2001-09-25 13:59:01 +0000573 "mktime argument out of range");
Guido van Rossumbceeac81996-05-23 22:53:47 +0000574 return NULL;
575 }
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000576 return PyFloat_FromDouble((double)tt);
Guido van Rossum234f9421993-06-17 12:35:49 +0000577}
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000578
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000579PyDoc_STRVAR(mktime_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000580"mktime(tuple) -> floating point number\n\
581\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000582Convert a time tuple in local time to seconds since the Epoch.");
Guido van Rossum60cd8131998-03-06 17:16:21 +0000583#endif /* HAVE_MKTIME */
Guido van Rossum234f9421993-06-17 12:35:49 +0000584
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000585#ifdef HAVE_WORKING_TZSET
586void inittimezone(PyObject *module);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000587
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000588static PyObject *
589time_tzset(PyObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000590{
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000591 PyObject* m;
Fred Drake9bb74322002-04-01 14:49:59 +0000592
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000593 if (!PyArg_ParseTuple(args, ":tzset"))
594 return NULL;
595
596 m = PyImport_ImportModule("time");
597 if (m == NULL) {
598 return NULL;
599 }
600
601 tzset();
602
603 /* Reset timezone, altzone, daylight and tzname */
604 inittimezone(m);
605 Py_DECREF(m);
Tim Peters1b6f7a92004-06-20 02:50:16 +0000606
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000607 Py_INCREF(Py_None);
608 return Py_None;
609}
610
611PyDoc_STRVAR(tzset_doc,
612"tzset(zone)\n\
613\n\
614Initialize, or reinitialize, the local timezone to the value stored in\n\
615os.environ['TZ']. The TZ environment variable should be specified in\n\
Neal Norwitzdc8e1942004-07-20 22:34:37 +0000616standard Unix timezone format as documented in the tzset man page\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000617(eg. 'US/Eastern', 'Europe/Amsterdam'). Unknown timezones will silently\n\
618fall back to UTC. If the TZ environment variable is not set, the local\n\
619timezone is set to the systems best guess of wallclock time.\n\
620Changing the TZ environment variable without calling tzset *may* change\n\
621the local timezone used by methods such as localtime, but this behaviour\n\
622should not be relied on.");
623#endif /* HAVE_WORKING_TZSET */
624
625void inittimezone(PyObject *m) {
626 /* This code moved from inittime wholesale to allow calling it from
627 time_tzset. In the future, some parts of it can be moved back
628 (for platforms that don't HAVE_WORKING_TZSET, when we know what they
629 are), and the extranious calls to tzset(3) should be removed.
630 I havn't done this yet, as I don't want to change this code as
631 little as possible when introducing the time.tzset and time.tzsetwall
632 methods. This should simply be a method of doing the following once,
633 at the top of this function and removing the call to tzset() from
634 time_tzset():
635
636 #ifdef HAVE_TZSET
637 tzset()
638 #endif
639
640 And I'm lazy and hate C so nyer.
641 */
Guido van Rossum10b164a2001-09-25 13:59:01 +0000642#if defined(HAVE_TZNAME) && !defined(__GLIBC__) && !defined(__CYGWIN__)
Guido van Rossum234f9421993-06-17 12:35:49 +0000643 tzset();
Guido van Rossum26452411998-09-28 22:07:11 +0000644#ifdef PYOS_OS2
Fred Drake9bb74322002-04-01 14:49:59 +0000645 PyModule_AddIntConstant(m, "timezone", _timezone);
Guido van Rossum26452411998-09-28 22:07:11 +0000646#else /* !PYOS_OS2 */
Fred Drake9bb74322002-04-01 14:49:59 +0000647 PyModule_AddIntConstant(m, "timezone", timezone);
Guido van Rossum26452411998-09-28 22:07:11 +0000648#endif /* PYOS_OS2 */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000649#ifdef HAVE_ALTZONE
Fred Drake9bb74322002-04-01 14:49:59 +0000650 PyModule_AddIntConstant(m, "altzone", altzone);
Guido van Rossumb6775db1994-08-01 11:34:53 +0000651#else
Guido van Rossum26452411998-09-28 22:07:11 +0000652#ifdef 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#else /* !PYOS_OS2 */
Fred Drake9bb74322002-04-01 14:49:59 +0000655 PyModule_AddIntConstant(m, "altzone", timezone-3600);
Guido van Rossum26452411998-09-28 22:07:11 +0000656#endif /* PYOS_OS2 */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000657#endif
Fred Drake9bb74322002-04-01 14:49:59 +0000658 PyModule_AddIntConstant(m, "daylight", daylight);
659 PyModule_AddObject(m, "tzname",
660 Py_BuildValue("(zz)", tzname[0], tzname[1]));
Guido van Rossum10b164a2001-09-25 13:59:01 +0000661#else /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/
Martin v. Löwis60a5d722002-10-16 20:28:25 +0000662#ifdef HAVE_STRUCT_TM_TM_ZONE
Guido van Rossum234f9421993-06-17 12:35:49 +0000663 {
664#define YEAR ((time_t)((365 * 24 + 6) * 3600))
665 time_t t;
666 struct tm *p;
Guido van Rossum57731601999-03-29 19:12:04 +0000667 long janzone, julyzone;
668 char janname[10], julyname[10];
Guido van Rossum234f9421993-06-17 12:35:49 +0000669 t = (time((time_t *)0) / YEAR) * YEAR;
670 p = localtime(&t);
Guido van Rossum57731601999-03-29 19:12:04 +0000671 janzone = -p->tm_gmtoff;
672 strncpy(janname, p->tm_zone ? p->tm_zone : " ", 9);
673 janname[9] = '\0';
Guido van Rossum234f9421993-06-17 12:35:49 +0000674 t += YEAR/2;
675 p = localtime(&t);
Guido van Rossum57731601999-03-29 19:12:04 +0000676 julyzone = -p->tm_gmtoff;
677 strncpy(julyname, p->tm_zone ? p->tm_zone : " ", 9);
678 julyname[9] = '\0';
Guido van Rossum10b164a2001-09-25 13:59:01 +0000679
Guido van Rossum57731601999-03-29 19:12:04 +0000680 if( janzone < julyzone ) {
681 /* DST is reversed in the southern hemisphere */
Fred Drake9bb74322002-04-01 14:49:59 +0000682 PyModule_AddIntConstant(m, "timezone", julyzone);
683 PyModule_AddIntConstant(m, "altzone", janzone);
684 PyModule_AddIntConstant(m, "daylight",
685 janzone != julyzone);
686 PyModule_AddObject(m, "tzname",
687 Py_BuildValue("(zz)",
688 julyname, janname));
Guido van Rossum57731601999-03-29 19:12:04 +0000689 } else {
Fred Drake9bb74322002-04-01 14:49:59 +0000690 PyModule_AddIntConstant(m, "timezone", janzone);
691 PyModule_AddIntConstant(m, "altzone", julyzone);
692 PyModule_AddIntConstant(m, "daylight",
693 janzone != julyzone);
694 PyModule_AddObject(m, "tzname",
695 Py_BuildValue("(zz)",
696 janname, julyname));
Guido van Rossum57731601999-03-29 19:12:04 +0000697 }
Guido van Rossum234f9421993-06-17 12:35:49 +0000698 }
Guido van Rossume6a4b7b1997-10-08 15:27:56 +0000699#else
Martin v. Löwis60a5d722002-10-16 20:28:25 +0000700#endif /* HAVE_STRUCT_TM_TM_ZONE */
Tim Peters26ae7cd2001-03-20 03:26:49 +0000701#ifdef __CYGWIN__
702 tzset();
Fred Drake9bb74322002-04-01 14:49:59 +0000703 PyModule_AddIntConstant(m, "timezone", _timezone);
704 PyModule_AddIntConstant(m, "altzone", _timezone);
705 PyModule_AddIntConstant(m, "daylight", _daylight);
706 PyModule_AddObject(m, "tzname",
707 Py_BuildValue("(zz)", _tzname[0], _tzname[1]));
Tim Peters26ae7cd2001-03-20 03:26:49 +0000708#endif /* __CYGWIN__ */
Guido van Rossum10b164a2001-09-25 13:59:01 +0000709#endif /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000710}
711
712
713static PyMethodDef time_methods[] = {
714 {"time", time_time, METH_VARARGS, time_doc},
715#ifdef HAVE_CLOCK
716 {"clock", time_clock, METH_VARARGS, clock_doc},
717#endif
718 {"sleep", time_sleep, METH_VARARGS, sleep_doc},
719 {"gmtime", time_gmtime, METH_VARARGS, gmtime_doc},
720 {"localtime", time_localtime, METH_VARARGS, localtime_doc},
721 {"asctime", time_asctime, METH_VARARGS, asctime_doc},
722 {"ctime", time_ctime, METH_VARARGS, ctime_doc},
723#ifdef HAVE_MKTIME
724 {"mktime", time_mktime, METH_VARARGS, mktime_doc},
725#endif
726#ifdef HAVE_STRFTIME
727 {"strftime", time_strftime, METH_VARARGS, strftime_doc},
728#endif
729 {"strptime", time_strptime, METH_VARARGS, strptime_doc},
730#ifdef HAVE_WORKING_TZSET
731 {"tzset", time_tzset, METH_VARARGS, tzset_doc},
732#endif
733 {NULL, NULL} /* sentinel */
734};
735
736
737PyDoc_STRVAR(module_doc,
738"This module provides various functions to manipulate time values.\n\
739\n\
740There are two standard representations of time. One is the number\n\
741of seconds since the Epoch, in UTC (a.k.a. GMT). It may be an integer\n\
742or a floating point number (to represent fractions of seconds).\n\
743The Epoch is system-defined; on Unix, it is generally January 1st, 1970.\n\
744The actual value can be retrieved by calling gmtime(0).\n\
745\n\
746The other representation is a tuple of 9 integers giving local time.\n\
747The tuple items are:\n\
748 year (four digits, e.g. 1998)\n\
749 month (1-12)\n\
750 day (1-31)\n\
751 hours (0-23)\n\
752 minutes (0-59)\n\
753 seconds (0-59)\n\
754 weekday (0-6, Monday is 0)\n\
755 Julian day (day in the year, 1-366)\n\
756 DST (Daylight Savings Time) flag (-1, 0 or 1)\n\
757If the DST flag is 0, the time is given in the regular time zone;\n\
758if it is 1, the time is given in the DST time zone;\n\
759if it is -1, mktime() should guess based on the date and time.\n\
760\n\
761Variables:\n\
762\n\
763timezone -- difference in seconds between UTC and local standard time\n\
764altzone -- difference in seconds between UTC and local DST time\n\
765daylight -- whether local time should reflect DST\n\
766tzname -- tuple of (standard time zone name, DST time zone name)\n\
767\n\
768Functions:\n\
769\n\
770time() -- return current time in seconds since the Epoch as a float\n\
771clock() -- return CPU time since process start as a float\n\
772sleep() -- delay for a number of seconds given as a float\n\
773gmtime() -- convert seconds since Epoch to UTC tuple\n\
774localtime() -- convert seconds since Epoch to local time tuple\n\
775asctime() -- convert time tuple to string\n\
776ctime() -- convert time in seconds to string\n\
777mktime() -- convert local time tuple to seconds since Epoch\n\
778strftime() -- convert time tuple to string according to format specification\n\
779strptime() -- parse string to time tuple according to format specification\n\
780tzset() -- change the local timezone");
781
782
783PyMODINIT_FUNC
784inittime(void)
785{
786 PyObject *m;
787 char *p;
788 m = Py_InitModule3("time", time_methods, module_doc);
Neal Norwitz1ac754f2006-01-19 06:09:39 +0000789 if (m == NULL)
790 return;
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000791
792 /* Accept 2-digit dates unless PYTHONY2K is set and non-empty */
793 p = Py_GETENV("PYTHONY2K");
794 PyModule_AddIntConstant(m, "accept2dyear", (long) (!p || !*p));
795 /* Squirrel away the module's dictionary for the y2k check */
796 moddict = PyModule_GetDict(m);
797 Py_INCREF(moddict);
798
799 /* Set, or reset, module variables like time.timezone */
800 inittimezone(m);
801
Mark Hammond975e3922002-07-16 01:29:19 +0000802#ifdef MS_WINDOWS
803 /* Helper to allow interrupts for Windows.
804 If Ctrl+C event delivered while not sleeping
805 it will be ignored.
806 */
807 main_thread = PyThread_get_thread_ident();
808 hInterruptEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
809 SetConsoleCtrlHandler( PyCtrlHandler, TRUE);
810#endif /* MS_WINDOWS */
Martin v. Löwis19ab6c92006-04-16 18:55:50 +0000811 if (!initialized) {
812 PyStructSequence_InitType(&StructTimeType,
813 &struct_time_type_desc);
814 }
Fred Drake9bb74322002-04-01 14:49:59 +0000815 Py_INCREF(&StructTimeType);
816 PyModule_AddObject(m, "struct_time", (PyObject*) &StructTimeType);
Martin v. Löwis19ab6c92006-04-16 18:55:50 +0000817 initialized = 1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000818}
819
820
Guido van Rossumb6775db1994-08-01 11:34:53 +0000821/* Implement floattime() for various platforms */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000822
Guido van Rossumb6775db1994-08-01 11:34:53 +0000823static double
Thomas Woutersf3f33dc2000-07-21 06:00:07 +0000824floattime(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000825{
Guido van Rossumb6775db1994-08-01 11:34:53 +0000826 /* There are three ways to get the time:
Barry Warsaw4a6cf411997-01-13 22:44:55 +0000827 (1) gettimeofday() -- resolution in microseconds
828 (2) ftime() -- resolution in milliseconds
829 (3) time() -- resolution in seconds
830 In all cases the return value is a float in seconds.
831 Since on some systems (e.g. SCO ODT 3.0) gettimeofday() may
832 fail, so we fall back on ftime() or time().
833 Note: clock resolution does not imply clock accuracy! */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000834#ifdef HAVE_GETTIMEOFDAY
Barry Warsaw4a6cf411997-01-13 22:44:55 +0000835 {
836 struct timeval t;
Guido van Rossum3bbc62e1995-01-02 19:30:30 +0000837#ifdef GETTIMEOFDAY_NO_TZ
Barry Warsaw4a6cf411997-01-13 22:44:55 +0000838 if (gettimeofday(&t) == 0)
839 return (double)t.tv_sec + t.tv_usec*0.000001;
Guido van Rossum3bbc62e1995-01-02 19:30:30 +0000840#else /* !GETTIMEOFDAY_NO_TZ */
Barry Warsaw4a6cf411997-01-13 22:44:55 +0000841 if (gettimeofday(&t, (struct timezone *)NULL) == 0)
842 return (double)t.tv_sec + t.tv_usec*0.000001;
Guido van Rossum3bbc62e1995-01-02 19:30:30 +0000843#endif /* !GETTIMEOFDAY_NO_TZ */
Barry Warsaw4a6cf411997-01-13 22:44:55 +0000844 }
Guido van Rossumb6775db1994-08-01 11:34:53 +0000845#endif /* !HAVE_GETTIMEOFDAY */
Barry Warsaw4a6cf411997-01-13 22:44:55 +0000846 {
Guido van Rossumd3eb5771999-03-09 16:07:23 +0000847#if defined(HAVE_FTIME)
Barry Warsaw4a6cf411997-01-13 22:44:55 +0000848 struct timeb t;
849 ftime(&t);
850 return (double)t.time + (double)t.millitm * (double)0.001;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000851#else /* !HAVE_FTIME */
Barry Warsaw4a6cf411997-01-13 22:44:55 +0000852 time_t secs;
853 time(&secs);
854 return (double)secs;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000855#endif /* !HAVE_FTIME */
Barry Warsaw4a6cf411997-01-13 22:44:55 +0000856 }
Guido van Rossum426035c1991-02-19 12:27:35 +0000857}
858
Guido van Rossumb6775db1994-08-01 11:34:53 +0000859
860/* Implement floatsleep() for various platforms.
861 When interrupted (or when another error occurs), return -1 and
862 set an exception; else return 0. */
863
864static int
Guido van Rossuma320fd31995-03-09 12:14:15 +0000865floatsleep(double secs)
Guido van Rossum426035c1991-02-19 12:27:35 +0000866{
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000867/* XXX Should test for MS_WINDOWS first! */
Andrew MacIntyre7bf68332002-03-03 02:59:16 +0000868#if defined(HAVE_SELECT) && !defined(__BEOS__) && !defined(__EMX__)
Guido van Rossum426035c1991-02-19 12:27:35 +0000869 struct timeval t;
Guido van Rossum775f4da1993-01-09 17:18:52 +0000870 double frac;
Guido van Rossum775f4da1993-01-09 17:18:52 +0000871 frac = fmod(secs, 1.0);
872 secs = floor(secs);
873 t.tv_sec = (long)secs;
874 t.tv_usec = (long)(frac*1000000.0);
Guido van Rossum8607ae21997-11-03 22:04:46 +0000875 Py_BEGIN_ALLOW_THREADS
Guido van Rossumb6775db1994-08-01 11:34:53 +0000876 if (select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &t) != 0) {
Guido van Rossum09cbb011999-11-08 15:32:27 +0000877#ifdef EINTR
Guido van Rossuma5456d51999-08-19 14:40:27 +0000878 if (errno != EINTR) {
Guido van Rossum09cbb011999-11-08 15:32:27 +0000879#else
880 if (1) {
881#endif
Andrew M. Kuchlingc24ca4b2000-03-24 20:35:20 +0000882 Py_BLOCK_THREADS
Guido van Rossuma5456d51999-08-19 14:40:27 +0000883 PyErr_SetFromErrno(PyExc_IOError);
884 return -1;
885 }
Guido van Rossumb6775db1994-08-01 11:34:53 +0000886 }
Guido van Rossum8607ae21997-11-03 22:04:46 +0000887 Py_END_ALLOW_THREADS
Martin v. Löwis02af9642002-01-16 11:04:06 +0000888#elif defined(__WATCOMC__) && !defined(__QNX__)
Guido van Rossumbceeac81996-05-23 22:53:47 +0000889 /* XXX Can't interrupt this sleep */
Guido van Rossum8607ae21997-11-03 22:04:46 +0000890 Py_BEGIN_ALLOW_THREADS
Guido van Rossumbceeac81996-05-23 22:53:47 +0000891 delay((int)(secs * 1000 + 0.5)); /* delay() uses milliseconds */
Guido van Rossum8607ae21997-11-03 22:04:46 +0000892 Py_END_ALLOW_THREADS
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000893#elif defined(MS_WINDOWS)
Fred Drake0e123952000-06-29 21:31:02 +0000894 {
895 double millisecs = secs * 1000.0;
Tim Peters513a1cd2003-01-19 04:54:58 +0000896 unsigned long ul_millis;
897
Fred Drake0e123952000-06-29 21:31:02 +0000898 if (millisecs > (double)ULONG_MAX) {
Tim Peters513a1cd2003-01-19 04:54:58 +0000899 PyErr_SetString(PyExc_OverflowError,
900 "sleep length is too large");
Fred Drake0e123952000-06-29 21:31:02 +0000901 return -1;
902 }
Fred Drake0e123952000-06-29 21:31:02 +0000903 Py_BEGIN_ALLOW_THREADS
Tim Peters513a1cd2003-01-19 04:54:58 +0000904 /* Allow sleep(0) to maintain win32 semantics, and as decreed
905 * by Guido, only the main thread can be interrupted.
906 */
907 ul_millis = (unsigned long)millisecs;
908 if (ul_millis == 0 ||
909 main_thread != PyThread_get_thread_ident())
910 Sleep(ul_millis);
Mark Hammond975e3922002-07-16 01:29:19 +0000911 else {
912 DWORD rc;
913 ResetEvent(hInterruptEvent);
Tim Peters513a1cd2003-01-19 04:54:58 +0000914 rc = WaitForSingleObject(hInterruptEvent, ul_millis);
915 if (rc == WAIT_OBJECT_0) {
916 /* Yield to make sure real Python signal
917 * handler called.
918 */
Mark Hammond975e3922002-07-16 01:29:19 +0000919 Sleep(1);
920 Py_BLOCK_THREADS
Mark Hammond975e3922002-07-16 01:29:19 +0000921 errno = EINTR;
922 PyErr_SetFromErrno(PyExc_IOError);
923 return -1;
924 }
925 }
Fred Drake0e123952000-06-29 21:31:02 +0000926 Py_END_ALLOW_THREADS
927 }
Martin v. Löwis02af9642002-01-16 11:04:06 +0000928#elif defined(PYOS_OS2)
Guido van Rossum8e9ebfd1997-11-22 21:53:48 +0000929 /* This Sleep *IS* Interruptable by Exceptions */
Guido van Rossum1d0d7e41997-12-29 20:03:10 +0000930 Py_BEGIN_ALLOW_THREADS
Guido van Rossum8e9ebfd1997-11-22 21:53:48 +0000931 if (DosSleep(secs * 1000) != NO_ERROR) {
Guido van Rossum1d0d7e41997-12-29 20:03:10 +0000932 Py_BLOCK_THREADS
Guido van Rossum8e9ebfd1997-11-22 21:53:48 +0000933 PyErr_SetFromErrno(PyExc_IOError);
934 return -1;
935 }
Guido van Rossum1d0d7e41997-12-29 20:03:10 +0000936 Py_END_ALLOW_THREADS
Martin v. Löwis02af9642002-01-16 11:04:06 +0000937#elif defined(__BEOS__)
Guido van Rossumbcc20741998-08-04 22:53:56 +0000938 /* This sleep *CAN BE* interrupted. */
939 {
Guido van Rossumbcc20741998-08-04 22:53:56 +0000940 if( secs <= 0.0 ) {
941 return;
942 }
Guido van Rossum10b164a2001-09-25 13:59:01 +0000943
Guido van Rossumbcc20741998-08-04 22:53:56 +0000944 Py_BEGIN_ALLOW_THREADS
Guido van Rossumd3eb5771999-03-09 16:07:23 +0000945 /* BeOS snooze() is in microseconds... */
946 if( snooze( (bigtime_t)( secs * 1000.0 * 1000.0 ) ) == B_INTERRUPTED ) {
Guido van Rossumbcc20741998-08-04 22:53:56 +0000947 Py_BLOCK_THREADS
948 PyErr_SetFromErrno( PyExc_IOError );
949 return -1;
950 }
951 Py_END_ALLOW_THREADS
952 }
Martin v. Löwis02af9642002-01-16 11:04:06 +0000953#elif defined(RISCOS)
Guido van Rossumbceccf52001-04-10 22:07:43 +0000954 if (secs <= 0.0)
955 return 0;
956 Py_BEGIN_ALLOW_THREADS
957 /* This sleep *CAN BE* interrupted. */
Martin v. Löwisa94568a2003-05-10 07:36:56 +0000958 if ( riscos_sleep(secs) )
Guido van Rossumbceccf52001-04-10 22:07:43 +0000959 return -1;
960 Py_END_ALLOW_THREADS
Martin v. Löwis02af9642002-01-16 11:04:06 +0000961#elif defined(PLAN9)
962 {
963 double millisecs = secs * 1000.0;
964 if (millisecs > (double)LONG_MAX) {
965 PyErr_SetString(PyExc_OverflowError, "sleep length is too large");
966 return -1;
967 }
968 /* This sleep *CAN BE* interrupted. */
969 Py_BEGIN_ALLOW_THREADS
970 if(sleep((long)millisecs) < 0){
971 Py_BLOCK_THREADS
972 PyErr_SetFromErrno(PyExc_IOError);
973 return -1;
974 }
975 Py_END_ALLOW_THREADS
976 }
977#else
Guido van Rossumb6775db1994-08-01 11:34:53 +0000978 /* XXX Can't interrupt this sleep */
Guido van Rossum8607ae21997-11-03 22:04:46 +0000979 Py_BEGIN_ALLOW_THREADS
Guido van Rossumb6775db1994-08-01 11:34:53 +0000980 sleep((int)secs);
Guido van Rossum8607ae21997-11-03 22:04:46 +0000981 Py_END_ALLOW_THREADS
Martin v. Löwis02af9642002-01-16 11:04:06 +0000982#endif
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000983
Guido van Rossumb6775db1994-08-01 11:34:53 +0000984 return 0;
Guido van Rossum80c9d881991-04-16 08:47:51 +0000985}
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000986
987