blob: 27272977922cc1225d968c2886a9e8aa658bc565 [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
Martin v. Löwis8a7c8662007-08-30 15:40:24 +00008#define TZNAME_ENCODING "utf-8"
9
Thomas Wouters477c8d52006-05-27 19:21:47 +000010#ifdef __APPLE__
11#if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_FTIME)
12 /*
13 * floattime falls back to ftime when getttimeofday fails because the latter
14 * might fail on some platforms. This fallback is unwanted on MacOSX because
15 * that makes it impossible to use a binary build on OSX 10.4 on earlier
16 * releases of the OS. Therefore claim we don't support ftime.
17 */
18# undef HAVE_FTIME
19#endif
20#endif
21
Guido van Rossum87ce7bb1998-06-09 16:30:31 +000022#include <ctype.h>
23
Thomas Wouters0e3f5912006-08-11 14:57:12 +000024#ifdef HAVE_SYS_TYPES_H
Guido van Rossumb6775db1994-08-01 11:34:53 +000025#include <sys/types.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +000026#endif /* HAVE_SYS_TYPES_H */
Guido van Rossum6d946f91992-08-14 13:49:30 +000027
Guido van Rossumb6775db1994-08-01 11:34:53 +000028#ifdef QUICKWIN
29#include <io.h>
30#endif
31
Guido van Rossumb6775db1994-08-01 11:34:53 +000032#ifdef HAVE_FTIME
33#include <sys/timeb.h>
Guido van Rossum8e9ebfd1997-11-22 21:53:48 +000034#if !defined(MS_WINDOWS) && !defined(PYOS_OS2)
Thomas Woutersbd4bc4e2000-07-22 23:57:55 +000035extern int ftime(struct timeb *);
Guido van Rossum52174571996-12-09 18:38:52 +000036#endif /* MS_WINDOWS */
37#endif /* HAVE_FTIME */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000038
Guido van Rossum7bf22de1997-12-02 20:34:19 +000039#if defined(__WATCOMC__) && !defined(__QNX__)
Guido van Rossumbceeac81996-05-23 22:53:47 +000040#include <i86.h>
41#else
Guido van Rossumcac6c721996-09-06 13:34:02 +000042#ifdef MS_WINDOWS
Mark Hammond975e3922002-07-16 01:29:19 +000043#define WIN32_LEAN_AND_MEAN
Guido van Rossum258ccd42001-03-02 06:53:29 +000044#include <windows.h>
Mark Hammond975e3922002-07-16 01:29:19 +000045#include "pythread.h"
46
47/* helper to allow us to interrupt sleep() on Windows*/
48static HANDLE hInterruptEvent = NULL;
49static BOOL WINAPI PyCtrlHandler(DWORD dwCtrlType)
50{
51 SetEvent(hInterruptEvent);
52 /* allow other default handlers to be called.
53 Default Python handler will setup the
54 KeyboardInterrupt exception.
55 */
56 return FALSE;
57}
58static long main_thread;
59
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000060#if defined(__BORLANDC__)
Guido van Rossumb2fb3641996-09-07 00:47:35 +000061/* These overrides not needed for Win32 */
Guido van Rossumb6775db1994-08-01 11:34:53 +000062#define timezone _timezone
Guido van Rossumcc081121995-03-14 15:05:41 +000063#define tzname _tzname
64#define daylight _daylight
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000065#endif /* __BORLANDC__ */
Guido van Rossumcac6c721996-09-06 13:34:02 +000066#endif /* MS_WINDOWS */
Guido van Rossum7bf22de1997-12-02 20:34:19 +000067#endif /* !__WATCOMC__ || __QNX__ */
Guido van Rossum234f9421993-06-17 12:35:49 +000068
Thomas Wouters477c8d52006-05-27 19:21:47 +000069#if defined(MS_WINDOWS) && !defined(__BORLANDC__)
70/* Win32 has better clock replacement; we have our own version below. */
71#undef HAVE_CLOCK
Martin v. Löwis3bb00702007-08-30 14:37:48 +000072#undef TZNAME_ENCODING
73#define TZNAME_ENCODING "mbcs"
Thomas Wouters477c8d52006-05-27 19:21:47 +000074#endif /* MS_WINDOWS && !defined(__BORLANDC__) */
Guido van Rossum3917c221997-04-02 05:35:28 +000075
Andrew MacIntyre7bf68332002-03-03 02:59:16 +000076#if defined(PYOS_OS2)
77#define INCL_DOS
78#define INCL_ERRORS
79#include <os2.h>
80#endif
81
Guido van Rossum8e9ebfd1997-11-22 21:53:48 +000082#if defined(PYCC_VACPP)
Guido van Rossum26452411998-09-28 22:07:11 +000083#include <sys/time.h>
Guido van Rossum8e9ebfd1997-11-22 21:53:48 +000084#endif
85
Guido van Rossum234f9421993-06-17 12:35:49 +000086/* Forward declarations */
Tim Petersdbd9ba62000-07-09 03:09:57 +000087static int floatsleep(double);
Thomas Woutersed77bac2000-07-24 15:26:39 +000088static double floattime(void);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000089
Guido van Rossumcfbaecc1998-08-25 14:51:12 +000090/* For Y2K check */
91static PyObject *moddict;
92
Tim Peters1b6f7a92004-06-20 02:50:16 +000093/* Exposed in timefuncs.h. */
94time_t
Brett Cannon298c3802004-06-19 20:48:43 +000095_PyTime_DoubleToTimet(double x)
96{
97 time_t result;
98 double diff;
99
100 result = (time_t)x;
101 /* How much info did we lose? time_t may be an integral or
102 * floating type, and we don't know which. If it's integral,
103 * we don't know whether C truncates, rounds, returns the floor,
104 * etc. If we lost a second or more, the C rounding is
105 * unreasonable, or the input just doesn't fit in a time_t;
106 * call it an error regardless. Note that the original cast to
107 * time_t can cause a C error too, but nothing we can do to
108 * worm around that.
109 */
110 diff = x - (double)result;
111 if (diff <= -1.0 || diff >= 1.0) {
112 PyErr_SetString(PyExc_ValueError,
113 "timestamp out of range for platform time_t");
114 result = (time_t)-1;
115 }
116 return result;
117}
118
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000119static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000120time_time(PyObject *self, PyObject *unused)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000121{
Guido van Rossumb6775db1994-08-01 11:34:53 +0000122 double secs;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000123 secs = floattime();
124 if (secs == 0.0) {
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000125 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossuma2b7f401993-01-04 09:09:59 +0000126 return NULL;
127 }
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000128 return PyFloat_FromDouble(secs);
Guido van Rossumb6775db1994-08-01 11:34:53 +0000129}
130
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000131PyDoc_STRVAR(time_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000132"time() -> floating point number\n\
133\n\
134Return the current time in seconds since the Epoch.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000135Fractions of a second may be present if the system clock provides them.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000136
Guido van Rossumb6775db1994-08-01 11:34:53 +0000137#ifdef HAVE_CLOCK
138
139#ifndef CLOCKS_PER_SEC
Guido van Rossum1b66a4f1996-02-25 04:50:33 +0000140#ifdef CLK_TCK
141#define CLOCKS_PER_SEC CLK_TCK
142#else
Guido van Rossumb6775db1994-08-01 11:34:53 +0000143#define CLOCKS_PER_SEC 1000000
144#endif
Guido van Rossum1b66a4f1996-02-25 04:50:33 +0000145#endif
Guido van Rossumb6775db1994-08-01 11:34:53 +0000146
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000147static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000148time_clock(PyObject *self, PyObject *unused)
Guido van Rossumb6775db1994-08-01 11:34:53 +0000149{
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000150 return PyFloat_FromDouble(((double)clock()) / CLOCKS_PER_SEC);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000151}
Guido van Rossumb6775db1994-08-01 11:34:53 +0000152#endif /* HAVE_CLOCK */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000153
Thomas Wouters477c8d52006-05-27 19:21:47 +0000154#if defined(MS_WINDOWS) && !defined(__BORLANDC__)
Mark Hammond7ba5e812002-02-12 04:02:33 +0000155/* Due to Mark Hammond and Tim Peters */
Guido van Rossum3917c221997-04-02 05:35:28 +0000156static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000157time_clock(PyObject *self, PyObject *unused)
Guido van Rossum3917c221997-04-02 05:35:28 +0000158{
Tim Peters9ad4b682002-02-13 05:14:18 +0000159 static LARGE_INTEGER ctrStart;
Mark Hammond7ba5e812002-02-12 04:02:33 +0000160 static double divisor = 0.0;
Tim Peters9ad4b682002-02-13 05:14:18 +0000161 LARGE_INTEGER now;
Mark Hammond7ba5e812002-02-12 04:02:33 +0000162 double diff;
Guido van Rossum3917c221997-04-02 05:35:28 +0000163
Mark Hammond7ba5e812002-02-12 04:02:33 +0000164 if (divisor == 0.0) {
Tim Peters9ad4b682002-02-13 05:14:18 +0000165 LARGE_INTEGER freq;
166 QueryPerformanceCounter(&ctrStart);
167 if (!QueryPerformanceFrequency(&freq) || freq.QuadPart == 0) {
Mark Hammond7ba5e812002-02-12 04:02:33 +0000168 /* Unlikely to happen - this works on all intel
169 machines at least! Revert to clock() */
Guido van Rossumd8faa362007-04-27 19:54:29 +0000170 return PyFloat_FromDouble(((double)clock()) /
171 CLOCKS_PER_SEC);
Guido van Rossum3917c221997-04-02 05:35:28 +0000172 }
Tim Peters9ad4b682002-02-13 05:14:18 +0000173 divisor = (double)freq.QuadPart;
Guido van Rossum3917c221997-04-02 05:35:28 +0000174 }
Tim Peters9ad4b682002-02-13 05:14:18 +0000175 QueryPerformanceCounter(&now);
176 diff = (double)(now.QuadPart - ctrStart.QuadPart);
Mark Hammond7ba5e812002-02-12 04:02:33 +0000177 return PyFloat_FromDouble(diff / divisor);
Guido van Rossum3917c221997-04-02 05:35:28 +0000178}
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000179
Guido van Rossum3917c221997-04-02 05:35:28 +0000180#define HAVE_CLOCK /* So it gets included in the methods */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000181#endif /* MS_WINDOWS && !defined(__BORLANDC__) */
Guido van Rossum3917c221997-04-02 05:35:28 +0000182
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000183#ifdef HAVE_CLOCK
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000184PyDoc_STRVAR(clock_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000185"clock() -> floating point number\n\
186\n\
187Return the CPU time or real time since the start of the process or since\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000188the first call to clock(). This has as much precision as the system\n\
189records.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000190#endif
191
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000192static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000193time_sleep(PyObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000194{
Guido van Rossum775f4da1993-01-09 17:18:52 +0000195 double secs;
Thomas Woutersfe385252001-01-19 23:16:56 +0000196 if (!PyArg_ParseTuple(args, "d:sleep", &secs))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000197 return NULL;
Guido van Rossum8607ae21997-11-03 22:04:46 +0000198 if (floatsleep(secs) != 0)
199 return NULL;
200 Py_INCREF(Py_None);
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000201 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000202}
203
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000204PyDoc_STRVAR(sleep_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000205"sleep(seconds)\n\
206\n\
207Delay execution for a given number of seconds. The argument may be\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000208a floating point number for subsecond precision.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000209
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000210static PyStructSequence_Field struct_time_type_fields[] = {
211 {"tm_year", NULL},
212 {"tm_mon", NULL},
213 {"tm_mday", NULL},
214 {"tm_hour", NULL},
215 {"tm_min", NULL},
216 {"tm_sec", NULL},
217 {"tm_wday", NULL},
218 {"tm_yday", NULL},
219 {"tm_isdst", NULL},
220 {0}
221};
222
223static PyStructSequence_Desc struct_time_type_desc = {
Guido van Rossum14648392001-12-08 18:02:58 +0000224 "time.struct_time",
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000225 NULL,
226 struct_time_type_fields,
227 9,
228};
Tim Peters9ad4b682002-02-13 05:14:18 +0000229
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000230static int initialized;
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000231static PyTypeObject StructTimeType;
232
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000233static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000234tmtotuple(struct tm *p)
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000235{
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000236 PyObject *v = PyStructSequence_New(&StructTimeType);
237 if (v == NULL)
238 return NULL;
Tim Peters9ad4b682002-02-13 05:14:18 +0000239
Christian Heimes217cfd12007-12-02 14:31:20 +0000240#define SET(i,val) PyStructSequence_SET_ITEM(v, i, PyLong_FromLong((long) val))
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000241
242 SET(0, p->tm_year + 1900);
243 SET(1, p->tm_mon + 1); /* Want January == 1 */
244 SET(2, p->tm_mday);
245 SET(3, p->tm_hour);
246 SET(4, p->tm_min);
247 SET(5, p->tm_sec);
248 SET(6, (p->tm_wday + 6) % 7); /* Want Monday == 0 */
249 SET(7, p->tm_yday + 1); /* Want January, 1 == 1 */
250 SET(8, p->tm_isdst);
251#undef SET
252 if (PyErr_Occurred()) {
253 Py_XDECREF(v);
254 return NULL;
255 }
256
257 return v;
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000258}
259
260static PyObject *
Skip Montanaro41cfce92007-08-24 21:11:00 +0000261structtime_totuple(PyObject *t)
262{
263 PyObject *x = NULL;
264 unsigned int i;
265 PyObject *v = PyTuple_New(9);
266 if (v == NULL)
267 return NULL;
268
269 for (i=0; i<9; i++) {
270 x = PyStructSequence_GET_ITEM(t, i);
271 Py_INCREF(x);
272 PyTuple_SET_ITEM(v, i, x);
273 }
274
275 if (PyErr_Occurred()) {
276 Py_XDECREF(v);
277 return NULL;
278 }
279
280 return v;
281}
282
283static PyObject *
Brett Cannon298c3802004-06-19 20:48:43 +0000284time_convert(double when, struct tm * (*function)(const time_t *))
Guido van Rossum234f9421993-06-17 12:35:49 +0000285{
Guido van Rossum6e8583d1996-10-08 14:19:52 +0000286 struct tm *p;
Brett Cannon298c3802004-06-19 20:48:43 +0000287 time_t whent = _PyTime_DoubleToTimet(when);
288
289 if (whent == (time_t)-1 && PyErr_Occurred())
290 return NULL;
Guido van Rossum6e8583d1996-10-08 14:19:52 +0000291 errno = 0;
Brett Cannon298c3802004-06-19 20:48:43 +0000292 p = function(&whent);
Guido van Rossum6e8583d1996-10-08 14:19:52 +0000293 if (p == NULL) {
294#ifdef EINVAL
Guido van Rossum0b1ff661996-11-02 17:31:22 +0000295 if (errno == 0)
Guido van Rossum6e8583d1996-10-08 14:19:52 +0000296 errno = EINVAL;
297#endif
Tim Peters8b19a932003-01-17 20:08:54 +0000298 return PyErr_SetFromErrno(PyExc_ValueError);
Guido van Rossum6e8583d1996-10-08 14:19:52 +0000299 }
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000300 return tmtotuple(p);
Guido van Rossum234f9421993-06-17 12:35:49 +0000301}
302
Fred Drakef901abd2004-08-03 17:58:55 +0000303/* Parse arg tuple that can contain an optional float-or-None value;
304 format needs to be "|O:name".
305 Returns non-zero on success (parallels PyArg_ParseTuple).
306*/
307static int
308parse_time_double_args(PyObject *args, char *format, double *pwhen)
309{
310 PyObject *ot = NULL;
311
312 if (!PyArg_ParseTuple(args, format, &ot))
313 return 0;
314 if (ot == NULL || ot == Py_None)
315 *pwhen = floattime();
316 else {
317 double when = PyFloat_AsDouble(ot);
318 if (PyErr_Occurred())
319 return 0;
320 *pwhen = when;
321 }
322 return 1;
323}
324
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000325static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000326time_gmtime(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:gmtime", &when))
Guido van Rossum234f9421993-06-17 12:35:49 +0000330 return NULL;
Brett Cannon298c3802004-06-19 20:48:43 +0000331 return time_convert(when, gmtime);
Guido van Rossum234f9421993-06-17 12:35:49 +0000332}
333
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000334PyDoc_STRVAR(gmtime_doc,
Christian Heimes9a371592007-12-28 14:08:13 +0000335"gmtime([seconds]) -> (tm_year, tm_mon, tm_mday, tm_hour, tm_min,\n\
Fred Drake193a3f62002-03-12 21:38:49 +0000336 tm_sec, tm_wday, tm_yday, tm_isdst)\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000337\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000338Convert seconds since the Epoch to a time tuple expressing UTC (a.k.a.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000339GMT). When 'seconds' is not passed in, convert the current time instead.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000340
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000341static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000342time_localtime(PyObject *self, PyObject *args)
Guido van Rossum234f9421993-06-17 12:35:49 +0000343{
344 double when;
Fred Drakef901abd2004-08-03 17:58:55 +0000345 if (!parse_time_double_args(args, "|O:localtime", &when))
Guido van Rossum234f9421993-06-17 12:35:49 +0000346 return NULL;
Brett Cannon298c3802004-06-19 20:48:43 +0000347 return time_convert(when, localtime);
Guido van Rossum234f9421993-06-17 12:35:49 +0000348}
349
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000350PyDoc_STRVAR(localtime_doc,
Christian Heimes9a371592007-12-28 14:08:13 +0000351"localtime([seconds]) -> (tm_year,tm_mon,tm_mday,tm_hour,tm_min,\n\
352 tm_sec,tm_wday,tm_yday,tm_isdst)\n\
Martin v. Löwisb3cfc1d2001-12-02 12:27:43 +0000353\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000354Convert seconds since the Epoch to a time tuple expressing local time.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000355When 'seconds' is not passed in, convert the current time instead.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000356
Guido van Rossum9e90a671993-06-24 11:10:19 +0000357static int
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000358gettmarg(PyObject *args, struct tm *p)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000359{
Guido van Rossumcfbaecc1998-08-25 14:51:12 +0000360 int y;
Skip Montanaro41cfce92007-08-24 21:11:00 +0000361 PyObject *t = NULL;
Guido van Rossumcfbaecc1998-08-25 14:51:12 +0000362
Guido van Rossumb9081262007-08-25 03:14:09 +0000363 memset((void *) p, '\0', sizeof(struct tm));
364
Skip Montanaro41cfce92007-08-24 21:11:00 +0000365 if (PyTuple_Check(args)) {
366 t = args;
367 Py_INCREF(t);
368 }
Christian Heimes90aa7642007-12-19 02:45:37 +0000369 else if (Py_TYPE(args) == &StructTimeType) {
Skip Montanaro41cfce92007-08-24 21:11:00 +0000370 t = structtime_totuple(args);
371 }
372 else {
373 PyErr_SetString(PyExc_TypeError,
374 "Tuple or struct_time argument required");
Guido van Rossum9e90a671993-06-24 11:10:19 +0000375 return 0;
Skip Montanaro41cfce92007-08-24 21:11:00 +0000376 }
377
378 if (t == NULL || !PyArg_ParseTuple(t, "iiiiiiiii",
379 &y,
380 &p->tm_mon,
381 &p->tm_mday,
382 &p->tm_hour,
383 &p->tm_min,
384 &p->tm_sec,
385 &p->tm_wday,
386 &p->tm_yday,
387 &p->tm_isdst)) {
388 Py_XDECREF(t);
389 return 0;
390 }
391 Py_DECREF(t);
392
Guido van Rossumcfbaecc1998-08-25 14:51:12 +0000393 if (y < 1900) {
394 PyObject *accept = PyDict_GetItemString(moddict,
395 "accept2dyear");
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000396 if (accept == NULL || !PyLong_CheckExact(accept) ||
397 !PyObject_IsTrue(accept)) {
Guido van Rossumcfbaecc1998-08-25 14:51:12 +0000398 PyErr_SetString(PyExc_ValueError,
399 "year >= 1900 required");
400 return 0;
401 }
402 if (69 <= y && y <= 99)
403 y += 1900;
404 else if (0 <= y && y <= 68)
405 y += 2000;
406 else {
407 PyErr_SetString(PyExc_ValueError,
Skip Montanaro1a10aac2001-08-22 12:39:16 +0000408 "year out of range");
Guido van Rossumcfbaecc1998-08-25 14:51:12 +0000409 return 0;
410 }
411 }
412 p->tm_year = y - 1900;
Guido van Rossum9e90a671993-06-24 11:10:19 +0000413 p->tm_mon--;
414 p->tm_wday = (p->tm_wday + 1) % 7;
415 p->tm_yday--;
416 return 1;
417}
418
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000419#ifdef HAVE_STRFTIME
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000420static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000421time_strftime(PyObject *self, PyObject *args)
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000422{
Thomas Woutersfe385252001-01-19 23:16:56 +0000423 PyObject *tup = NULL;
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000424 struct tm buf;
425 const char *fmt;
Guido van Rossumeda12ec2007-08-24 03:51:52 +0000426 PyObject *format;
Guido van Rossumfa481162000-06-28 21:33:59 +0000427 size_t fmtlen, buflen;
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000428 char *outbuf = 0;
Guido van Rossumfa481162000-06-28 21:33:59 +0000429 size_t i;
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000430
Thomas Wouters334fb892000-07-25 12:56:38 +0000431 memset((void *) &buf, '\0', sizeof(buf));
Guido van Rossum1f41f841998-04-27 19:04:26 +0000432
Guido van Rossumeda12ec2007-08-24 03:51:52 +0000433 /* Will always expect a unicode string to be passed as format.
434 Given that there's no str type anymore in py3k this seems safe.
435 */
436 if (!PyArg_ParseTuple(args, "U|O:strftime", &format, &tup))
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000437 return NULL;
Thomas Woutersfe385252001-01-19 23:16:56 +0000438
439 if (tup == NULL) {
440 time_t tt = time(NULL);
441 buf = *localtime(&tt);
442 } else if (!gettmarg(tup, &buf))
443 return NULL;
Guido van Rossum10b164a2001-09-25 13:59:01 +0000444
Brett Cannond1080a32004-03-02 04:38:10 +0000445 /* Checks added to make sure strftime() does not crash Python by
446 indexing blindly into some array for a textual representation
447 by some bad index (fixes bug #897625).
Tim Peters1b6f7a92004-06-20 02:50:16 +0000448
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000449 Also support values of zero from Python code for arguments in which
450 that is out of range by forcing that value to the lowest value that
451 is valid (fixed bug #1520914).
452
453 Valid ranges based on what is allowed in struct tm:
454
455 - tm_year: [0, max(int)] (1)
456 - tm_mon: [0, 11] (2)
457 - tm_mday: [1, 31]
458 - tm_hour: [0, 23]
459 - tm_min: [0, 59]
460 - tm_sec: [0, 60]
461 - tm_wday: [0, 6] (1)
462 - tm_yday: [0, 365] (2)
463 - tm_isdst: [-max(int), max(int)]
464
465 (1) gettmarg() handles bounds-checking.
466 (2) Python's acceptable range is one greater than the range in C,
467 thus need to check against automatic decrement by gettmarg().
Brett Cannond1080a32004-03-02 04:38:10 +0000468 */
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000469 if (buf.tm_mon == -1)
470 buf.tm_mon = 0;
471 else if (buf.tm_mon < 0 || buf.tm_mon > 11) {
Brett Cannond1080a32004-03-02 04:38:10 +0000472 PyErr_SetString(PyExc_ValueError, "month out of range");
473 return NULL;
474 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000475 if (buf.tm_mday == 0)
476 buf.tm_mday = 1;
477 else if (buf.tm_mday < 0 || buf.tm_mday > 31) {
Brett Cannond1080a32004-03-02 04:38:10 +0000478 PyErr_SetString(PyExc_ValueError, "day of month out of range");
479 return NULL;
480 }
481 if (buf.tm_hour < 0 || buf.tm_hour > 23) {
482 PyErr_SetString(PyExc_ValueError, "hour out of range");
483 return NULL;
484 }
485 if (buf.tm_min < 0 || buf.tm_min > 59) {
486 PyErr_SetString(PyExc_ValueError, "minute out of range");
487 return NULL;
488 }
489 if (buf.tm_sec < 0 || buf.tm_sec > 61) {
490 PyErr_SetString(PyExc_ValueError, "seconds out of range");
491 return NULL;
492 }
493 /* tm_wday does not need checking of its upper-bound since taking
494 ``% 7`` in gettmarg() automatically restricts the range. */
495 if (buf.tm_wday < 0) {
496 PyErr_SetString(PyExc_ValueError, "day of week out of range");
497 return NULL;
498 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000499 if (buf.tm_yday == -1)
500 buf.tm_yday = 0;
501 else if (buf.tm_yday < 0 || buf.tm_yday > 365) {
Brett Cannond1080a32004-03-02 04:38:10 +0000502 PyErr_SetString(PyExc_ValueError, "day of year out of range");
503 return NULL;
504 }
505 if (buf.tm_isdst < -1 || buf.tm_isdst > 1) {
506 PyErr_SetString(PyExc_ValueError,
507 "daylight savings flag out of range");
508 return NULL;
509 }
510
Hirokazu Yamamoto575d1332009-02-16 09:13:20 +0000511 /* Convert the unicode string to an ascii one */
512 format = PyUnicode_AsEncodedString(format, TZNAME_ENCODING, NULL);
513 if (format == NULL)
514 return NULL;
515 fmt = PyBytes_AS_STRING(format);
Amaury Forgeot d'Arcb5be6d42009-03-02 23:52:57 +0000516
517#ifdef MS_WINDOWS
518 /* check that the format string contains only valid directives */
519 for(outbuf = strchr(fmt, '%');
520 outbuf != NULL;
521 outbuf = strchr(outbuf+2, '%'))
522 {
523 if (outbuf[1]=='#')
524 ++outbuf; /* not documented by python, */
525 if (outbuf[1]=='\0' ||
526 !strchr("aAbBcdfHIjmMpSUwWxXyYzZ%", outbuf[1]))
527 {
528 PyErr_SetString(PyExc_ValueError, "Invalid format string");
529 return 0;
530 }
531 }
532#endif
533
Guido van Rossumc222ec21999-02-23 00:00:10 +0000534 fmtlen = strlen(fmt);
535
Barry Warsaw4a6cf411997-01-13 22:44:55 +0000536 /* I hate these functions that presume you know how big the output
537 * will be ahead of time...
538 */
Guido van Rossumc222ec21999-02-23 00:00:10 +0000539 for (i = 1024; ; i += i) {
Walter Dörwaldcf47af42007-05-31 19:23:17 +0000540 outbuf = (char *)PyMem_Malloc(i);
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000541 if (outbuf == NULL) {
Hirokazu Yamamoto575d1332009-02-16 09:13:20 +0000542 Py_DECREF(format);
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000543 return PyErr_NoMemory();
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000544 }
Guido van Rossumc222ec21999-02-23 00:00:10 +0000545 buflen = strftime(outbuf, i, fmt, &buf);
546 if (buflen > 0 || i >= 256 * fmtlen) {
547 /* If the buffer is 256 times as long as the format,
548 it's probably not failing for lack of room!
549 More likely, the format yields an empty result,
550 e.g. an empty format, or %Z when the timezone
551 is unknown. */
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000552 PyObject *ret;
Guido van Rossumb98cda42007-10-23 19:43:28 +0000553 ret = PyUnicode_Decode(outbuf, buflen,
554 TZNAME_ENCODING, NULL);
Walter Dörwaldcf47af42007-05-31 19:23:17 +0000555 PyMem_Free(outbuf);
Hirokazu Yamamoto575d1332009-02-16 09:13:20 +0000556 Py_DECREF(format);
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000557 return ret;
558 }
Walter Dörwaldcf47af42007-05-31 19:23:17 +0000559 PyMem_Free(outbuf);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000560#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
561 /* VisualStudio .NET 2005 does this properly */
562 if (buflen == 0 && errno == EINVAL) {
563 PyErr_SetString(PyExc_ValueError, "Invalid format string");
Hirokazu Yamamoto575d1332009-02-16 09:13:20 +0000564 Py_DECREF(format);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000565 return 0;
566 }
567#endif
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000568 }
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000569}
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000570
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000571PyDoc_STRVAR(strftime_doc,
Thomas Woutersfe385252001-01-19 23:16:56 +0000572"strftime(format[, tuple]) -> string\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000573\n\
574Convert a time tuple to a string according to a format specification.\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000575See the library reference manual for formatting codes. When the time tuple\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000576is not present, current time as returned by localtime() is used.");
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000577#endif /* HAVE_STRFTIME */
578
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000579static PyObject *
580time_strptime(PyObject *self, PyObject *args)
581{
Christian Heimes072c0f12008-01-03 23:01:04 +0000582 PyObject *strptime_module = PyImport_ImportModuleNoBlock("_strptime");
Raymond Hettinger502168a2003-04-10 16:03:22 +0000583 PyObject *strptime_result;
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000584
Tim Peters513a1cd2003-01-19 04:54:58 +0000585 if (!strptime_module)
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000586 return NULL;
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000587 strptime_result = PyObject_CallMethod(strptime_module, "_strptime_time", "O", args);
Raymond Hettinger502168a2003-04-10 16:03:22 +0000588 Py_DECREF(strptime_module);
589 return strptime_result;
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000590}
591
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000592PyDoc_STRVAR(strptime_doc,
Brett Cannon20def8b2003-07-01 05:16:08 +0000593"strptime(string, format) -> struct_time\n\
Martin v. Löwisb3cfc1d2001-12-02 12:27:43 +0000594\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000595Parse a string to a time tuple according to a format specification.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000596See the library reference manual for formatting codes (same as strftime()).");
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000597
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000598
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000599static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000600time_asctime(PyObject *self, PyObject *args)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000601{
Thomas Woutersfe385252001-01-19 23:16:56 +0000602 PyObject *tup = NULL;
Guido van Rossum9e90a671993-06-24 11:10:19 +0000603 struct tm buf;
604 char *p;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000605 if (!PyArg_UnpackTuple(args, "asctime", 0, 1, &tup))
Guido van Rossumb2b42dd2000-01-12 16:38:20 +0000606 return NULL;
Thomas Woutersfe385252001-01-19 23:16:56 +0000607 if (tup == NULL) {
608 time_t tt = time(NULL);
609 buf = *localtime(&tt);
610 } else if (!gettmarg(tup, &buf))
Guido van Rossum9e90a671993-06-24 11:10:19 +0000611 return NULL;
612 p = asctime(&buf);
613 if (p[24] == '\n')
614 p[24] = '\0';
Guido van Rossumeda12ec2007-08-24 03:51:52 +0000615 return PyUnicode_FromString(p);
Guido van Rossum9e90a671993-06-24 11:10:19 +0000616}
617
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000618PyDoc_STRVAR(asctime_doc,
Thomas Woutersfe385252001-01-19 23:16:56 +0000619"asctime([tuple]) -> string\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000620\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000621Convert a time tuple to a string, e.g. 'Sat Jun 06 16:26:11 1998'.\n\
622When the time tuple is not present, current time as returned by localtime()\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000623is used.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000624
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000625static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000626time_ctime(PyObject *self, PyObject *args)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000627{
Fred Drakef901abd2004-08-03 17:58:55 +0000628 PyObject *ot = NULL;
Guido van Rossum9e90a671993-06-24 11:10:19 +0000629 time_t tt;
630 char *p;
Guido van Rossum10b164a2001-09-25 13:59:01 +0000631
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000632 if (!PyArg_UnpackTuple(args, "ctime", 0, 1, &ot))
Fred Drakef901abd2004-08-03 17:58:55 +0000633 return NULL;
634 if (ot == NULL || ot == Py_None)
Thomas Woutersfe385252001-01-19 23:16:56 +0000635 tt = time(NULL);
636 else {
Fred Drakef901abd2004-08-03 17:58:55 +0000637 double dt = PyFloat_AsDouble(ot);
638 if (PyErr_Occurred())
Thomas Woutersfe385252001-01-19 23:16:56 +0000639 return NULL;
Brett Cannon298c3802004-06-19 20:48:43 +0000640 tt = _PyTime_DoubleToTimet(dt);
641 if (tt == (time_t)-1 && PyErr_Occurred())
642 return NULL;
Thomas Woutersfe385252001-01-19 23:16:56 +0000643 }
Guido van Rossum9e90a671993-06-24 11:10:19 +0000644 p = ctime(&tt);
Guido van Rossum78535701998-03-03 22:19:10 +0000645 if (p == NULL) {
646 PyErr_SetString(PyExc_ValueError, "unconvertible time");
647 return NULL;
648 }
Guido van Rossum9e90a671993-06-24 11:10:19 +0000649 if (p[24] == '\n')
650 p[24] = '\0';
Guido van Rossumeda12ec2007-08-24 03:51:52 +0000651 return PyUnicode_FromString(p);
Guido van Rossum9e90a671993-06-24 11:10:19 +0000652}
653
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000654PyDoc_STRVAR(ctime_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000655"ctime(seconds) -> string\n\
656\n\
657Convert a time in seconds since the Epoch to a string in local time.\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000658This is equivalent to asctime(localtime(seconds)). When the time tuple is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000659not present, current time as returned by localtime() is used.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000660
Guido van Rossum60cd8131998-03-06 17:16:21 +0000661#ifdef HAVE_MKTIME
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000662static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000663time_mktime(PyObject *self, PyObject *tup)
Guido van Rossum234f9421993-06-17 12:35:49 +0000664{
665 struct tm buf;
Guido van Rossumbceeac81996-05-23 22:53:47 +0000666 time_t tt;
Guido van Rossumb2b42dd2000-01-12 16:38:20 +0000667 if (!gettmarg(tup, &buf))
Guido van Rossum234f9421993-06-17 12:35:49 +0000668 return NULL;
Guido van Rossumbceeac81996-05-23 22:53:47 +0000669 tt = mktime(&buf);
670 if (tt == (time_t)(-1)) {
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000671 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum10b164a2001-09-25 13:59:01 +0000672 "mktime argument out of range");
Guido van Rossumbceeac81996-05-23 22:53:47 +0000673 return NULL;
674 }
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000675 return PyFloat_FromDouble((double)tt);
Guido van Rossum234f9421993-06-17 12:35:49 +0000676}
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000677
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000678PyDoc_STRVAR(mktime_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000679"mktime(tuple) -> floating point number\n\
680\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000681Convert a time tuple in local time to seconds since the Epoch.");
Guido van Rossum60cd8131998-03-06 17:16:21 +0000682#endif /* HAVE_MKTIME */
Guido van Rossum234f9421993-06-17 12:35:49 +0000683
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000684#ifdef HAVE_WORKING_TZSET
Martin v. Löwis1a214512008-06-11 05:26:20 +0000685static void PyInit_timezone(PyObject *module);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000686
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000687static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000688time_tzset(PyObject *self, PyObject *unused)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000689{
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000690 PyObject* m;
Fred Drake9bb74322002-04-01 14:49:59 +0000691
Christian Heimes072c0f12008-01-03 23:01:04 +0000692 m = PyImport_ImportModuleNoBlock("time");
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000693 if (m == NULL) {
694 return NULL;
695 }
696
697 tzset();
698
699 /* Reset timezone, altzone, daylight and tzname */
Martin v. Löwis1a214512008-06-11 05:26:20 +0000700 PyInit_timezone(m);
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000701 Py_DECREF(m);
Tim Peters1b6f7a92004-06-20 02:50:16 +0000702
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000703 Py_INCREF(Py_None);
704 return Py_None;
705}
706
707PyDoc_STRVAR(tzset_doc,
708"tzset(zone)\n\
709\n\
710Initialize, or reinitialize, the local timezone to the value stored in\n\
711os.environ['TZ']. The TZ environment variable should be specified in\n\
Neal Norwitzdc8e1942004-07-20 22:34:37 +0000712standard Unix timezone format as documented in the tzset man page\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000713(eg. 'US/Eastern', 'Europe/Amsterdam'). Unknown timezones will silently\n\
714fall back to UTC. If the TZ environment variable is not set, the local\n\
715timezone is set to the systems best guess of wallclock time.\n\
716Changing the TZ environment variable without calling tzset *may* change\n\
717the local timezone used by methods such as localtime, but this behaviour\n\
718should not be relied on.");
719#endif /* HAVE_WORKING_TZSET */
720
Martin v. Löwisd218dc12008-04-07 03:17:54 +0000721static void
Martin v. Löwis1a214512008-06-11 05:26:20 +0000722PyInit_timezone(PyObject *m) {
723 /* This code moved from PyInit_time wholesale to allow calling it from
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000724 time_tzset. In the future, some parts of it can be moved back
725 (for platforms that don't HAVE_WORKING_TZSET, when we know what they
Martin v. Löwisd218dc12008-04-07 03:17:54 +0000726 are), and the extraneous calls to tzset(3) should be removed.
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000727 I haven't done this yet, as I don't want to change this code as
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000728 little as possible when introducing the time.tzset and time.tzsetwall
729 methods. This should simply be a method of doing the following once,
730 at the top of this function and removing the call to tzset() from
731 time_tzset():
732
733 #ifdef HAVE_TZSET
734 tzset()
735 #endif
736
737 And I'm lazy and hate C so nyer.
738 */
Guido van Rossum10b164a2001-09-25 13:59:01 +0000739#if defined(HAVE_TZNAME) && !defined(__GLIBC__) && !defined(__CYGWIN__)
Martin v. Löwis3bb00702007-08-30 14:37:48 +0000740 PyObject *otz0, *otz1;
Guido van Rossum234f9421993-06-17 12:35:49 +0000741 tzset();
Guido van Rossum26452411998-09-28 22:07:11 +0000742#ifdef PYOS_OS2
Fred Drake9bb74322002-04-01 14:49:59 +0000743 PyModule_AddIntConstant(m, "timezone", _timezone);
Guido van Rossum26452411998-09-28 22:07:11 +0000744#else /* !PYOS_OS2 */
Fred Drake9bb74322002-04-01 14:49:59 +0000745 PyModule_AddIntConstant(m, "timezone", timezone);
Guido van Rossum26452411998-09-28 22:07:11 +0000746#endif /* PYOS_OS2 */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000747#ifdef HAVE_ALTZONE
Fred Drake9bb74322002-04-01 14:49:59 +0000748 PyModule_AddIntConstant(m, "altzone", altzone);
Guido van Rossumb6775db1994-08-01 11:34:53 +0000749#else
Guido van Rossum26452411998-09-28 22:07:11 +0000750#ifdef PYOS_OS2
Fred Drake9bb74322002-04-01 14:49:59 +0000751 PyModule_AddIntConstant(m, "altzone", _timezone-3600);
Guido van Rossum26452411998-09-28 22:07:11 +0000752#else /* !PYOS_OS2 */
Fred Drake9bb74322002-04-01 14:49:59 +0000753 PyModule_AddIntConstant(m, "altzone", timezone-3600);
Guido van Rossum26452411998-09-28 22:07:11 +0000754#endif /* PYOS_OS2 */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000755#endif
Fred Drake9bb74322002-04-01 14:49:59 +0000756 PyModule_AddIntConstant(m, "daylight", daylight);
Martin v. Löwis3bb00702007-08-30 14:37:48 +0000757 otz0 = PyUnicode_Decode(tzname[0], strlen(tzname[0]), TZNAME_ENCODING, NULL);
758 otz1 = PyUnicode_Decode(tzname[1], strlen(tzname[1]), TZNAME_ENCODING, NULL);
759 PyModule_AddObject(m, "tzname", Py_BuildValue("(NN)", otz0, otz1));
Guido van Rossum10b164a2001-09-25 13:59:01 +0000760#else /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/
Martin v. Löwis60a5d722002-10-16 20:28:25 +0000761#ifdef HAVE_STRUCT_TM_TM_ZONE
Guido van Rossum234f9421993-06-17 12:35:49 +0000762 {
763#define YEAR ((time_t)((365 * 24 + 6) * 3600))
764 time_t t;
765 struct tm *p;
Guido van Rossum57731601999-03-29 19:12:04 +0000766 long janzone, julyzone;
767 char janname[10], julyname[10];
Guido van Rossum234f9421993-06-17 12:35:49 +0000768 t = (time((time_t *)0) / YEAR) * YEAR;
769 p = localtime(&t);
Guido van Rossum57731601999-03-29 19:12:04 +0000770 janzone = -p->tm_gmtoff;
771 strncpy(janname, p->tm_zone ? p->tm_zone : " ", 9);
772 janname[9] = '\0';
Guido van Rossum234f9421993-06-17 12:35:49 +0000773 t += YEAR/2;
774 p = localtime(&t);
Guido van Rossum57731601999-03-29 19:12:04 +0000775 julyzone = -p->tm_gmtoff;
776 strncpy(julyname, p->tm_zone ? p->tm_zone : " ", 9);
777 julyname[9] = '\0';
Guido van Rossum10b164a2001-09-25 13:59:01 +0000778
Guido van Rossum57731601999-03-29 19:12:04 +0000779 if( janzone < julyzone ) {
780 /* DST is reversed in the southern hemisphere */
Fred Drake9bb74322002-04-01 14:49:59 +0000781 PyModule_AddIntConstant(m, "timezone", julyzone);
782 PyModule_AddIntConstant(m, "altzone", janzone);
783 PyModule_AddIntConstant(m, "daylight",
784 janzone != julyzone);
785 PyModule_AddObject(m, "tzname",
786 Py_BuildValue("(zz)",
787 julyname, janname));
Guido van Rossum57731601999-03-29 19:12:04 +0000788 } else {
Fred Drake9bb74322002-04-01 14:49:59 +0000789 PyModule_AddIntConstant(m, "timezone", janzone);
790 PyModule_AddIntConstant(m, "altzone", julyzone);
791 PyModule_AddIntConstant(m, "daylight",
792 janzone != julyzone);
793 PyModule_AddObject(m, "tzname",
794 Py_BuildValue("(zz)",
795 janname, julyname));
Guido van Rossum57731601999-03-29 19:12:04 +0000796 }
Guido van Rossum234f9421993-06-17 12:35:49 +0000797 }
Guido van Rossume6a4b7b1997-10-08 15:27:56 +0000798#else
Martin v. Löwis60a5d722002-10-16 20:28:25 +0000799#endif /* HAVE_STRUCT_TM_TM_ZONE */
Tim Peters26ae7cd2001-03-20 03:26:49 +0000800#ifdef __CYGWIN__
801 tzset();
Fred Drake9bb74322002-04-01 14:49:59 +0000802 PyModule_AddIntConstant(m, "timezone", _timezone);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000803 PyModule_AddIntConstant(m, "altzone", _timezone-3600);
Fred Drake9bb74322002-04-01 14:49:59 +0000804 PyModule_AddIntConstant(m, "daylight", _daylight);
805 PyModule_AddObject(m, "tzname",
806 Py_BuildValue("(zz)", _tzname[0], _tzname[1]));
Tim Peters26ae7cd2001-03-20 03:26:49 +0000807#endif /* __CYGWIN__ */
Guido van Rossum10b164a2001-09-25 13:59:01 +0000808#endif /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000809}
810
811
812static PyMethodDef time_methods[] = {
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000813 {"time", time_time, METH_NOARGS, time_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000814#ifdef HAVE_CLOCK
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000815 {"clock", time_clock, METH_NOARGS, clock_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000816#endif
817 {"sleep", time_sleep, METH_VARARGS, sleep_doc},
818 {"gmtime", time_gmtime, METH_VARARGS, gmtime_doc},
819 {"localtime", time_localtime, METH_VARARGS, localtime_doc},
820 {"asctime", time_asctime, METH_VARARGS, asctime_doc},
821 {"ctime", time_ctime, METH_VARARGS, ctime_doc},
822#ifdef HAVE_MKTIME
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000823 {"mktime", time_mktime, METH_O, mktime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000824#endif
825#ifdef HAVE_STRFTIME
826 {"strftime", time_strftime, METH_VARARGS, strftime_doc},
827#endif
828 {"strptime", time_strptime, METH_VARARGS, strptime_doc},
829#ifdef HAVE_WORKING_TZSET
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000830 {"tzset", time_tzset, METH_NOARGS, tzset_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000831#endif
832 {NULL, NULL} /* sentinel */
833};
834
835
836PyDoc_STRVAR(module_doc,
837"This module provides various functions to manipulate time values.\n\
838\n\
839There are two standard representations of time. One is the number\n\
840of seconds since the Epoch, in UTC (a.k.a. GMT). It may be an integer\n\
841or a floating point number (to represent fractions of seconds).\n\
842The Epoch is system-defined; on Unix, it is generally January 1st, 1970.\n\
843The actual value can be retrieved by calling gmtime(0).\n\
844\n\
845The other representation is a tuple of 9 integers giving local time.\n\
846The tuple items are:\n\
847 year (four digits, e.g. 1998)\n\
848 month (1-12)\n\
849 day (1-31)\n\
850 hours (0-23)\n\
851 minutes (0-59)\n\
852 seconds (0-59)\n\
853 weekday (0-6, Monday is 0)\n\
854 Julian day (day in the year, 1-366)\n\
855 DST (Daylight Savings Time) flag (-1, 0 or 1)\n\
856If the DST flag is 0, the time is given in the regular time zone;\n\
857if it is 1, the time is given in the DST time zone;\n\
858if it is -1, mktime() should guess based on the date and time.\n\
859\n\
860Variables:\n\
861\n\
862timezone -- difference in seconds between UTC and local standard time\n\
863altzone -- difference in seconds between UTC and local DST time\n\
864daylight -- whether local time should reflect DST\n\
865tzname -- tuple of (standard time zone name, DST time zone name)\n\
866\n\
867Functions:\n\
868\n\
869time() -- return current time in seconds since the Epoch as a float\n\
870clock() -- return CPU time since process start as a float\n\
871sleep() -- delay for a number of seconds given as a float\n\
872gmtime() -- convert seconds since Epoch to UTC tuple\n\
873localtime() -- convert seconds since Epoch to local time tuple\n\
874asctime() -- convert time tuple to string\n\
875ctime() -- convert time in seconds to string\n\
876mktime() -- convert local time tuple to seconds since Epoch\n\
877strftime() -- convert time tuple to string according to format specification\n\
878strptime() -- parse string to time tuple according to format specification\n\
879tzset() -- change the local timezone");
880
881
Martin v. Löwis1a214512008-06-11 05:26:20 +0000882
883static struct PyModuleDef timemodule = {
884 PyModuleDef_HEAD_INIT,
885 "time",
886 module_doc,
887 -1,
888 time_methods,
889 NULL,
890 NULL,
891 NULL,
892 NULL
893};
894
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000895PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +0000896PyInit_time(void)
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000897{
898 PyObject *m;
899 char *p;
Martin v. Löwis1a214512008-06-11 05:26:20 +0000900 m = PyModule_Create(&timemodule);
Neal Norwitz1ac754f2006-01-19 06:09:39 +0000901 if (m == NULL)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000902 return NULL;
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000903
904 /* Accept 2-digit dates unless PYTHONY2K is set and non-empty */
905 p = Py_GETENV("PYTHONY2K");
906 PyModule_AddIntConstant(m, "accept2dyear", (long) (!p || !*p));
907 /* Squirrel away the module's dictionary for the y2k check */
908 moddict = PyModule_GetDict(m);
909 Py_INCREF(moddict);
910
911 /* Set, or reset, module variables like time.timezone */
Martin v. Löwis1a214512008-06-11 05:26:20 +0000912 PyInit_timezone(m);
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000913
Mark Hammond975e3922002-07-16 01:29:19 +0000914#ifdef MS_WINDOWS
915 /* Helper to allow interrupts for Windows.
916 If Ctrl+C event delivered while not sleeping
917 it will be ignored.
918 */
919 main_thread = PyThread_get_thread_ident();
920 hInterruptEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
921 SetConsoleCtrlHandler( PyCtrlHandler, TRUE);
922#endif /* MS_WINDOWS */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000923 if (!initialized) {
Thomas Wouters477c8d52006-05-27 19:21:47 +0000924 PyStructSequence_InitType(&StructTimeType,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000925 &struct_time_type_desc);
926 }
Fred Drake9bb74322002-04-01 14:49:59 +0000927 Py_INCREF(&StructTimeType);
928 PyModule_AddObject(m, "struct_time", (PyObject*) &StructTimeType);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000929 initialized = 1;
Martin v. Löwis1a214512008-06-11 05:26:20 +0000930 return m;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000931}
932
933
Guido van Rossumb6775db1994-08-01 11:34:53 +0000934/* Implement floattime() for various platforms */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000935
Guido van Rossumb6775db1994-08-01 11:34:53 +0000936static double
Thomas Woutersf3f33dc2000-07-21 06:00:07 +0000937floattime(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000938{
Guido van Rossumb6775db1994-08-01 11:34:53 +0000939 /* There are three ways to get the time:
Barry Warsaw4a6cf411997-01-13 22:44:55 +0000940 (1) gettimeofday() -- resolution in microseconds
941 (2) ftime() -- resolution in milliseconds
942 (3) time() -- resolution in seconds
943 In all cases the return value is a float in seconds.
944 Since on some systems (e.g. SCO ODT 3.0) gettimeofday() may
945 fail, so we fall back on ftime() or time().
946 Note: clock resolution does not imply clock accuracy! */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000947#ifdef HAVE_GETTIMEOFDAY
Barry Warsaw4a6cf411997-01-13 22:44:55 +0000948 {
949 struct timeval t;
Guido van Rossum3bbc62e1995-01-02 19:30:30 +0000950#ifdef GETTIMEOFDAY_NO_TZ
Barry Warsaw4a6cf411997-01-13 22:44:55 +0000951 if (gettimeofday(&t) == 0)
952 return (double)t.tv_sec + t.tv_usec*0.000001;
Guido van Rossum3bbc62e1995-01-02 19:30:30 +0000953#else /* !GETTIMEOFDAY_NO_TZ */
Barry Warsaw4a6cf411997-01-13 22:44:55 +0000954 if (gettimeofday(&t, (struct timezone *)NULL) == 0)
955 return (double)t.tv_sec + t.tv_usec*0.000001;
Guido van Rossum3bbc62e1995-01-02 19:30:30 +0000956#endif /* !GETTIMEOFDAY_NO_TZ */
Barry Warsaw4a6cf411997-01-13 22:44:55 +0000957 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000958
Guido van Rossumb6775db1994-08-01 11:34:53 +0000959#endif /* !HAVE_GETTIMEOFDAY */
Barry Warsaw4a6cf411997-01-13 22:44:55 +0000960 {
Guido van Rossumd3eb5771999-03-09 16:07:23 +0000961#if defined(HAVE_FTIME)
Barry Warsaw4a6cf411997-01-13 22:44:55 +0000962 struct timeb t;
963 ftime(&t);
964 return (double)t.time + (double)t.millitm * (double)0.001;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000965#else /* !HAVE_FTIME */
Barry Warsaw4a6cf411997-01-13 22:44:55 +0000966 time_t secs;
967 time(&secs);
968 return (double)secs;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000969#endif /* !HAVE_FTIME */
Barry Warsaw4a6cf411997-01-13 22:44:55 +0000970 }
Guido van Rossum426035c1991-02-19 12:27:35 +0000971}
972
Guido van Rossumb6775db1994-08-01 11:34:53 +0000973
974/* Implement floatsleep() for various platforms.
975 When interrupted (or when another error occurs), return -1 and
976 set an exception; else return 0. */
977
978static int
Guido van Rossuma320fd31995-03-09 12:14:15 +0000979floatsleep(double secs)
Guido van Rossum426035c1991-02-19 12:27:35 +0000980{
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000981/* XXX Should test for MS_WINDOWS first! */
Skip Montanaroeb33e5a2007-08-17 12:57:41 +0000982#if defined(HAVE_SELECT) && !defined(__EMX__)
Guido van Rossum426035c1991-02-19 12:27:35 +0000983 struct timeval t;
Guido van Rossum775f4da1993-01-09 17:18:52 +0000984 double frac;
Guido van Rossum775f4da1993-01-09 17:18:52 +0000985 frac = fmod(secs, 1.0);
986 secs = floor(secs);
987 t.tv_sec = (long)secs;
988 t.tv_usec = (long)(frac*1000000.0);
Guido van Rossum8607ae21997-11-03 22:04:46 +0000989 Py_BEGIN_ALLOW_THREADS
Guido van Rossumb6775db1994-08-01 11:34:53 +0000990 if (select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &t) != 0) {
Guido van Rossum09cbb011999-11-08 15:32:27 +0000991#ifdef EINTR
Guido van Rossuma5456d51999-08-19 14:40:27 +0000992 if (errno != EINTR) {
Guido van Rossum09cbb011999-11-08 15:32:27 +0000993#else
994 if (1) {
995#endif
Andrew M. Kuchlingc24ca4b2000-03-24 20:35:20 +0000996 Py_BLOCK_THREADS
Guido van Rossuma5456d51999-08-19 14:40:27 +0000997 PyErr_SetFromErrno(PyExc_IOError);
998 return -1;
999 }
Guido van Rossumb6775db1994-08-01 11:34:53 +00001000 }
Guido van Rossum8607ae21997-11-03 22:04:46 +00001001 Py_END_ALLOW_THREADS
Martin v. Löwis02af9642002-01-16 11:04:06 +00001002#elif defined(__WATCOMC__) && !defined(__QNX__)
Guido van Rossumbceeac81996-05-23 22:53:47 +00001003 /* XXX Can't interrupt this sleep */
Guido van Rossum8607ae21997-11-03 22:04:46 +00001004 Py_BEGIN_ALLOW_THREADS
Guido van Rossumbceeac81996-05-23 22:53:47 +00001005 delay((int)(secs * 1000 + 0.5)); /* delay() uses milliseconds */
Guido van Rossum8607ae21997-11-03 22:04:46 +00001006 Py_END_ALLOW_THREADS
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001007#elif defined(MS_WINDOWS)
Fred Drake0e123952000-06-29 21:31:02 +00001008 {
1009 double millisecs = secs * 1000.0;
Tim Peters513a1cd2003-01-19 04:54:58 +00001010 unsigned long ul_millis;
1011
Fred Drake0e123952000-06-29 21:31:02 +00001012 if (millisecs > (double)ULONG_MAX) {
Tim Peters513a1cd2003-01-19 04:54:58 +00001013 PyErr_SetString(PyExc_OverflowError,
1014 "sleep length is too large");
Fred Drake0e123952000-06-29 21:31:02 +00001015 return -1;
1016 }
Fred Drake0e123952000-06-29 21:31:02 +00001017 Py_BEGIN_ALLOW_THREADS
Tim Peters513a1cd2003-01-19 04:54:58 +00001018 /* Allow sleep(0) to maintain win32 semantics, and as decreed
1019 * by Guido, only the main thread can be interrupted.
1020 */
1021 ul_millis = (unsigned long)millisecs;
1022 if (ul_millis == 0 ||
1023 main_thread != PyThread_get_thread_ident())
1024 Sleep(ul_millis);
Mark Hammond975e3922002-07-16 01:29:19 +00001025 else {
1026 DWORD rc;
1027 ResetEvent(hInterruptEvent);
Tim Peters513a1cd2003-01-19 04:54:58 +00001028 rc = WaitForSingleObject(hInterruptEvent, ul_millis);
1029 if (rc == WAIT_OBJECT_0) {
1030 /* Yield to make sure real Python signal
1031 * handler called.
1032 */
Mark Hammond975e3922002-07-16 01:29:19 +00001033 Sleep(1);
1034 Py_BLOCK_THREADS
Mark Hammond975e3922002-07-16 01:29:19 +00001035 errno = EINTR;
1036 PyErr_SetFromErrno(PyExc_IOError);
1037 return -1;
1038 }
1039 }
Fred Drake0e123952000-06-29 21:31:02 +00001040 Py_END_ALLOW_THREADS
1041 }
Martin v. Löwis02af9642002-01-16 11:04:06 +00001042#elif defined(PYOS_OS2)
Guido van Rossum8e9ebfd1997-11-22 21:53:48 +00001043 /* This Sleep *IS* Interruptable by Exceptions */
Guido van Rossum1d0d7e41997-12-29 20:03:10 +00001044 Py_BEGIN_ALLOW_THREADS
Guido van Rossum8e9ebfd1997-11-22 21:53:48 +00001045 if (DosSleep(secs * 1000) != NO_ERROR) {
Guido van Rossum1d0d7e41997-12-29 20:03:10 +00001046 Py_BLOCK_THREADS
Guido van Rossum8e9ebfd1997-11-22 21:53:48 +00001047 PyErr_SetFromErrno(PyExc_IOError);
1048 return -1;
1049 }
Guido van Rossum1d0d7e41997-12-29 20:03:10 +00001050 Py_END_ALLOW_THREADS
Martin v. Löwis02af9642002-01-16 11:04:06 +00001051#elif defined(PLAN9)
1052 {
1053 double millisecs = secs * 1000.0;
1054 if (millisecs > (double)LONG_MAX) {
1055 PyErr_SetString(PyExc_OverflowError, "sleep length is too large");
1056 return -1;
1057 }
1058 /* This sleep *CAN BE* interrupted. */
1059 Py_BEGIN_ALLOW_THREADS
1060 if(sleep((long)millisecs) < 0){
1061 Py_BLOCK_THREADS
1062 PyErr_SetFromErrno(PyExc_IOError);
1063 return -1;
1064 }
1065 Py_END_ALLOW_THREADS
1066 }
1067#else
Guido van Rossumb6775db1994-08-01 11:34:53 +00001068 /* XXX Can't interrupt this sleep */
Guido van Rossum8607ae21997-11-03 22:04:46 +00001069 Py_BEGIN_ALLOW_THREADS
Guido van Rossumb6775db1994-08-01 11:34:53 +00001070 sleep((int)secs);
Guido van Rossum8607ae21997-11-03 22:04:46 +00001071 Py_END_ALLOW_THREADS
Martin v. Löwis02af9642002-01-16 11:04:06 +00001072#endif
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001073
Guido van Rossumb6775db1994-08-01 11:34:53 +00001074 return 0;
Guido van Rossum80c9d881991-04-16 08:47:51 +00001075}