blob: 402e349b42045baaffd903dd0c7cf7f055a2e1e8 [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
Martin v. Löwis0e8bd7e2006-06-10 12:23:46 +000022#ifdef HAVE_SYS_TYPES_H
Guido van Rossumb6775db1994-08-01 11:34:53 +000023#include <sys/types.h>
Martin v. Löwis0e8bd7e2006-06-10 12:23:46 +000024#endif /* HAVE_SYS_TYPES_H */
Guido van Rossum6d946f91992-08-14 13:49:30 +000025
Guido van Rossumb6775db1994-08-01 11:34:53 +000026#ifdef QUICKWIN
27#include <io.h>
28#endif
29
Guido van Rossumb6775db1994-08-01 11:34:53 +000030#ifdef HAVE_FTIME
31#include <sys/timeb.h>
Guido van Rossum8e9ebfd1997-11-22 21:53:48 +000032#if !defined(MS_WINDOWS) && !defined(PYOS_OS2)
Thomas Woutersbd4bc4e2000-07-22 23:57:55 +000033extern int ftime(struct timeb *);
Guido van Rossum52174571996-12-09 18:38:52 +000034#endif /* MS_WINDOWS */
35#endif /* HAVE_FTIME */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000036
Guido van Rossum7bf22de1997-12-02 20:34:19 +000037#if defined(__WATCOMC__) && !defined(__QNX__)
Guido van Rossumbceeac81996-05-23 22:53:47 +000038#include <i86.h>
39#else
Guido van Rossumcac6c721996-09-06 13:34:02 +000040#ifdef MS_WINDOWS
Mark Hammond975e3922002-07-16 01:29:19 +000041#define WIN32_LEAN_AND_MEAN
Guido van Rossum258ccd42001-03-02 06:53:29 +000042#include <windows.h>
Mark Hammond975e3922002-07-16 01:29:19 +000043#include "pythread.h"
44
45/* helper to allow us to interrupt sleep() on Windows*/
46static HANDLE hInterruptEvent = NULL;
47static BOOL WINAPI PyCtrlHandler(DWORD dwCtrlType)
48{
49 SetEvent(hInterruptEvent);
50 /* allow other default handlers to be called.
51 Default Python handler will setup the
52 KeyboardInterrupt exception.
53 */
54 return FALSE;
55}
56static long main_thread;
57
58
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000059#if defined(__BORLANDC__)
Guido van Rossumb2fb3641996-09-07 00:47:35 +000060/* These overrides not needed for Win32 */
Guido van Rossumb6775db1994-08-01 11:34:53 +000061#define timezone _timezone
Guido van Rossumcc081121995-03-14 15:05:41 +000062#define tzname _tzname
63#define daylight _daylight
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000064#endif /* __BORLANDC__ */
Guido van Rossumcac6c721996-09-06 13:34:02 +000065#endif /* MS_WINDOWS */
Guido van Rossum7bf22de1997-12-02 20:34:19 +000066#endif /* !__WATCOMC__ || __QNX__ */
Guido van Rossum234f9421993-06-17 12:35:49 +000067
Tim Peters7a822da2006-05-25 21:50:17 +000068#if defined(MS_WINDOWS) && !defined(__BORLANDC__)
Tim Petersc285e622006-05-25 22:25:25 +000069/* Win32 has better clock replacement; we have our own version below. */
70#undef HAVE_CLOCK
Tim Peters7a822da2006-05-25 21:50:17 +000071#endif /* MS_WINDOWS && !defined(__BORLANDC__) */
Guido van Rossum3917c221997-04-02 05:35:28 +000072
Andrew MacIntyre7bf68332002-03-03 02:59:16 +000073#if defined(PYOS_OS2)
74#define INCL_DOS
75#define INCL_ERRORS
76#include <os2.h>
77#endif
78
Guido van Rossum8e9ebfd1997-11-22 21:53:48 +000079#if defined(PYCC_VACPP)
Guido van Rossum26452411998-09-28 22:07:11 +000080#include <sys/time.h>
Guido van Rossum8e9ebfd1997-11-22 21:53:48 +000081#endif
82
Guido van Rossumbcc20741998-08-04 22:53:56 +000083#ifdef __BEOS__
Fred Drake56221a72000-08-15 18:52:33 +000084#include <time.h>
Guido van Rossumbcc20741998-08-04 22:53:56 +000085/* For bigtime_t, snooze(). - [cjh] */
86#include <support/SupportDefs.h>
87#include <kernel/OS.h>
88#endif
89
Martin v. Löwisa94568a2003-05-10 07:36:56 +000090#ifdef RISCOS
91extern int riscos_sleep(double);
92#endif
93
Guido van Rossum234f9421993-06-17 12:35:49 +000094/* Forward declarations */
Tim Petersdbd9ba62000-07-09 03:09:57 +000095static int floatsleep(double);
Thomas Woutersed77bac2000-07-24 15:26:39 +000096static double floattime(void);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000097
Guido van Rossumcfbaecc1998-08-25 14:51:12 +000098/* For Y2K check */
99static PyObject *moddict;
100
Tim Peters1b6f7a92004-06-20 02:50:16 +0000101/* Exposed in timefuncs.h. */
102time_t
Brett Cannon298c3802004-06-19 20:48:43 +0000103_PyTime_DoubleToTimet(double x)
104{
105 time_t result;
106 double diff;
107
108 result = (time_t)x;
109 /* How much info did we lose? time_t may be an integral or
110 * floating type, and we don't know which. If it's integral,
111 * we don't know whether C truncates, rounds, returns the floor,
112 * etc. If we lost a second or more, the C rounding is
113 * unreasonable, or the input just doesn't fit in a time_t;
114 * call it an error regardless. Note that the original cast to
115 * time_t can cause a C error too, but nothing we can do to
116 * worm around that.
117 */
118 diff = x - (double)result;
119 if (diff <= -1.0 || diff >= 1.0) {
120 PyErr_SetString(PyExc_ValueError,
121 "timestamp out of range for platform time_t");
122 result = (time_t)-1;
123 }
124 return result;
125}
126
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000127static PyObject *
Georg Brandl96a8c392006-05-29 21:04:52 +0000128time_time(PyObject *self, PyObject *unused)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000129{
Guido van Rossumb6775db1994-08-01 11:34:53 +0000130 double secs;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000131 secs = floattime();
132 if (secs == 0.0) {
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000133 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossuma2b7f401993-01-04 09:09:59 +0000134 return NULL;
135 }
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000136 return PyFloat_FromDouble(secs);
Guido van Rossumb6775db1994-08-01 11:34:53 +0000137}
138
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000139PyDoc_STRVAR(time_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000140"time() -> floating point number\n\
141\n\
142Return the current time in seconds since the Epoch.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000143Fractions of a second may be present if the system clock provides them.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000144
Guido van Rossumb6775db1994-08-01 11:34:53 +0000145#ifdef HAVE_CLOCK
146
147#ifndef CLOCKS_PER_SEC
Guido van Rossum1b66a4f1996-02-25 04:50:33 +0000148#ifdef CLK_TCK
149#define CLOCKS_PER_SEC CLK_TCK
150#else
Guido van Rossumb6775db1994-08-01 11:34:53 +0000151#define CLOCKS_PER_SEC 1000000
152#endif
Guido van Rossum1b66a4f1996-02-25 04:50:33 +0000153#endif
Guido van Rossumb6775db1994-08-01 11:34:53 +0000154
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000155static PyObject *
Georg Brandl96a8c392006-05-29 21:04:52 +0000156time_clock(PyObject *self, PyObject *unused)
Guido van Rossumb6775db1994-08-01 11:34:53 +0000157{
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000158 return PyFloat_FromDouble(((double)clock()) / CLOCKS_PER_SEC);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000159}
Guido van Rossumb6775db1994-08-01 11:34:53 +0000160#endif /* HAVE_CLOCK */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000161
Tim Petersc285e622006-05-25 22:25:25 +0000162#if defined(MS_WINDOWS) && !defined(__BORLANDC__)
Mark Hammond7ba5e812002-02-12 04:02:33 +0000163/* Due to Mark Hammond and Tim Peters */
Guido van Rossum3917c221997-04-02 05:35:28 +0000164static PyObject *
Georg Brandl96a8c392006-05-29 21:04:52 +0000165time_clock(PyObject *self, PyObject *unused)
Guido van Rossum3917c221997-04-02 05:35:28 +0000166{
Tim Peters9ad4b682002-02-13 05:14:18 +0000167 static LARGE_INTEGER ctrStart;
Mark Hammond7ba5e812002-02-12 04:02:33 +0000168 static double divisor = 0.0;
Tim Peters9ad4b682002-02-13 05:14:18 +0000169 LARGE_INTEGER now;
Mark Hammond7ba5e812002-02-12 04:02:33 +0000170 double diff;
Guido van Rossum3917c221997-04-02 05:35:28 +0000171
Mark Hammond7ba5e812002-02-12 04:02:33 +0000172 if (divisor == 0.0) {
Tim Peters9ad4b682002-02-13 05:14:18 +0000173 LARGE_INTEGER freq;
174 QueryPerformanceCounter(&ctrStart);
175 if (!QueryPerformanceFrequency(&freq) || freq.QuadPart == 0) {
Mark Hammond7ba5e812002-02-12 04:02:33 +0000176 /* Unlikely to happen - this works on all intel
177 machines at least! Revert to clock() */
Guido van Rossum3917c221997-04-02 05:35:28 +0000178 return PyFloat_FromDouble(clock());
179 }
Tim Peters9ad4b682002-02-13 05:14:18 +0000180 divisor = (double)freq.QuadPart;
Guido van Rossum3917c221997-04-02 05:35:28 +0000181 }
Tim Peters9ad4b682002-02-13 05:14:18 +0000182 QueryPerformanceCounter(&now);
183 diff = (double)(now.QuadPart - ctrStart.QuadPart);
Mark Hammond7ba5e812002-02-12 04:02:33 +0000184 return PyFloat_FromDouble(diff / divisor);
Guido van Rossum3917c221997-04-02 05:35:28 +0000185}
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000186
Guido van Rossum3917c221997-04-02 05:35:28 +0000187#define HAVE_CLOCK /* So it gets included in the methods */
Tim Petersc285e622006-05-25 22:25:25 +0000188#endif /* MS_WINDOWS && !defined(__BORLANDC__) */
Guido van Rossum3917c221997-04-02 05:35:28 +0000189
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000190#ifdef HAVE_CLOCK
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000191PyDoc_STRVAR(clock_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000192"clock() -> floating point number\n\
193\n\
194Return the CPU time or real time since the start of the process or since\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000195the first call to clock(). This has as much precision as the system\n\
196records.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000197#endif
198
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000199static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000200time_sleep(PyObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000201{
Guido van Rossum775f4da1993-01-09 17:18:52 +0000202 double secs;
Thomas Woutersfe385252001-01-19 23:16:56 +0000203 if (!PyArg_ParseTuple(args, "d:sleep", &secs))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000204 return NULL;
Guido van Rossum8607ae21997-11-03 22:04:46 +0000205 if (floatsleep(secs) != 0)
206 return NULL;
207 Py_INCREF(Py_None);
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000208 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000209}
210
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000211PyDoc_STRVAR(sleep_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000212"sleep(seconds)\n\
213\n\
214Delay execution for a given number of seconds. The argument may be\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000215a floating point number for subsecond precision.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000216
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000217static PyStructSequence_Field struct_time_type_fields[] = {
218 {"tm_year", NULL},
219 {"tm_mon", NULL},
220 {"tm_mday", NULL},
221 {"tm_hour", NULL},
222 {"tm_min", NULL},
223 {"tm_sec", NULL},
224 {"tm_wday", NULL},
225 {"tm_yday", NULL},
226 {"tm_isdst", NULL},
227 {0}
228};
229
230static PyStructSequence_Desc struct_time_type_desc = {
Guido van Rossum14648392001-12-08 18:02:58 +0000231 "time.struct_time",
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000232 NULL,
233 struct_time_type_fields,
234 9,
235};
Tim Peters9ad4b682002-02-13 05:14:18 +0000236
Martin v. Löwis19ab6c92006-04-16 18:55:50 +0000237static int initialized;
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000238static PyTypeObject StructTimeType;
239
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000240static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000241tmtotuple(struct tm *p)
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000242{
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000243 PyObject *v = PyStructSequence_New(&StructTimeType);
244 if (v == NULL)
245 return NULL;
Tim Peters9ad4b682002-02-13 05:14:18 +0000246
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000247#define SET(i,val) PyStructSequence_SET_ITEM(v, i, PyInt_FromLong((long) val))
248
249 SET(0, p->tm_year + 1900);
250 SET(1, p->tm_mon + 1); /* Want January == 1 */
251 SET(2, p->tm_mday);
252 SET(3, p->tm_hour);
253 SET(4, p->tm_min);
254 SET(5, p->tm_sec);
255 SET(6, (p->tm_wday + 6) % 7); /* Want Monday == 0 */
256 SET(7, p->tm_yday + 1); /* Want January, 1 == 1 */
257 SET(8, p->tm_isdst);
258#undef SET
259 if (PyErr_Occurred()) {
260 Py_XDECREF(v);
261 return NULL;
262 }
263
264 return v;
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000265}
266
267static PyObject *
Brett Cannon298c3802004-06-19 20:48:43 +0000268time_convert(double when, struct tm * (*function)(const time_t *))
Guido van Rossum234f9421993-06-17 12:35:49 +0000269{
Guido van Rossum6e8583d1996-10-08 14:19:52 +0000270 struct tm *p;
Brett Cannon298c3802004-06-19 20:48:43 +0000271 time_t whent = _PyTime_DoubleToTimet(when);
272
273 if (whent == (time_t)-1 && PyErr_Occurred())
274 return NULL;
Guido van Rossum6e8583d1996-10-08 14:19:52 +0000275 errno = 0;
Brett Cannon298c3802004-06-19 20:48:43 +0000276 p = function(&whent);
Guido van Rossum6e8583d1996-10-08 14:19:52 +0000277 if (p == NULL) {
278#ifdef EINVAL
Guido van Rossum0b1ff661996-11-02 17:31:22 +0000279 if (errno == 0)
Guido van Rossum6e8583d1996-10-08 14:19:52 +0000280 errno = EINVAL;
281#endif
Tim Peters8b19a932003-01-17 20:08:54 +0000282 return PyErr_SetFromErrno(PyExc_ValueError);
Guido van Rossum6e8583d1996-10-08 14:19:52 +0000283 }
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000284 return tmtotuple(p);
Guido van Rossum234f9421993-06-17 12:35:49 +0000285}
286
Fred Drakef901abd2004-08-03 17:58:55 +0000287/* Parse arg tuple that can contain an optional float-or-None value;
288 format needs to be "|O:name".
289 Returns non-zero on success (parallels PyArg_ParseTuple).
290*/
291static int
292parse_time_double_args(PyObject *args, char *format, double *pwhen)
293{
294 PyObject *ot = NULL;
295
296 if (!PyArg_ParseTuple(args, format, &ot))
297 return 0;
298 if (ot == NULL || ot == Py_None)
299 *pwhen = floattime();
300 else {
301 double when = PyFloat_AsDouble(ot);
302 if (PyErr_Occurred())
303 return 0;
304 *pwhen = when;
305 }
306 return 1;
307}
308
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000309static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000310time_gmtime(PyObject *self, PyObject *args)
Guido van Rossum234f9421993-06-17 12:35:49 +0000311{
312 double when;
Fred Drakef901abd2004-08-03 17:58:55 +0000313 if (!parse_time_double_args(args, "|O:gmtime", &when))
Guido van Rossum234f9421993-06-17 12:35:49 +0000314 return NULL;
Brett Cannon298c3802004-06-19 20:48:43 +0000315 return time_convert(when, gmtime);
Guido van Rossum234f9421993-06-17 12:35:49 +0000316}
317
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000318PyDoc_STRVAR(gmtime_doc,
Fred Drake193a3f62002-03-12 21:38:49 +0000319"gmtime([seconds]) -> (tm_year, tm_mon, tm_day, tm_hour, tm_min,\n\
320 tm_sec, tm_wday, tm_yday, tm_isdst)\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000321\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000322Convert seconds since the Epoch to a time tuple expressing UTC (a.k.a.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000323GMT). When 'seconds' is not passed in, convert the current time instead.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000324
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000325static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000326time_localtime(PyObject *self, PyObject *args)
Guido van Rossum234f9421993-06-17 12:35:49 +0000327{
328 double when;
Fred Drakef901abd2004-08-03 17:58:55 +0000329 if (!parse_time_double_args(args, "|O:localtime", &when))
Guido van Rossum234f9421993-06-17 12:35:49 +0000330 return NULL;
Brett Cannon298c3802004-06-19 20:48:43 +0000331 return time_convert(when, localtime);
Guido van Rossum234f9421993-06-17 12:35:49 +0000332}
333
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000334PyDoc_STRVAR(localtime_doc,
Fred Drake193a3f62002-03-12 21:38:49 +0000335"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 +0000336\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000337Convert seconds since the Epoch to a time tuple expressing local time.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000338When 'seconds' is not passed in, convert the current time instead.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000339
Guido van Rossum9e90a671993-06-24 11:10:19 +0000340static int
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000341gettmarg(PyObject *args, struct tm *p)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000342{
Guido van Rossumcfbaecc1998-08-25 14:51:12 +0000343 int y;
Thomas Wouters334fb892000-07-25 12:56:38 +0000344 memset((void *) p, '\0', sizeof(struct tm));
Guido van Rossumcfbaecc1998-08-25 14:51:12 +0000345
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000346 if (!PyArg_Parse(args, "(iiiiiiiii)",
Guido van Rossumcfbaecc1998-08-25 14:51:12 +0000347 &y,
Barry Warsaw4a6cf411997-01-13 22:44:55 +0000348 &p->tm_mon,
349 &p->tm_mday,
350 &p->tm_hour,
351 &p->tm_min,
352 &p->tm_sec,
353 &p->tm_wday,
354 &p->tm_yday,
355 &p->tm_isdst))
Guido van Rossum9e90a671993-06-24 11:10:19 +0000356 return 0;
Guido van Rossumcfbaecc1998-08-25 14:51:12 +0000357 if (y < 1900) {
358 PyObject *accept = PyDict_GetItemString(moddict,
359 "accept2dyear");
360 if (accept == NULL || !PyInt_Check(accept) ||
361 PyInt_AsLong(accept) == 0) {
362 PyErr_SetString(PyExc_ValueError,
363 "year >= 1900 required");
364 return 0;
365 }
366 if (69 <= y && y <= 99)
367 y += 1900;
368 else if (0 <= y && y <= 68)
369 y += 2000;
370 else {
371 PyErr_SetString(PyExc_ValueError,
Skip Montanaro1a10aac2001-08-22 12:39:16 +0000372 "year out of range");
Guido van Rossumcfbaecc1998-08-25 14:51:12 +0000373 return 0;
374 }
375 }
376 p->tm_year = y - 1900;
Guido van Rossum9e90a671993-06-24 11:10:19 +0000377 p->tm_mon--;
378 p->tm_wday = (p->tm_wday + 1) % 7;
379 p->tm_yday--;
380 return 1;
381}
382
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000383#ifdef HAVE_STRFTIME
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000384static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000385time_strftime(PyObject *self, PyObject *args)
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000386{
Thomas Woutersfe385252001-01-19 23:16:56 +0000387 PyObject *tup = NULL;
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000388 struct tm buf;
389 const char *fmt;
Guido van Rossumfa481162000-06-28 21:33:59 +0000390 size_t fmtlen, buflen;
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000391 char *outbuf = 0;
Guido van Rossumfa481162000-06-28 21:33:59 +0000392 size_t i;
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000393
Thomas Wouters334fb892000-07-25 12:56:38 +0000394 memset((void *) &buf, '\0', sizeof(buf));
Guido van Rossum1f41f841998-04-27 19:04:26 +0000395
Thomas Woutersfe385252001-01-19 23:16:56 +0000396 if (!PyArg_ParseTuple(args, "s|O:strftime", &fmt, &tup))
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000397 return NULL;
Thomas Woutersfe385252001-01-19 23:16:56 +0000398
399 if (tup == NULL) {
400 time_t tt = time(NULL);
401 buf = *localtime(&tt);
402 } else if (!gettmarg(tup, &buf))
403 return NULL;
Guido van Rossum10b164a2001-09-25 13:59:01 +0000404
Brett Cannond1080a32004-03-02 04:38:10 +0000405 /* Checks added to make sure strftime() does not crash Python by
406 indexing blindly into some array for a textual representation
407 by some bad index (fixes bug #897625).
Tim Peters1b6f7a92004-06-20 02:50:16 +0000408
Brett Cannond1080a32004-03-02 04:38:10 +0000409 No check for year since handled in gettmarg().
410 */
411 if (buf.tm_mon < 0 || buf.tm_mon > 11) {
412 PyErr_SetString(PyExc_ValueError, "month out of range");
413 return NULL;
414 }
415 if (buf.tm_mday < 1 || buf.tm_mday > 31) {
416 PyErr_SetString(PyExc_ValueError, "day of month out of range");
417 return NULL;
418 }
419 if (buf.tm_hour < 0 || buf.tm_hour > 23) {
420 PyErr_SetString(PyExc_ValueError, "hour out of range");
421 return NULL;
422 }
423 if (buf.tm_min < 0 || buf.tm_min > 59) {
424 PyErr_SetString(PyExc_ValueError, "minute out of range");
425 return NULL;
426 }
427 if (buf.tm_sec < 0 || buf.tm_sec > 61) {
428 PyErr_SetString(PyExc_ValueError, "seconds out of range");
429 return NULL;
430 }
431 /* tm_wday does not need checking of its upper-bound since taking
432 ``% 7`` in gettmarg() automatically restricts the range. */
433 if (buf.tm_wday < 0) {
434 PyErr_SetString(PyExc_ValueError, "day of week out of range");
435 return NULL;
436 }
437 if (buf.tm_yday < 0 || buf.tm_yday > 365) {
438 PyErr_SetString(PyExc_ValueError, "day of year out of range");
439 return NULL;
440 }
441 if (buf.tm_isdst < -1 || buf.tm_isdst > 1) {
442 PyErr_SetString(PyExc_ValueError,
443 "daylight savings flag out of range");
444 return NULL;
445 }
446
Guido van Rossumc222ec21999-02-23 00:00:10 +0000447 fmtlen = strlen(fmt);
448
Barry Warsaw4a6cf411997-01-13 22:44:55 +0000449 /* I hate these functions that presume you know how big the output
450 * will be ahead of time...
451 */
Guido van Rossumc222ec21999-02-23 00:00:10 +0000452 for (i = 1024; ; i += i) {
Anthony Baxter7cbc0f52006-04-13 07:19:01 +0000453 outbuf = (char *)malloc(i);
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000454 if (outbuf == NULL) {
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000455 return PyErr_NoMemory();
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000456 }
Guido van Rossumc222ec21999-02-23 00:00:10 +0000457 buflen = strftime(outbuf, i, fmt, &buf);
458 if (buflen > 0 || i >= 256 * fmtlen) {
459 /* If the buffer is 256 times as long as the format,
460 it's probably not failing for lack of room!
461 More likely, the format yields an empty result,
462 e.g. an empty format, or %Z when the timezone
463 is unknown. */
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000464 PyObject *ret;
Guido van Rossumc222ec21999-02-23 00:00:10 +0000465 ret = PyString_FromStringAndSize(outbuf, buflen);
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000466 free(outbuf);
467 return ret;
468 }
469 free(outbuf);
Kristján Valur Jónsson74c3ea02006-07-03 14:59:05 +0000470#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
Kristján Valur Jónssonf6083172006-06-12 15:45:12 +0000471 /* VisualStudio .NET 2005 does this properly */
472 if (buflen == 0 && errno == EINVAL) {
473 PyErr_SetString(PyExc_ValueError, "Invalid format string");
474 return 0;
475 }
476#endif
477
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000478 }
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000479}
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000480
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000481PyDoc_STRVAR(strftime_doc,
Thomas Woutersfe385252001-01-19 23:16:56 +0000482"strftime(format[, tuple]) -> string\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000483\n\
484Convert a time tuple to a string according to a format specification.\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000485See the library reference manual for formatting codes. When the time tuple\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000486is not present, current time as returned by localtime() is used.");
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000487#endif /* HAVE_STRFTIME */
488
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000489static PyObject *
490time_strptime(PyObject *self, PyObject *args)
491{
492 PyObject *strptime_module = PyImport_ImportModule("_strptime");
Raymond Hettinger502168a2003-04-10 16:03:22 +0000493 PyObject *strptime_result;
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000494
Tim Peters513a1cd2003-01-19 04:54:58 +0000495 if (!strptime_module)
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000496 return NULL;
Raymond Hettinger502168a2003-04-10 16:03:22 +0000497 strptime_result = PyObject_CallMethod(strptime_module, "strptime", "O", args);
498 Py_DECREF(strptime_module);
499 return strptime_result;
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000500}
501
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000502PyDoc_STRVAR(strptime_doc,
Brett Cannon20def8b2003-07-01 05:16:08 +0000503"strptime(string, format) -> struct_time\n\
Martin v. Löwisb3cfc1d2001-12-02 12:27:43 +0000504\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000505Parse a string to a time tuple according to a format specification.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000506See the library reference manual for formatting codes (same as strftime()).");
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000507
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000508
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000509static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000510time_asctime(PyObject *self, PyObject *args)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000511{
Thomas Woutersfe385252001-01-19 23:16:56 +0000512 PyObject *tup = NULL;
Guido van Rossum9e90a671993-06-24 11:10:19 +0000513 struct tm buf;
514 char *p;
Georg Brandl96a8c392006-05-29 21:04:52 +0000515 if (!PyArg_UnpackTuple(args, "asctime", 0, 1, &tup))
Guido van Rossumb2b42dd2000-01-12 16:38:20 +0000516 return NULL;
Thomas Woutersfe385252001-01-19 23:16:56 +0000517 if (tup == NULL) {
518 time_t tt = time(NULL);
519 buf = *localtime(&tt);
520 } else if (!gettmarg(tup, &buf))
Guido van Rossum9e90a671993-06-24 11:10:19 +0000521 return NULL;
522 p = asctime(&buf);
523 if (p[24] == '\n')
524 p[24] = '\0';
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000525 return PyString_FromString(p);
Guido van Rossum9e90a671993-06-24 11:10:19 +0000526}
527
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000528PyDoc_STRVAR(asctime_doc,
Thomas Woutersfe385252001-01-19 23:16:56 +0000529"asctime([tuple]) -> string\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000530\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000531Convert a time tuple to a string, e.g. 'Sat Jun 06 16:26:11 1998'.\n\
532When the time tuple is not present, current time as returned by localtime()\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000533is used.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000534
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000535static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000536time_ctime(PyObject *self, PyObject *args)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000537{
Fred Drakef901abd2004-08-03 17:58:55 +0000538 PyObject *ot = NULL;
Guido van Rossum9e90a671993-06-24 11:10:19 +0000539 time_t tt;
540 char *p;
Guido van Rossum10b164a2001-09-25 13:59:01 +0000541
Georg Brandl96a8c392006-05-29 21:04:52 +0000542 if (!PyArg_UnpackTuple(args, "ctime", 0, 1, &ot))
Fred Drakef901abd2004-08-03 17:58:55 +0000543 return NULL;
544 if (ot == NULL || ot == Py_None)
Thomas Woutersfe385252001-01-19 23:16:56 +0000545 tt = time(NULL);
546 else {
Fred Drakef901abd2004-08-03 17:58:55 +0000547 double dt = PyFloat_AsDouble(ot);
548 if (PyErr_Occurred())
Thomas Woutersfe385252001-01-19 23:16:56 +0000549 return NULL;
Brett Cannon298c3802004-06-19 20:48:43 +0000550 tt = _PyTime_DoubleToTimet(dt);
551 if (tt == (time_t)-1 && PyErr_Occurred())
552 return NULL;
Thomas Woutersfe385252001-01-19 23:16:56 +0000553 }
Guido van Rossum9e90a671993-06-24 11:10:19 +0000554 p = ctime(&tt);
Guido van Rossum78535701998-03-03 22:19:10 +0000555 if (p == NULL) {
556 PyErr_SetString(PyExc_ValueError, "unconvertible time");
557 return NULL;
558 }
Guido van Rossum9e90a671993-06-24 11:10:19 +0000559 if (p[24] == '\n')
560 p[24] = '\0';
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000561 return PyString_FromString(p);
Guido van Rossum9e90a671993-06-24 11:10:19 +0000562}
563
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000564PyDoc_STRVAR(ctime_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000565"ctime(seconds) -> string\n\
566\n\
567Convert a time in seconds since the Epoch to a string in local time.\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000568This is equivalent to asctime(localtime(seconds)). When the time tuple is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000569not present, current time as returned by localtime() is used.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000570
Guido van Rossum60cd8131998-03-06 17:16:21 +0000571#ifdef HAVE_MKTIME
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000572static PyObject *
Georg Brandl96a8c392006-05-29 21:04:52 +0000573time_mktime(PyObject *self, PyObject *tup)
Guido van Rossum234f9421993-06-17 12:35:49 +0000574{
575 struct tm buf;
Guido van Rossumbceeac81996-05-23 22:53:47 +0000576 time_t tt;
577 tt = time(&tt);
578 buf = *localtime(&tt);
Guido van Rossumb2b42dd2000-01-12 16:38:20 +0000579 if (!gettmarg(tup, &buf))
Guido van Rossum234f9421993-06-17 12:35:49 +0000580 return NULL;
Guido van Rossumbceeac81996-05-23 22:53:47 +0000581 tt = mktime(&buf);
582 if (tt == (time_t)(-1)) {
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000583 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum10b164a2001-09-25 13:59:01 +0000584 "mktime argument out of range");
Guido van Rossumbceeac81996-05-23 22:53:47 +0000585 return NULL;
586 }
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000587 return PyFloat_FromDouble((double)tt);
Guido van Rossum234f9421993-06-17 12:35:49 +0000588}
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000589
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000590PyDoc_STRVAR(mktime_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000591"mktime(tuple) -> floating point number\n\
592\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000593Convert a time tuple in local time to seconds since the Epoch.");
Guido van Rossum60cd8131998-03-06 17:16:21 +0000594#endif /* HAVE_MKTIME */
Guido van Rossum234f9421993-06-17 12:35:49 +0000595
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000596#ifdef HAVE_WORKING_TZSET
597void inittimezone(PyObject *module);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000598
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000599static PyObject *
Georg Brandl96a8c392006-05-29 21:04:52 +0000600time_tzset(PyObject *self, PyObject *unused)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000601{
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000602 PyObject* m;
Fred Drake9bb74322002-04-01 14:49:59 +0000603
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000604 m = PyImport_ImportModule("time");
605 if (m == NULL) {
606 return NULL;
607 }
608
609 tzset();
610
611 /* Reset timezone, altzone, daylight and tzname */
612 inittimezone(m);
613 Py_DECREF(m);
Tim Peters1b6f7a92004-06-20 02:50:16 +0000614
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000615 Py_INCREF(Py_None);
616 return Py_None;
617}
618
619PyDoc_STRVAR(tzset_doc,
620"tzset(zone)\n\
621\n\
622Initialize, or reinitialize, the local timezone to the value stored in\n\
623os.environ['TZ']. The TZ environment variable should be specified in\n\
Neal Norwitzdc8e1942004-07-20 22:34:37 +0000624standard Unix timezone format as documented in the tzset man page\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000625(eg. 'US/Eastern', 'Europe/Amsterdam'). Unknown timezones will silently\n\
626fall back to UTC. If the TZ environment variable is not set, the local\n\
627timezone is set to the systems best guess of wallclock time.\n\
628Changing the TZ environment variable without calling tzset *may* change\n\
629the local timezone used by methods such as localtime, but this behaviour\n\
630should not be relied on.");
631#endif /* HAVE_WORKING_TZSET */
632
633void inittimezone(PyObject *m) {
634 /* This code moved from inittime wholesale to allow calling it from
635 time_tzset. In the future, some parts of it can be moved back
636 (for platforms that don't HAVE_WORKING_TZSET, when we know what they
637 are), and the extranious calls to tzset(3) should be removed.
638 I havn't done this yet, as I don't want to change this code as
639 little as possible when introducing the time.tzset and time.tzsetwall
640 methods. This should simply be a method of doing the following once,
641 at the top of this function and removing the call to tzset() from
642 time_tzset():
643
644 #ifdef HAVE_TZSET
645 tzset()
646 #endif
647
648 And I'm lazy and hate C so nyer.
649 */
Guido van Rossum10b164a2001-09-25 13:59:01 +0000650#if defined(HAVE_TZNAME) && !defined(__GLIBC__) && !defined(__CYGWIN__)
Guido van Rossum234f9421993-06-17 12:35:49 +0000651 tzset();
Guido van Rossum26452411998-09-28 22:07:11 +0000652#ifdef PYOS_OS2
Fred Drake9bb74322002-04-01 14:49:59 +0000653 PyModule_AddIntConstant(m, "timezone", _timezone);
Guido van Rossum26452411998-09-28 22:07:11 +0000654#else /* !PYOS_OS2 */
Fred Drake9bb74322002-04-01 14:49:59 +0000655 PyModule_AddIntConstant(m, "timezone", timezone);
Guido van Rossum26452411998-09-28 22:07:11 +0000656#endif /* PYOS_OS2 */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000657#ifdef HAVE_ALTZONE
Fred Drake9bb74322002-04-01 14:49:59 +0000658 PyModule_AddIntConstant(m, "altzone", altzone);
Guido van Rossumb6775db1994-08-01 11:34:53 +0000659#else
Guido van Rossum26452411998-09-28 22:07:11 +0000660#ifdef PYOS_OS2
Fred Drake9bb74322002-04-01 14:49:59 +0000661 PyModule_AddIntConstant(m, "altzone", _timezone-3600);
Guido van Rossum26452411998-09-28 22:07:11 +0000662#else /* !PYOS_OS2 */
Fred Drake9bb74322002-04-01 14:49:59 +0000663 PyModule_AddIntConstant(m, "altzone", timezone-3600);
Guido van Rossum26452411998-09-28 22:07:11 +0000664#endif /* PYOS_OS2 */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000665#endif
Fred Drake9bb74322002-04-01 14:49:59 +0000666 PyModule_AddIntConstant(m, "daylight", daylight);
667 PyModule_AddObject(m, "tzname",
668 Py_BuildValue("(zz)", tzname[0], tzname[1]));
Guido van Rossum10b164a2001-09-25 13:59:01 +0000669#else /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/
Martin v. Löwis60a5d722002-10-16 20:28:25 +0000670#ifdef HAVE_STRUCT_TM_TM_ZONE
Guido van Rossum234f9421993-06-17 12:35:49 +0000671 {
672#define YEAR ((time_t)((365 * 24 + 6) * 3600))
673 time_t t;
674 struct tm *p;
Guido van Rossum57731601999-03-29 19:12:04 +0000675 long janzone, julyzone;
676 char janname[10], julyname[10];
Guido van Rossum234f9421993-06-17 12:35:49 +0000677 t = (time((time_t *)0) / YEAR) * YEAR;
678 p = localtime(&t);
Guido van Rossum57731601999-03-29 19:12:04 +0000679 janzone = -p->tm_gmtoff;
680 strncpy(janname, p->tm_zone ? p->tm_zone : " ", 9);
681 janname[9] = '\0';
Guido van Rossum234f9421993-06-17 12:35:49 +0000682 t += YEAR/2;
683 p = localtime(&t);
Guido van Rossum57731601999-03-29 19:12:04 +0000684 julyzone = -p->tm_gmtoff;
685 strncpy(julyname, p->tm_zone ? p->tm_zone : " ", 9);
686 julyname[9] = '\0';
Guido van Rossum10b164a2001-09-25 13:59:01 +0000687
Guido van Rossum57731601999-03-29 19:12:04 +0000688 if( janzone < julyzone ) {
689 /* DST is reversed in the southern hemisphere */
Fred Drake9bb74322002-04-01 14:49:59 +0000690 PyModule_AddIntConstant(m, "timezone", julyzone);
691 PyModule_AddIntConstant(m, "altzone", janzone);
692 PyModule_AddIntConstant(m, "daylight",
693 janzone != julyzone);
694 PyModule_AddObject(m, "tzname",
695 Py_BuildValue("(zz)",
696 julyname, janname));
Guido van Rossum57731601999-03-29 19:12:04 +0000697 } else {
Fred Drake9bb74322002-04-01 14:49:59 +0000698 PyModule_AddIntConstant(m, "timezone", janzone);
699 PyModule_AddIntConstant(m, "altzone", julyzone);
700 PyModule_AddIntConstant(m, "daylight",
701 janzone != julyzone);
702 PyModule_AddObject(m, "tzname",
703 Py_BuildValue("(zz)",
704 janname, julyname));
Guido van Rossum57731601999-03-29 19:12:04 +0000705 }
Guido van Rossum234f9421993-06-17 12:35:49 +0000706 }
Guido van Rossume6a4b7b1997-10-08 15:27:56 +0000707#else
Martin v. Löwis60a5d722002-10-16 20:28:25 +0000708#endif /* HAVE_STRUCT_TM_TM_ZONE */
Tim Peters26ae7cd2001-03-20 03:26:49 +0000709#ifdef __CYGWIN__
710 tzset();
Fred Drake9bb74322002-04-01 14:49:59 +0000711 PyModule_AddIntConstant(m, "timezone", _timezone);
Georg Brandl378d5922006-05-17 14:26:50 +0000712 PyModule_AddIntConstant(m, "altzone", _timezone-3600);
Fred Drake9bb74322002-04-01 14:49:59 +0000713 PyModule_AddIntConstant(m, "daylight", _daylight);
714 PyModule_AddObject(m, "tzname",
715 Py_BuildValue("(zz)", _tzname[0], _tzname[1]));
Tim Peters26ae7cd2001-03-20 03:26:49 +0000716#endif /* __CYGWIN__ */
Guido van Rossum10b164a2001-09-25 13:59:01 +0000717#endif /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000718}
719
720
721static PyMethodDef time_methods[] = {
Georg Brandl96a8c392006-05-29 21:04:52 +0000722 {"time", time_time, METH_NOARGS, time_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000723#ifdef HAVE_CLOCK
Georg Brandl96a8c392006-05-29 21:04:52 +0000724 {"clock", time_clock, METH_NOARGS, clock_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000725#endif
726 {"sleep", time_sleep, METH_VARARGS, sleep_doc},
727 {"gmtime", time_gmtime, METH_VARARGS, gmtime_doc},
728 {"localtime", time_localtime, METH_VARARGS, localtime_doc},
729 {"asctime", time_asctime, METH_VARARGS, asctime_doc},
730 {"ctime", time_ctime, METH_VARARGS, ctime_doc},
731#ifdef HAVE_MKTIME
Georg Brandl96a8c392006-05-29 21:04:52 +0000732 {"mktime", time_mktime, METH_O, mktime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000733#endif
734#ifdef HAVE_STRFTIME
735 {"strftime", time_strftime, METH_VARARGS, strftime_doc},
736#endif
737 {"strptime", time_strptime, METH_VARARGS, strptime_doc},
738#ifdef HAVE_WORKING_TZSET
Georg Brandl96a8c392006-05-29 21:04:52 +0000739 {"tzset", time_tzset, METH_NOARGS, tzset_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000740#endif
741 {NULL, NULL} /* sentinel */
742};
743
744
745PyDoc_STRVAR(module_doc,
746"This module provides various functions to manipulate time values.\n\
747\n\
748There are two standard representations of time. One is the number\n\
749of seconds since the Epoch, in UTC (a.k.a. GMT). It may be an integer\n\
750or a floating point number (to represent fractions of seconds).\n\
751The Epoch is system-defined; on Unix, it is generally January 1st, 1970.\n\
752The actual value can be retrieved by calling gmtime(0).\n\
753\n\
754The other representation is a tuple of 9 integers giving local time.\n\
755The tuple items are:\n\
756 year (four digits, e.g. 1998)\n\
757 month (1-12)\n\
758 day (1-31)\n\
759 hours (0-23)\n\
760 minutes (0-59)\n\
761 seconds (0-59)\n\
762 weekday (0-6, Monday is 0)\n\
763 Julian day (day in the year, 1-366)\n\
764 DST (Daylight Savings Time) flag (-1, 0 or 1)\n\
765If the DST flag is 0, the time is given in the regular time zone;\n\
766if it is 1, the time is given in the DST time zone;\n\
767if it is -1, mktime() should guess based on the date and time.\n\
768\n\
769Variables:\n\
770\n\
771timezone -- difference in seconds between UTC and local standard time\n\
772altzone -- difference in seconds between UTC and local DST time\n\
773daylight -- whether local time should reflect DST\n\
774tzname -- tuple of (standard time zone name, DST time zone name)\n\
775\n\
776Functions:\n\
777\n\
778time() -- return current time in seconds since the Epoch as a float\n\
779clock() -- return CPU time since process start as a float\n\
780sleep() -- delay for a number of seconds given as a float\n\
781gmtime() -- convert seconds since Epoch to UTC tuple\n\
782localtime() -- convert seconds since Epoch to local time tuple\n\
783asctime() -- convert time tuple to string\n\
784ctime() -- convert time in seconds to string\n\
785mktime() -- convert local time tuple to seconds since Epoch\n\
786strftime() -- convert time tuple to string according to format specification\n\
787strptime() -- parse string to time tuple according to format specification\n\
788tzset() -- change the local timezone");
789
790
791PyMODINIT_FUNC
792inittime(void)
793{
794 PyObject *m;
795 char *p;
796 m = Py_InitModule3("time", time_methods, module_doc);
Neal Norwitz1ac754f2006-01-19 06:09:39 +0000797 if (m == NULL)
798 return;
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000799
800 /* Accept 2-digit dates unless PYTHONY2K is set and non-empty */
801 p = Py_GETENV("PYTHONY2K");
802 PyModule_AddIntConstant(m, "accept2dyear", (long) (!p || !*p));
803 /* Squirrel away the module's dictionary for the y2k check */
804 moddict = PyModule_GetDict(m);
805 Py_INCREF(moddict);
806
807 /* Set, or reset, module variables like time.timezone */
808 inittimezone(m);
809
Mark Hammond975e3922002-07-16 01:29:19 +0000810#ifdef MS_WINDOWS
811 /* Helper to allow interrupts for Windows.
812 If Ctrl+C event delivered while not sleeping
813 it will be ignored.
814 */
815 main_thread = PyThread_get_thread_ident();
816 hInterruptEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
817 SetConsoleCtrlHandler( PyCtrlHandler, TRUE);
818#endif /* MS_WINDOWS */
Martin v. Löwis19ab6c92006-04-16 18:55:50 +0000819 if (!initialized) {
Tim Peters7a822da2006-05-25 21:50:17 +0000820 PyStructSequence_InitType(&StructTimeType,
Martin v. Löwis19ab6c92006-04-16 18:55:50 +0000821 &struct_time_type_desc);
822 }
Fred Drake9bb74322002-04-01 14:49:59 +0000823 Py_INCREF(&StructTimeType);
824 PyModule_AddObject(m, "struct_time", (PyObject*) &StructTimeType);
Martin v. Löwis19ab6c92006-04-16 18:55:50 +0000825 initialized = 1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000826}
827
828
Guido van Rossumb6775db1994-08-01 11:34:53 +0000829/* Implement floattime() for various platforms */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000830
Guido van Rossumb6775db1994-08-01 11:34:53 +0000831static double
Thomas Woutersf3f33dc2000-07-21 06:00:07 +0000832floattime(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000833{
Guido van Rossumb6775db1994-08-01 11:34:53 +0000834 /* There are three ways to get the time:
Barry Warsaw4a6cf411997-01-13 22:44:55 +0000835 (1) gettimeofday() -- resolution in microseconds
836 (2) ftime() -- resolution in milliseconds
837 (3) time() -- resolution in seconds
838 In all cases the return value is a float in seconds.
839 Since on some systems (e.g. SCO ODT 3.0) gettimeofday() may
840 fail, so we fall back on ftime() or time().
841 Note: clock resolution does not imply clock accuracy! */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000842#ifdef HAVE_GETTIMEOFDAY
Barry Warsaw4a6cf411997-01-13 22:44:55 +0000843 {
844 struct timeval t;
Guido van Rossum3bbc62e1995-01-02 19:30:30 +0000845#ifdef GETTIMEOFDAY_NO_TZ
Barry Warsaw4a6cf411997-01-13 22:44:55 +0000846 if (gettimeofday(&t) == 0)
847 return (double)t.tv_sec + t.tv_usec*0.000001;
Guido van Rossum3bbc62e1995-01-02 19:30:30 +0000848#else /* !GETTIMEOFDAY_NO_TZ */
Barry Warsaw4a6cf411997-01-13 22:44:55 +0000849 if (gettimeofday(&t, (struct timezone *)NULL) == 0)
850 return (double)t.tv_sec + t.tv_usec*0.000001;
Guido van Rossum3bbc62e1995-01-02 19:30:30 +0000851#endif /* !GETTIMEOFDAY_NO_TZ */
Barry Warsaw4a6cf411997-01-13 22:44:55 +0000852 }
Ronald Oussorend06b6f22006-04-23 11:59:25 +0000853
Guido van Rossumb6775db1994-08-01 11:34:53 +0000854#endif /* !HAVE_GETTIMEOFDAY */
Barry Warsaw4a6cf411997-01-13 22:44:55 +0000855 {
Guido van Rossumd3eb5771999-03-09 16:07:23 +0000856#if defined(HAVE_FTIME)
Barry Warsaw4a6cf411997-01-13 22:44:55 +0000857 struct timeb t;
858 ftime(&t);
859 return (double)t.time + (double)t.millitm * (double)0.001;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000860#else /* !HAVE_FTIME */
Barry Warsaw4a6cf411997-01-13 22:44:55 +0000861 time_t secs;
862 time(&secs);
863 return (double)secs;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000864#endif /* !HAVE_FTIME */
Barry Warsaw4a6cf411997-01-13 22:44:55 +0000865 }
Guido van Rossum426035c1991-02-19 12:27:35 +0000866}
867
Guido van Rossumb6775db1994-08-01 11:34:53 +0000868
869/* Implement floatsleep() for various platforms.
870 When interrupted (or when another error occurs), return -1 and
871 set an exception; else return 0. */
872
873static int
Guido van Rossuma320fd31995-03-09 12:14:15 +0000874floatsleep(double secs)
Guido van Rossum426035c1991-02-19 12:27:35 +0000875{
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000876/* XXX Should test for MS_WINDOWS first! */
Andrew MacIntyre7bf68332002-03-03 02:59:16 +0000877#if defined(HAVE_SELECT) && !defined(__BEOS__) && !defined(__EMX__)
Guido van Rossum426035c1991-02-19 12:27:35 +0000878 struct timeval t;
Guido van Rossum775f4da1993-01-09 17:18:52 +0000879 double frac;
Guido van Rossum775f4da1993-01-09 17:18:52 +0000880 frac = fmod(secs, 1.0);
881 secs = floor(secs);
882 t.tv_sec = (long)secs;
883 t.tv_usec = (long)(frac*1000000.0);
Guido van Rossum8607ae21997-11-03 22:04:46 +0000884 Py_BEGIN_ALLOW_THREADS
Guido van Rossumb6775db1994-08-01 11:34:53 +0000885 if (select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &t) != 0) {
Guido van Rossum09cbb011999-11-08 15:32:27 +0000886#ifdef EINTR
Guido van Rossuma5456d51999-08-19 14:40:27 +0000887 if (errno != EINTR) {
Guido van Rossum09cbb011999-11-08 15:32:27 +0000888#else
889 if (1) {
890#endif
Andrew M. Kuchlingc24ca4b2000-03-24 20:35:20 +0000891 Py_BLOCK_THREADS
Guido van Rossuma5456d51999-08-19 14:40:27 +0000892 PyErr_SetFromErrno(PyExc_IOError);
893 return -1;
894 }
Guido van Rossumb6775db1994-08-01 11:34:53 +0000895 }
Guido van Rossum8607ae21997-11-03 22:04:46 +0000896 Py_END_ALLOW_THREADS
Martin v. Löwis02af9642002-01-16 11:04:06 +0000897#elif defined(__WATCOMC__) && !defined(__QNX__)
Guido van Rossumbceeac81996-05-23 22:53:47 +0000898 /* XXX Can't interrupt this sleep */
Guido van Rossum8607ae21997-11-03 22:04:46 +0000899 Py_BEGIN_ALLOW_THREADS
Guido van Rossumbceeac81996-05-23 22:53:47 +0000900 delay((int)(secs * 1000 + 0.5)); /* delay() uses milliseconds */
Guido van Rossum8607ae21997-11-03 22:04:46 +0000901 Py_END_ALLOW_THREADS
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000902#elif defined(MS_WINDOWS)
Fred Drake0e123952000-06-29 21:31:02 +0000903 {
904 double millisecs = secs * 1000.0;
Tim Peters513a1cd2003-01-19 04:54:58 +0000905 unsigned long ul_millis;
906
Fred Drake0e123952000-06-29 21:31:02 +0000907 if (millisecs > (double)ULONG_MAX) {
Tim Peters513a1cd2003-01-19 04:54:58 +0000908 PyErr_SetString(PyExc_OverflowError,
909 "sleep length is too large");
Fred Drake0e123952000-06-29 21:31:02 +0000910 return -1;
911 }
Fred Drake0e123952000-06-29 21:31:02 +0000912 Py_BEGIN_ALLOW_THREADS
Tim Peters513a1cd2003-01-19 04:54:58 +0000913 /* Allow sleep(0) to maintain win32 semantics, and as decreed
914 * by Guido, only the main thread can be interrupted.
915 */
916 ul_millis = (unsigned long)millisecs;
917 if (ul_millis == 0 ||
918 main_thread != PyThread_get_thread_ident())
919 Sleep(ul_millis);
Mark Hammond975e3922002-07-16 01:29:19 +0000920 else {
921 DWORD rc;
922 ResetEvent(hInterruptEvent);
Tim Peters513a1cd2003-01-19 04:54:58 +0000923 rc = WaitForSingleObject(hInterruptEvent, ul_millis);
924 if (rc == WAIT_OBJECT_0) {
925 /* Yield to make sure real Python signal
926 * handler called.
927 */
Mark Hammond975e3922002-07-16 01:29:19 +0000928 Sleep(1);
929 Py_BLOCK_THREADS
Mark Hammond975e3922002-07-16 01:29:19 +0000930 errno = EINTR;
931 PyErr_SetFromErrno(PyExc_IOError);
932 return -1;
933 }
934 }
Fred Drake0e123952000-06-29 21:31:02 +0000935 Py_END_ALLOW_THREADS
936 }
Martin v. Löwis02af9642002-01-16 11:04:06 +0000937#elif defined(PYOS_OS2)
Guido van Rossum8e9ebfd1997-11-22 21:53:48 +0000938 /* This Sleep *IS* Interruptable by Exceptions */
Guido van Rossum1d0d7e41997-12-29 20:03:10 +0000939 Py_BEGIN_ALLOW_THREADS
Guido van Rossum8e9ebfd1997-11-22 21:53:48 +0000940 if (DosSleep(secs * 1000) != NO_ERROR) {
Guido van Rossum1d0d7e41997-12-29 20:03:10 +0000941 Py_BLOCK_THREADS
Guido van Rossum8e9ebfd1997-11-22 21:53:48 +0000942 PyErr_SetFromErrno(PyExc_IOError);
943 return -1;
944 }
Guido van Rossum1d0d7e41997-12-29 20:03:10 +0000945 Py_END_ALLOW_THREADS
Martin v. Löwis02af9642002-01-16 11:04:06 +0000946#elif defined(__BEOS__)
Guido van Rossumbcc20741998-08-04 22:53:56 +0000947 /* This sleep *CAN BE* interrupted. */
948 {
Guido van Rossumbcc20741998-08-04 22:53:56 +0000949 if( secs <= 0.0 ) {
950 return;
951 }
Guido van Rossum10b164a2001-09-25 13:59:01 +0000952
Guido van Rossumbcc20741998-08-04 22:53:56 +0000953 Py_BEGIN_ALLOW_THREADS
Guido van Rossumd3eb5771999-03-09 16:07:23 +0000954 /* BeOS snooze() is in microseconds... */
955 if( snooze( (bigtime_t)( secs * 1000.0 * 1000.0 ) ) == B_INTERRUPTED ) {
Guido van Rossumbcc20741998-08-04 22:53:56 +0000956 Py_BLOCK_THREADS
957 PyErr_SetFromErrno( PyExc_IOError );
958 return -1;
959 }
960 Py_END_ALLOW_THREADS
961 }
Martin v. Löwis02af9642002-01-16 11:04:06 +0000962#elif defined(RISCOS)
Guido van Rossumbceccf52001-04-10 22:07:43 +0000963 if (secs <= 0.0)
964 return 0;
965 Py_BEGIN_ALLOW_THREADS
966 /* This sleep *CAN BE* interrupted. */
Martin v. Löwisa94568a2003-05-10 07:36:56 +0000967 if ( riscos_sleep(secs) )
Guido van Rossumbceccf52001-04-10 22:07:43 +0000968 return -1;
969 Py_END_ALLOW_THREADS
Martin v. Löwis02af9642002-01-16 11:04:06 +0000970#elif defined(PLAN9)
971 {
972 double millisecs = secs * 1000.0;
973 if (millisecs > (double)LONG_MAX) {
974 PyErr_SetString(PyExc_OverflowError, "sleep length is too large");
975 return -1;
976 }
977 /* This sleep *CAN BE* interrupted. */
978 Py_BEGIN_ALLOW_THREADS
979 if(sleep((long)millisecs) < 0){
980 Py_BLOCK_THREADS
981 PyErr_SetFromErrno(PyExc_IOError);
982 return -1;
983 }
984 Py_END_ALLOW_THREADS
985 }
986#else
Guido van Rossumb6775db1994-08-01 11:34:53 +0000987 /* XXX Can't interrupt this sleep */
Guido van Rossum8607ae21997-11-03 22:04:46 +0000988 Py_BEGIN_ALLOW_THREADS
Guido van Rossumb6775db1994-08-01 11:34:53 +0000989 sleep((int)secs);
Guido van Rossum8607ae21997-11-03 22:04:46 +0000990 Py_END_ALLOW_THREADS
Martin v. Löwis02af9642002-01-16 11:04:06 +0000991#endif
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000992
Guido van Rossumb6775db1994-08-01 11:34:53 +0000993 return 0;
Guido van Rossum80c9d881991-04-16 08:47:51 +0000994}
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000995
996