blob: cc302377e4fa3ec5400cf517cae31eb4e7526fa9 [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
Thomas Wouters477c8d52006-05-27 19:21:47 +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
Thomas Wouters0e3f5912006-08-11 14:57:12 +000022#ifdef HAVE_SYS_TYPES_H
Guido van Rossumb6775db1994-08-01 11:34:53 +000023#include <sys/types.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +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
Thomas Wouters477c8d52006-05-27 19:21:47 +000068#if defined(MS_WINDOWS) && !defined(__BORLANDC__)
69/* Win32 has better clock replacement; we have our own version below. */
70#undef HAVE_CLOCK
71#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 Rossum234f9421993-06-17 12:35:49 +000083/* Forward declarations */
Tim Petersdbd9ba62000-07-09 03:09:57 +000084static int floatsleep(double);
Thomas Woutersed77bac2000-07-24 15:26:39 +000085static double floattime(void);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000086
Guido van Rossumcfbaecc1998-08-25 14:51:12 +000087/* For Y2K check */
88static PyObject *moddict;
89
Tim Peters1b6f7a92004-06-20 02:50:16 +000090/* Exposed in timefuncs.h. */
91time_t
Brett Cannon298c3802004-06-19 20:48:43 +000092_PyTime_DoubleToTimet(double x)
93{
94 time_t result;
95 double diff;
96
97 result = (time_t)x;
98 /* How much info did we lose? time_t may be an integral or
99 * floating type, and we don't know which. If it's integral,
100 * we don't know whether C truncates, rounds, returns the floor,
101 * etc. If we lost a second or more, the C rounding is
102 * unreasonable, or the input just doesn't fit in a time_t;
103 * call it an error regardless. Note that the original cast to
104 * time_t can cause a C error too, but nothing we can do to
105 * worm around that.
106 */
107 diff = x - (double)result;
108 if (diff <= -1.0 || diff >= 1.0) {
109 PyErr_SetString(PyExc_ValueError,
110 "timestamp out of range for platform time_t");
111 result = (time_t)-1;
112 }
113 return result;
114}
115
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000116static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000117time_time(PyObject *self, PyObject *unused)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000118{
Guido van Rossumb6775db1994-08-01 11:34:53 +0000119 double secs;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000120 secs = floattime();
121 if (secs == 0.0) {
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000122 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossuma2b7f401993-01-04 09:09:59 +0000123 return NULL;
124 }
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000125 return PyFloat_FromDouble(secs);
Guido van Rossumb6775db1994-08-01 11:34:53 +0000126}
127
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000128PyDoc_STRVAR(time_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000129"time() -> floating point number\n\
130\n\
131Return the current time in seconds since the Epoch.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000132Fractions of a second may be present if the system clock provides them.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000133
Guido van Rossumb6775db1994-08-01 11:34:53 +0000134#ifdef HAVE_CLOCK
135
136#ifndef CLOCKS_PER_SEC
Guido van Rossum1b66a4f1996-02-25 04:50:33 +0000137#ifdef CLK_TCK
138#define CLOCKS_PER_SEC CLK_TCK
139#else
Guido van Rossumb6775db1994-08-01 11:34:53 +0000140#define CLOCKS_PER_SEC 1000000
141#endif
Guido van Rossum1b66a4f1996-02-25 04:50:33 +0000142#endif
Guido van Rossumb6775db1994-08-01 11:34:53 +0000143
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000144static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000145time_clock(PyObject *self, PyObject *unused)
Guido van Rossumb6775db1994-08-01 11:34:53 +0000146{
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000147 return PyFloat_FromDouble(((double)clock()) / CLOCKS_PER_SEC);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000148}
Guido van Rossumb6775db1994-08-01 11:34:53 +0000149#endif /* HAVE_CLOCK */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000150
Thomas Wouters477c8d52006-05-27 19:21:47 +0000151#if defined(MS_WINDOWS) && !defined(__BORLANDC__)
Mark Hammond7ba5e812002-02-12 04:02:33 +0000152/* Due to Mark Hammond and Tim Peters */
Guido van Rossum3917c221997-04-02 05:35:28 +0000153static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000154time_clock(PyObject *self, PyObject *unused)
Guido van Rossum3917c221997-04-02 05:35:28 +0000155{
Tim Peters9ad4b682002-02-13 05:14:18 +0000156 static LARGE_INTEGER ctrStart;
Mark Hammond7ba5e812002-02-12 04:02:33 +0000157 static double divisor = 0.0;
Tim Peters9ad4b682002-02-13 05:14:18 +0000158 LARGE_INTEGER now;
Mark Hammond7ba5e812002-02-12 04:02:33 +0000159 double diff;
Guido van Rossum3917c221997-04-02 05:35:28 +0000160
Mark Hammond7ba5e812002-02-12 04:02:33 +0000161 if (divisor == 0.0) {
Tim Peters9ad4b682002-02-13 05:14:18 +0000162 LARGE_INTEGER freq;
163 QueryPerformanceCounter(&ctrStart);
164 if (!QueryPerformanceFrequency(&freq) || freq.QuadPart == 0) {
Mark Hammond7ba5e812002-02-12 04:02:33 +0000165 /* Unlikely to happen - this works on all intel
166 machines at least! Revert to clock() */
Guido van Rossumd8faa362007-04-27 19:54:29 +0000167 return PyFloat_FromDouble(((double)clock()) /
168 CLOCKS_PER_SEC);
Guido van Rossum3917c221997-04-02 05:35:28 +0000169 }
Tim Peters9ad4b682002-02-13 05:14:18 +0000170 divisor = (double)freq.QuadPart;
Guido van Rossum3917c221997-04-02 05:35:28 +0000171 }
Tim Peters9ad4b682002-02-13 05:14:18 +0000172 QueryPerformanceCounter(&now);
173 diff = (double)(now.QuadPart - ctrStart.QuadPart);
Mark Hammond7ba5e812002-02-12 04:02:33 +0000174 return PyFloat_FromDouble(diff / divisor);
Guido van Rossum3917c221997-04-02 05:35:28 +0000175}
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000176
Guido van Rossum3917c221997-04-02 05:35:28 +0000177#define HAVE_CLOCK /* So it gets included in the methods */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000178#endif /* MS_WINDOWS && !defined(__BORLANDC__) */
Guido van Rossum3917c221997-04-02 05:35:28 +0000179
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000180#ifdef HAVE_CLOCK
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000181PyDoc_STRVAR(clock_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000182"clock() -> floating point number\n\
183\n\
184Return the CPU time or real time since the start of the process or since\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000185the first call to clock(). This has as much precision as the system\n\
186records.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000187#endif
188
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000189static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000190time_sleep(PyObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000191{
Guido van Rossum775f4da1993-01-09 17:18:52 +0000192 double secs;
Thomas Woutersfe385252001-01-19 23:16:56 +0000193 if (!PyArg_ParseTuple(args, "d:sleep", &secs))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000194 return NULL;
Guido van Rossum8607ae21997-11-03 22:04:46 +0000195 if (floatsleep(secs) != 0)
196 return NULL;
197 Py_INCREF(Py_None);
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000198 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000199}
200
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000201PyDoc_STRVAR(sleep_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000202"sleep(seconds)\n\
203\n\
204Delay execution for a given number of seconds. The argument may be\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000205a floating point number for subsecond precision.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000206
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000207static PyStructSequence_Field struct_time_type_fields[] = {
208 {"tm_year", NULL},
209 {"tm_mon", NULL},
210 {"tm_mday", NULL},
211 {"tm_hour", NULL},
212 {"tm_min", NULL},
213 {"tm_sec", NULL},
214 {"tm_wday", NULL},
215 {"tm_yday", NULL},
216 {"tm_isdst", NULL},
217 {0}
218};
219
220static PyStructSequence_Desc struct_time_type_desc = {
Guido van Rossum14648392001-12-08 18:02:58 +0000221 "time.struct_time",
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000222 NULL,
223 struct_time_type_fields,
224 9,
225};
Tim Peters9ad4b682002-02-13 05:14:18 +0000226
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000227static int initialized;
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000228static PyTypeObject StructTimeType;
229
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000230static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000231tmtotuple(struct tm *p)
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000232{
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000233 PyObject *v = PyStructSequence_New(&StructTimeType);
234 if (v == NULL)
235 return NULL;
Tim Peters9ad4b682002-02-13 05:14:18 +0000236
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000237#define SET(i,val) PyStructSequence_SET_ITEM(v, i, PyInt_FromLong((long) val))
238
239 SET(0, p->tm_year + 1900);
240 SET(1, p->tm_mon + 1); /* Want January == 1 */
241 SET(2, p->tm_mday);
242 SET(3, p->tm_hour);
243 SET(4, p->tm_min);
244 SET(5, p->tm_sec);
245 SET(6, (p->tm_wday + 6) % 7); /* Want Monday == 0 */
246 SET(7, p->tm_yday + 1); /* Want January, 1 == 1 */
247 SET(8, p->tm_isdst);
248#undef SET
249 if (PyErr_Occurred()) {
250 Py_XDECREF(v);
251 return NULL;
252 }
253
254 return v;
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000255}
256
257static PyObject *
Skip Montanaro41cfce92007-08-24 21:11:00 +0000258structtime_totuple(PyObject *t)
259{
260 PyObject *x = NULL;
261 unsigned int i;
262 PyObject *v = PyTuple_New(9);
263 if (v == NULL)
264 return NULL;
265
266 for (i=0; i<9; i++) {
267 x = PyStructSequence_GET_ITEM(t, i);
268 Py_INCREF(x);
269 PyTuple_SET_ITEM(v, i, x);
270 }
271
272 if (PyErr_Occurred()) {
273 Py_XDECREF(v);
274 return NULL;
275 }
276
277 return v;
278}
279
280static PyObject *
Brett Cannon298c3802004-06-19 20:48:43 +0000281time_convert(double when, struct tm * (*function)(const time_t *))
Guido van Rossum234f9421993-06-17 12:35:49 +0000282{
Guido van Rossum6e8583d1996-10-08 14:19:52 +0000283 struct tm *p;
Brett Cannon298c3802004-06-19 20:48:43 +0000284 time_t whent = _PyTime_DoubleToTimet(when);
285
286 if (whent == (time_t)-1 && PyErr_Occurred())
287 return NULL;
Guido van Rossum6e8583d1996-10-08 14:19:52 +0000288 errno = 0;
Brett Cannon298c3802004-06-19 20:48:43 +0000289 p = function(&whent);
Guido van Rossum6e8583d1996-10-08 14:19:52 +0000290 if (p == NULL) {
291#ifdef EINVAL
Guido van Rossum0b1ff661996-11-02 17:31:22 +0000292 if (errno == 0)
Guido van Rossum6e8583d1996-10-08 14:19:52 +0000293 errno = EINVAL;
294#endif
Tim Peters8b19a932003-01-17 20:08:54 +0000295 return PyErr_SetFromErrno(PyExc_ValueError);
Guido van Rossum6e8583d1996-10-08 14:19:52 +0000296 }
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000297 return tmtotuple(p);
Guido van Rossum234f9421993-06-17 12:35:49 +0000298}
299
Fred Drakef901abd2004-08-03 17:58:55 +0000300/* Parse arg tuple that can contain an optional float-or-None value;
301 format needs to be "|O:name".
302 Returns non-zero on success (parallels PyArg_ParseTuple).
303*/
304static int
305parse_time_double_args(PyObject *args, char *format, double *pwhen)
306{
307 PyObject *ot = NULL;
308
309 if (!PyArg_ParseTuple(args, format, &ot))
310 return 0;
311 if (ot == NULL || ot == Py_None)
312 *pwhen = floattime();
313 else {
314 double when = PyFloat_AsDouble(ot);
315 if (PyErr_Occurred())
316 return 0;
317 *pwhen = when;
318 }
319 return 1;
320}
321
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000322static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000323time_gmtime(PyObject *self, PyObject *args)
Guido van Rossum234f9421993-06-17 12:35:49 +0000324{
325 double when;
Fred Drakef901abd2004-08-03 17:58:55 +0000326 if (!parse_time_double_args(args, "|O:gmtime", &when))
Guido van Rossum234f9421993-06-17 12:35:49 +0000327 return NULL;
Brett Cannon298c3802004-06-19 20:48:43 +0000328 return time_convert(when, gmtime);
Guido van Rossum234f9421993-06-17 12:35:49 +0000329}
330
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000331PyDoc_STRVAR(gmtime_doc,
Fred Drake193a3f62002-03-12 21:38:49 +0000332"gmtime([seconds]) -> (tm_year, tm_mon, tm_day, tm_hour, tm_min,\n\
333 tm_sec, tm_wday, tm_yday, tm_isdst)\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000334\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000335Convert seconds since the Epoch to a time tuple expressing UTC (a.k.a.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000336GMT). When 'seconds' is not passed in, convert the current time instead.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000337
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000338static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000339time_localtime(PyObject *self, PyObject *args)
Guido van Rossum234f9421993-06-17 12:35:49 +0000340{
341 double when;
Fred Drakef901abd2004-08-03 17:58:55 +0000342 if (!parse_time_double_args(args, "|O:localtime", &when))
Guido van Rossum234f9421993-06-17 12:35:49 +0000343 return NULL;
Brett Cannon298c3802004-06-19 20:48:43 +0000344 return time_convert(when, localtime);
Guido van Rossum234f9421993-06-17 12:35:49 +0000345}
346
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000347PyDoc_STRVAR(localtime_doc,
Fred Drake193a3f62002-03-12 21:38:49 +0000348"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 +0000349\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000350Convert seconds since the Epoch to a time tuple expressing local time.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000351When 'seconds' is not passed in, convert the current time instead.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000352
Guido van Rossum9e90a671993-06-24 11:10:19 +0000353static int
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000354gettmarg(PyObject *args, struct tm *p)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000355{
Guido van Rossumcfbaecc1998-08-25 14:51:12 +0000356 int y;
Skip Montanaro41cfce92007-08-24 21:11:00 +0000357 PyObject *t = NULL;
Guido van Rossumcfbaecc1998-08-25 14:51:12 +0000358
Guido van Rossumb9081262007-08-25 03:14:09 +0000359 memset((void *) p, '\0', sizeof(struct tm));
360
Skip Montanaro41cfce92007-08-24 21:11:00 +0000361 if (PyTuple_Check(args)) {
362 t = args;
363 Py_INCREF(t);
364 }
365 else if (Py_Type(args) == &StructTimeType) {
366 t = structtime_totuple(args);
367 }
368 else {
369 PyErr_SetString(PyExc_TypeError,
370 "Tuple or struct_time argument required");
Guido van Rossum9e90a671993-06-24 11:10:19 +0000371 return 0;
Skip Montanaro41cfce92007-08-24 21:11:00 +0000372 }
373
374 if (t == NULL || !PyArg_ParseTuple(t, "iiiiiiiii",
375 &y,
376 &p->tm_mon,
377 &p->tm_mday,
378 &p->tm_hour,
379 &p->tm_min,
380 &p->tm_sec,
381 &p->tm_wday,
382 &p->tm_yday,
383 &p->tm_isdst)) {
384 Py_XDECREF(t);
385 return 0;
386 }
387 Py_DECREF(t);
388
Guido van Rossumcfbaecc1998-08-25 14:51:12 +0000389 if (y < 1900) {
390 PyObject *accept = PyDict_GetItemString(moddict,
391 "accept2dyear");
Guido van Rossumddefaf32007-01-14 03:31:43 +0000392 if (accept == NULL || !PyInt_CheckExact(accept) ||
Guido van Rossumcfbaecc1998-08-25 14:51:12 +0000393 PyInt_AsLong(accept) == 0) {
394 PyErr_SetString(PyExc_ValueError,
395 "year >= 1900 required");
396 return 0;
397 }
398 if (69 <= y && y <= 99)
399 y += 1900;
400 else if (0 <= y && y <= 68)
401 y += 2000;
402 else {
403 PyErr_SetString(PyExc_ValueError,
Skip Montanaro1a10aac2001-08-22 12:39:16 +0000404 "year out of range");
Guido van Rossumcfbaecc1998-08-25 14:51:12 +0000405 return 0;
406 }
407 }
408 p->tm_year = y - 1900;
Guido van Rossum9e90a671993-06-24 11:10:19 +0000409 p->tm_mon--;
410 p->tm_wday = (p->tm_wday + 1) % 7;
411 p->tm_yday--;
412 return 1;
413}
414
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000415#ifdef HAVE_STRFTIME
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000416static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000417time_strftime(PyObject *self, PyObject *args)
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000418{
Thomas Woutersfe385252001-01-19 23:16:56 +0000419 PyObject *tup = NULL;
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000420 struct tm buf;
421 const char *fmt;
Guido van Rossumeda12ec2007-08-24 03:51:52 +0000422 PyObject *format;
Guido van Rossumfa481162000-06-28 21:33:59 +0000423 size_t fmtlen, buflen;
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000424 char *outbuf = 0;
Guido van Rossumfa481162000-06-28 21:33:59 +0000425 size_t i;
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000426
Thomas Wouters334fb892000-07-25 12:56:38 +0000427 memset((void *) &buf, '\0', sizeof(buf));
Guido van Rossum1f41f841998-04-27 19:04:26 +0000428
Guido van Rossumeda12ec2007-08-24 03:51:52 +0000429 /* Will always expect a unicode string to be passed as format.
430 Given that there's no str type anymore in py3k this seems safe.
431 */
432 if (!PyArg_ParseTuple(args, "U|O:strftime", &format, &tup))
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000433 return NULL;
Thomas Woutersfe385252001-01-19 23:16:56 +0000434
435 if (tup == NULL) {
436 time_t tt = time(NULL);
437 buf = *localtime(&tt);
438 } else if (!gettmarg(tup, &buf))
439 return NULL;
Guido van Rossum10b164a2001-09-25 13:59:01 +0000440
Brett Cannond1080a32004-03-02 04:38:10 +0000441 /* Checks added to make sure strftime() does not crash Python by
442 indexing blindly into some array for a textual representation
443 by some bad index (fixes bug #897625).
Tim Peters1b6f7a92004-06-20 02:50:16 +0000444
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000445 Also support values of zero from Python code for arguments in which
446 that is out of range by forcing that value to the lowest value that
447 is valid (fixed bug #1520914).
448
449 Valid ranges based on what is allowed in struct tm:
450
451 - tm_year: [0, max(int)] (1)
452 - tm_mon: [0, 11] (2)
453 - tm_mday: [1, 31]
454 - tm_hour: [0, 23]
455 - tm_min: [0, 59]
456 - tm_sec: [0, 60]
457 - tm_wday: [0, 6] (1)
458 - tm_yday: [0, 365] (2)
459 - tm_isdst: [-max(int), max(int)]
460
461 (1) gettmarg() handles bounds-checking.
462 (2) Python's acceptable range is one greater than the range in C,
463 thus need to check against automatic decrement by gettmarg().
Brett Cannond1080a32004-03-02 04:38:10 +0000464 */
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000465 if (buf.tm_mon == -1)
466 buf.tm_mon = 0;
467 else if (buf.tm_mon < 0 || buf.tm_mon > 11) {
Brett Cannond1080a32004-03-02 04:38:10 +0000468 PyErr_SetString(PyExc_ValueError, "month out of range");
469 return NULL;
470 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000471 if (buf.tm_mday == 0)
472 buf.tm_mday = 1;
473 else if (buf.tm_mday < 0 || buf.tm_mday > 31) {
Brett Cannond1080a32004-03-02 04:38:10 +0000474 PyErr_SetString(PyExc_ValueError, "day of month out of range");
475 return NULL;
476 }
477 if (buf.tm_hour < 0 || buf.tm_hour > 23) {
478 PyErr_SetString(PyExc_ValueError, "hour out of range");
479 return NULL;
480 }
481 if (buf.tm_min < 0 || buf.tm_min > 59) {
482 PyErr_SetString(PyExc_ValueError, "minute out of range");
483 return NULL;
484 }
485 if (buf.tm_sec < 0 || buf.tm_sec > 61) {
486 PyErr_SetString(PyExc_ValueError, "seconds out of range");
487 return NULL;
488 }
489 /* tm_wday does not need checking of its upper-bound since taking
490 ``% 7`` in gettmarg() automatically restricts the range. */
491 if (buf.tm_wday < 0) {
492 PyErr_SetString(PyExc_ValueError, "day of week out of range");
493 return NULL;
494 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000495 if (buf.tm_yday == -1)
496 buf.tm_yday = 0;
497 else if (buf.tm_yday < 0 || buf.tm_yday > 365) {
Brett Cannond1080a32004-03-02 04:38:10 +0000498 PyErr_SetString(PyExc_ValueError, "day of year out of range");
499 return NULL;
500 }
501 if (buf.tm_isdst < -1 || buf.tm_isdst > 1) {
502 PyErr_SetString(PyExc_ValueError,
503 "daylight savings flag out of range");
504 return NULL;
505 }
506
Guido van Rossumeda12ec2007-08-24 03:51:52 +0000507 /* Convert the unicode string to an ascii one */
508 fmt = PyUnicode_AsString(format);
509
Guido van Rossumc222ec21999-02-23 00:00:10 +0000510 fmtlen = strlen(fmt);
511
Barry Warsaw4a6cf411997-01-13 22:44:55 +0000512 /* I hate these functions that presume you know how big the output
513 * will be ahead of time...
514 */
Guido van Rossumc222ec21999-02-23 00:00:10 +0000515 for (i = 1024; ; i += i) {
Walter Dörwaldcf47af42007-05-31 19:23:17 +0000516 outbuf = (char *)PyMem_Malloc(i);
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000517 if (outbuf == NULL) {
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000518 return PyErr_NoMemory();
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000519 }
Guido van Rossumc222ec21999-02-23 00:00:10 +0000520 buflen = strftime(outbuf, i, fmt, &buf);
521 if (buflen > 0 || i >= 256 * fmtlen) {
522 /* If the buffer is 256 times as long as the format,
523 it's probably not failing for lack of room!
524 More likely, the format yields an empty result,
525 e.g. an empty format, or %Z when the timezone
526 is unknown. */
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000527 PyObject *ret;
Walter Dörwaldcf47af42007-05-31 19:23:17 +0000528 ret = PyUnicode_FromStringAndSize(outbuf, buflen);
529 PyMem_Free(outbuf);
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000530 return ret;
531 }
Walter Dörwaldcf47af42007-05-31 19:23:17 +0000532 PyMem_Free(outbuf);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000533#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
534 /* VisualStudio .NET 2005 does this properly */
535 if (buflen == 0 && errno == EINVAL) {
536 PyErr_SetString(PyExc_ValueError, "Invalid format string");
537 return 0;
538 }
539#endif
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000540 }
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000541}
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000542
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000543PyDoc_STRVAR(strftime_doc,
Thomas Woutersfe385252001-01-19 23:16:56 +0000544"strftime(format[, tuple]) -> string\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000545\n\
546Convert a time tuple to a string according to a format specification.\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000547See the library reference manual for formatting codes. When the time tuple\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000548is not present, current time as returned by localtime() is used.");
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000549#endif /* HAVE_STRFTIME */
550
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000551static PyObject *
552time_strptime(PyObject *self, PyObject *args)
553{
554 PyObject *strptime_module = PyImport_ImportModule("_strptime");
Raymond Hettinger502168a2003-04-10 16:03:22 +0000555 PyObject *strptime_result;
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000556
Tim Peters513a1cd2003-01-19 04:54:58 +0000557 if (!strptime_module)
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000558 return NULL;
Raymond Hettinger502168a2003-04-10 16:03:22 +0000559 strptime_result = PyObject_CallMethod(strptime_module, "strptime", "O", args);
560 Py_DECREF(strptime_module);
561 return strptime_result;
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000562}
563
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000564PyDoc_STRVAR(strptime_doc,
Brett Cannon20def8b2003-07-01 05:16:08 +0000565"strptime(string, format) -> struct_time\n\
Martin v. Löwisb3cfc1d2001-12-02 12:27:43 +0000566\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000567Parse a string to a time tuple according to a format specification.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000568See the library reference manual for formatting codes (same as strftime()).");
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000569
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000570
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000571static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000572time_asctime(PyObject *self, PyObject *args)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000573{
Thomas Woutersfe385252001-01-19 23:16:56 +0000574 PyObject *tup = NULL;
Guido van Rossum9e90a671993-06-24 11:10:19 +0000575 struct tm buf;
576 char *p;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000577 if (!PyArg_UnpackTuple(args, "asctime", 0, 1, &tup))
Guido van Rossumb2b42dd2000-01-12 16:38:20 +0000578 return NULL;
Thomas Woutersfe385252001-01-19 23:16:56 +0000579 if (tup == NULL) {
580 time_t tt = time(NULL);
581 buf = *localtime(&tt);
582 } else if (!gettmarg(tup, &buf))
Guido van Rossum9e90a671993-06-24 11:10:19 +0000583 return NULL;
584 p = asctime(&buf);
585 if (p[24] == '\n')
586 p[24] = '\0';
Guido van Rossumeda12ec2007-08-24 03:51:52 +0000587 return PyUnicode_FromString(p);
Guido van Rossum9e90a671993-06-24 11:10:19 +0000588}
589
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000590PyDoc_STRVAR(asctime_doc,
Thomas Woutersfe385252001-01-19 23:16:56 +0000591"asctime([tuple]) -> string\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000592\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000593Convert a time tuple to a string, e.g. 'Sat Jun 06 16:26:11 1998'.\n\
594When the time tuple is not present, current time as returned by localtime()\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000595is used.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000596
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000597static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000598time_ctime(PyObject *self, PyObject *args)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000599{
Fred Drakef901abd2004-08-03 17:58:55 +0000600 PyObject *ot = NULL;
Guido van Rossum9e90a671993-06-24 11:10:19 +0000601 time_t tt;
602 char *p;
Guido van Rossum10b164a2001-09-25 13:59:01 +0000603
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000604 if (!PyArg_UnpackTuple(args, "ctime", 0, 1, &ot))
Fred Drakef901abd2004-08-03 17:58:55 +0000605 return NULL;
606 if (ot == NULL || ot == Py_None)
Thomas Woutersfe385252001-01-19 23:16:56 +0000607 tt = time(NULL);
608 else {
Fred Drakef901abd2004-08-03 17:58:55 +0000609 double dt = PyFloat_AsDouble(ot);
610 if (PyErr_Occurred())
Thomas Woutersfe385252001-01-19 23:16:56 +0000611 return NULL;
Brett Cannon298c3802004-06-19 20:48:43 +0000612 tt = _PyTime_DoubleToTimet(dt);
613 if (tt == (time_t)-1 && PyErr_Occurred())
614 return NULL;
Thomas Woutersfe385252001-01-19 23:16:56 +0000615 }
Guido van Rossum9e90a671993-06-24 11:10:19 +0000616 p = ctime(&tt);
Guido van Rossum78535701998-03-03 22:19:10 +0000617 if (p == NULL) {
618 PyErr_SetString(PyExc_ValueError, "unconvertible time");
619 return NULL;
620 }
Guido van Rossum9e90a671993-06-24 11:10:19 +0000621 if (p[24] == '\n')
622 p[24] = '\0';
Guido van Rossumeda12ec2007-08-24 03:51:52 +0000623 return PyUnicode_FromString(p);
Guido van Rossum9e90a671993-06-24 11:10:19 +0000624}
625
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000626PyDoc_STRVAR(ctime_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000627"ctime(seconds) -> string\n\
628\n\
629Convert a time in seconds since the Epoch to a string in local time.\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000630This is equivalent to asctime(localtime(seconds)). When the time tuple is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000631not present, current time as returned by localtime() is used.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000632
Guido van Rossum60cd8131998-03-06 17:16:21 +0000633#ifdef HAVE_MKTIME
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000634static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000635time_mktime(PyObject *self, PyObject *tup)
Guido van Rossum234f9421993-06-17 12:35:49 +0000636{
637 struct tm buf;
Guido van Rossumbceeac81996-05-23 22:53:47 +0000638 time_t tt;
639 tt = time(&tt);
640 buf = *localtime(&tt);
Guido van Rossumb2b42dd2000-01-12 16:38:20 +0000641 if (!gettmarg(tup, &buf))
Guido van Rossum234f9421993-06-17 12:35:49 +0000642 return NULL;
Guido van Rossumbceeac81996-05-23 22:53:47 +0000643 tt = mktime(&buf);
644 if (tt == (time_t)(-1)) {
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000645 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum10b164a2001-09-25 13:59:01 +0000646 "mktime argument out of range");
Guido van Rossumbceeac81996-05-23 22:53:47 +0000647 return NULL;
648 }
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000649 return PyFloat_FromDouble((double)tt);
Guido van Rossum234f9421993-06-17 12:35:49 +0000650}
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000651
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000652PyDoc_STRVAR(mktime_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000653"mktime(tuple) -> floating point number\n\
654\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000655Convert a time tuple in local time to seconds since the Epoch.");
Guido van Rossum60cd8131998-03-06 17:16:21 +0000656#endif /* HAVE_MKTIME */
Guido van Rossum234f9421993-06-17 12:35:49 +0000657
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000658#ifdef HAVE_WORKING_TZSET
659void inittimezone(PyObject *module);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000660
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000661static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000662time_tzset(PyObject *self, PyObject *unused)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000663{
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000664 PyObject* m;
Fred Drake9bb74322002-04-01 14:49:59 +0000665
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000666 m = PyImport_ImportModule("time");
667 if (m == NULL) {
668 return NULL;
669 }
670
671 tzset();
672
673 /* Reset timezone, altzone, daylight and tzname */
674 inittimezone(m);
675 Py_DECREF(m);
Tim Peters1b6f7a92004-06-20 02:50:16 +0000676
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000677 Py_INCREF(Py_None);
678 return Py_None;
679}
680
681PyDoc_STRVAR(tzset_doc,
682"tzset(zone)\n\
683\n\
684Initialize, or reinitialize, the local timezone to the value stored in\n\
685os.environ['TZ']. The TZ environment variable should be specified in\n\
Neal Norwitzdc8e1942004-07-20 22:34:37 +0000686standard Unix timezone format as documented in the tzset man page\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000687(eg. 'US/Eastern', 'Europe/Amsterdam'). Unknown timezones will silently\n\
688fall back to UTC. If the TZ environment variable is not set, the local\n\
689timezone is set to the systems best guess of wallclock time.\n\
690Changing the TZ environment variable without calling tzset *may* change\n\
691the local timezone used by methods such as localtime, but this behaviour\n\
692should not be relied on.");
693#endif /* HAVE_WORKING_TZSET */
694
695void inittimezone(PyObject *m) {
696 /* This code moved from inittime wholesale to allow calling it from
697 time_tzset. In the future, some parts of it can be moved back
698 (for platforms that don't HAVE_WORKING_TZSET, when we know what they
699 are), and the extranious calls to tzset(3) should be removed.
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000700 I haven't done this yet, as I don't want to change this code as
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000701 little as possible when introducing the time.tzset and time.tzsetwall
702 methods. This should simply be a method of doing the following once,
703 at the top of this function and removing the call to tzset() from
704 time_tzset():
705
706 #ifdef HAVE_TZSET
707 tzset()
708 #endif
709
710 And I'm lazy and hate C so nyer.
711 */
Guido van Rossum10b164a2001-09-25 13:59:01 +0000712#if defined(HAVE_TZNAME) && !defined(__GLIBC__) && !defined(__CYGWIN__)
Guido van Rossum234f9421993-06-17 12:35:49 +0000713 tzset();
Guido van Rossum26452411998-09-28 22:07:11 +0000714#ifdef PYOS_OS2
Fred Drake9bb74322002-04-01 14:49:59 +0000715 PyModule_AddIntConstant(m, "timezone", _timezone);
Guido van Rossum26452411998-09-28 22:07:11 +0000716#else /* !PYOS_OS2 */
Fred Drake9bb74322002-04-01 14:49:59 +0000717 PyModule_AddIntConstant(m, "timezone", timezone);
Guido van Rossum26452411998-09-28 22:07:11 +0000718#endif /* PYOS_OS2 */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000719#ifdef HAVE_ALTZONE
Fred Drake9bb74322002-04-01 14:49:59 +0000720 PyModule_AddIntConstant(m, "altzone", altzone);
Guido van Rossumb6775db1994-08-01 11:34:53 +0000721#else
Guido van Rossum26452411998-09-28 22:07:11 +0000722#ifdef PYOS_OS2
Fred Drake9bb74322002-04-01 14:49:59 +0000723 PyModule_AddIntConstant(m, "altzone", _timezone-3600);
Guido van Rossum26452411998-09-28 22:07:11 +0000724#else /* !PYOS_OS2 */
Fred Drake9bb74322002-04-01 14:49:59 +0000725 PyModule_AddIntConstant(m, "altzone", timezone-3600);
Guido van Rossum26452411998-09-28 22:07:11 +0000726#endif /* PYOS_OS2 */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000727#endif
Fred Drake9bb74322002-04-01 14:49:59 +0000728 PyModule_AddIntConstant(m, "daylight", daylight);
729 PyModule_AddObject(m, "tzname",
730 Py_BuildValue("(zz)", tzname[0], tzname[1]));
Guido van Rossum10b164a2001-09-25 13:59:01 +0000731#else /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/
Martin v. Löwis60a5d722002-10-16 20:28:25 +0000732#ifdef HAVE_STRUCT_TM_TM_ZONE
Guido van Rossum234f9421993-06-17 12:35:49 +0000733 {
734#define YEAR ((time_t)((365 * 24 + 6) * 3600))
735 time_t t;
736 struct tm *p;
Guido van Rossum57731601999-03-29 19:12:04 +0000737 long janzone, julyzone;
738 char janname[10], julyname[10];
Guido van Rossum234f9421993-06-17 12:35:49 +0000739 t = (time((time_t *)0) / YEAR) * YEAR;
740 p = localtime(&t);
Guido van Rossum57731601999-03-29 19:12:04 +0000741 janzone = -p->tm_gmtoff;
742 strncpy(janname, p->tm_zone ? p->tm_zone : " ", 9);
743 janname[9] = '\0';
Guido van Rossum234f9421993-06-17 12:35:49 +0000744 t += YEAR/2;
745 p = localtime(&t);
Guido van Rossum57731601999-03-29 19:12:04 +0000746 julyzone = -p->tm_gmtoff;
747 strncpy(julyname, p->tm_zone ? p->tm_zone : " ", 9);
748 julyname[9] = '\0';
Guido van Rossum10b164a2001-09-25 13:59:01 +0000749
Guido van Rossum57731601999-03-29 19:12:04 +0000750 if( janzone < julyzone ) {
751 /* DST is reversed in the southern hemisphere */
Fred Drake9bb74322002-04-01 14:49:59 +0000752 PyModule_AddIntConstant(m, "timezone", julyzone);
753 PyModule_AddIntConstant(m, "altzone", janzone);
754 PyModule_AddIntConstant(m, "daylight",
755 janzone != julyzone);
756 PyModule_AddObject(m, "tzname",
757 Py_BuildValue("(zz)",
758 julyname, janname));
Guido van Rossum57731601999-03-29 19:12:04 +0000759 } else {
Fred Drake9bb74322002-04-01 14:49:59 +0000760 PyModule_AddIntConstant(m, "timezone", janzone);
761 PyModule_AddIntConstant(m, "altzone", julyzone);
762 PyModule_AddIntConstant(m, "daylight",
763 janzone != julyzone);
764 PyModule_AddObject(m, "tzname",
765 Py_BuildValue("(zz)",
766 janname, julyname));
Guido van Rossum57731601999-03-29 19:12:04 +0000767 }
Guido van Rossum234f9421993-06-17 12:35:49 +0000768 }
Guido van Rossume6a4b7b1997-10-08 15:27:56 +0000769#else
Martin v. Löwis60a5d722002-10-16 20:28:25 +0000770#endif /* HAVE_STRUCT_TM_TM_ZONE */
Tim Peters26ae7cd2001-03-20 03:26:49 +0000771#ifdef __CYGWIN__
772 tzset();
Fred Drake9bb74322002-04-01 14:49:59 +0000773 PyModule_AddIntConstant(m, "timezone", _timezone);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000774 PyModule_AddIntConstant(m, "altzone", _timezone-3600);
Fred Drake9bb74322002-04-01 14:49:59 +0000775 PyModule_AddIntConstant(m, "daylight", _daylight);
776 PyModule_AddObject(m, "tzname",
777 Py_BuildValue("(zz)", _tzname[0], _tzname[1]));
Tim Peters26ae7cd2001-03-20 03:26:49 +0000778#endif /* __CYGWIN__ */
Guido van Rossum10b164a2001-09-25 13:59:01 +0000779#endif /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000780}
781
782
783static PyMethodDef time_methods[] = {
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000784 {"time", time_time, METH_NOARGS, time_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000785#ifdef HAVE_CLOCK
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000786 {"clock", time_clock, METH_NOARGS, clock_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000787#endif
788 {"sleep", time_sleep, METH_VARARGS, sleep_doc},
789 {"gmtime", time_gmtime, METH_VARARGS, gmtime_doc},
790 {"localtime", time_localtime, METH_VARARGS, localtime_doc},
791 {"asctime", time_asctime, METH_VARARGS, asctime_doc},
792 {"ctime", time_ctime, METH_VARARGS, ctime_doc},
793#ifdef HAVE_MKTIME
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000794 {"mktime", time_mktime, METH_O, mktime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000795#endif
796#ifdef HAVE_STRFTIME
797 {"strftime", time_strftime, METH_VARARGS, strftime_doc},
798#endif
799 {"strptime", time_strptime, METH_VARARGS, strptime_doc},
800#ifdef HAVE_WORKING_TZSET
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000801 {"tzset", time_tzset, METH_NOARGS, tzset_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000802#endif
803 {NULL, NULL} /* sentinel */
804};
805
806
807PyDoc_STRVAR(module_doc,
808"This module provides various functions to manipulate time values.\n\
809\n\
810There are two standard representations of time. One is the number\n\
811of seconds since the Epoch, in UTC (a.k.a. GMT). It may be an integer\n\
812or a floating point number (to represent fractions of seconds).\n\
813The Epoch is system-defined; on Unix, it is generally January 1st, 1970.\n\
814The actual value can be retrieved by calling gmtime(0).\n\
815\n\
816The other representation is a tuple of 9 integers giving local time.\n\
817The tuple items are:\n\
818 year (four digits, e.g. 1998)\n\
819 month (1-12)\n\
820 day (1-31)\n\
821 hours (0-23)\n\
822 minutes (0-59)\n\
823 seconds (0-59)\n\
824 weekday (0-6, Monday is 0)\n\
825 Julian day (day in the year, 1-366)\n\
826 DST (Daylight Savings Time) flag (-1, 0 or 1)\n\
827If the DST flag is 0, the time is given in the regular time zone;\n\
828if it is 1, the time is given in the DST time zone;\n\
829if it is -1, mktime() should guess based on the date and time.\n\
830\n\
831Variables:\n\
832\n\
833timezone -- difference in seconds between UTC and local standard time\n\
834altzone -- difference in seconds between UTC and local DST time\n\
835daylight -- whether local time should reflect DST\n\
836tzname -- tuple of (standard time zone name, DST time zone name)\n\
837\n\
838Functions:\n\
839\n\
840time() -- return current time in seconds since the Epoch as a float\n\
841clock() -- return CPU time since process start as a float\n\
842sleep() -- delay for a number of seconds given as a float\n\
843gmtime() -- convert seconds since Epoch to UTC tuple\n\
844localtime() -- convert seconds since Epoch to local time tuple\n\
845asctime() -- convert time tuple to string\n\
846ctime() -- convert time in seconds to string\n\
847mktime() -- convert local time tuple to seconds since Epoch\n\
848strftime() -- convert time tuple to string according to format specification\n\
849strptime() -- parse string to time tuple according to format specification\n\
850tzset() -- change the local timezone");
851
852
853PyMODINIT_FUNC
854inittime(void)
855{
856 PyObject *m;
857 char *p;
858 m = Py_InitModule3("time", time_methods, module_doc);
Neal Norwitz1ac754f2006-01-19 06:09:39 +0000859 if (m == NULL)
860 return;
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000861
862 /* Accept 2-digit dates unless PYTHONY2K is set and non-empty */
863 p = Py_GETENV("PYTHONY2K");
864 PyModule_AddIntConstant(m, "accept2dyear", (long) (!p || !*p));
865 /* Squirrel away the module's dictionary for the y2k check */
866 moddict = PyModule_GetDict(m);
867 Py_INCREF(moddict);
868
869 /* Set, or reset, module variables like time.timezone */
870 inittimezone(m);
871
Mark Hammond975e3922002-07-16 01:29:19 +0000872#ifdef MS_WINDOWS
873 /* Helper to allow interrupts for Windows.
874 If Ctrl+C event delivered while not sleeping
875 it will be ignored.
876 */
877 main_thread = PyThread_get_thread_ident();
878 hInterruptEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
879 SetConsoleCtrlHandler( PyCtrlHandler, TRUE);
880#endif /* MS_WINDOWS */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000881 if (!initialized) {
Thomas Wouters477c8d52006-05-27 19:21:47 +0000882 PyStructSequence_InitType(&StructTimeType,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000883 &struct_time_type_desc);
884 }
Fred Drake9bb74322002-04-01 14:49:59 +0000885 Py_INCREF(&StructTimeType);
886 PyModule_AddObject(m, "struct_time", (PyObject*) &StructTimeType);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000887 initialized = 1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000888}
889
890
Guido van Rossumb6775db1994-08-01 11:34:53 +0000891/* Implement floattime() for various platforms */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000892
Guido van Rossumb6775db1994-08-01 11:34:53 +0000893static double
Thomas Woutersf3f33dc2000-07-21 06:00:07 +0000894floattime(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000895{
Guido van Rossumb6775db1994-08-01 11:34:53 +0000896 /* There are three ways to get the time:
Barry Warsaw4a6cf411997-01-13 22:44:55 +0000897 (1) gettimeofday() -- resolution in microseconds
898 (2) ftime() -- resolution in milliseconds
899 (3) time() -- resolution in seconds
900 In all cases the return value is a float in seconds.
901 Since on some systems (e.g. SCO ODT 3.0) gettimeofday() may
902 fail, so we fall back on ftime() or time().
903 Note: clock resolution does not imply clock accuracy! */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000904#ifdef HAVE_GETTIMEOFDAY
Barry Warsaw4a6cf411997-01-13 22:44:55 +0000905 {
906 struct timeval t;
Guido van Rossum3bbc62e1995-01-02 19:30:30 +0000907#ifdef GETTIMEOFDAY_NO_TZ
Barry Warsaw4a6cf411997-01-13 22:44:55 +0000908 if (gettimeofday(&t) == 0)
909 return (double)t.tv_sec + t.tv_usec*0.000001;
Guido van Rossum3bbc62e1995-01-02 19:30:30 +0000910#else /* !GETTIMEOFDAY_NO_TZ */
Barry Warsaw4a6cf411997-01-13 22:44:55 +0000911 if (gettimeofday(&t, (struct timezone *)NULL) == 0)
912 return (double)t.tv_sec + t.tv_usec*0.000001;
Guido van Rossum3bbc62e1995-01-02 19:30:30 +0000913#endif /* !GETTIMEOFDAY_NO_TZ */
Barry Warsaw4a6cf411997-01-13 22:44:55 +0000914 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000915
Guido van Rossumb6775db1994-08-01 11:34:53 +0000916#endif /* !HAVE_GETTIMEOFDAY */
Barry Warsaw4a6cf411997-01-13 22:44:55 +0000917 {
Guido van Rossumd3eb5771999-03-09 16:07:23 +0000918#if defined(HAVE_FTIME)
Barry Warsaw4a6cf411997-01-13 22:44:55 +0000919 struct timeb t;
920 ftime(&t);
921 return (double)t.time + (double)t.millitm * (double)0.001;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000922#else /* !HAVE_FTIME */
Barry Warsaw4a6cf411997-01-13 22:44:55 +0000923 time_t secs;
924 time(&secs);
925 return (double)secs;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000926#endif /* !HAVE_FTIME */
Barry Warsaw4a6cf411997-01-13 22:44:55 +0000927 }
Guido van Rossum426035c1991-02-19 12:27:35 +0000928}
929
Guido van Rossumb6775db1994-08-01 11:34:53 +0000930
931/* Implement floatsleep() for various platforms.
932 When interrupted (or when another error occurs), return -1 and
933 set an exception; else return 0. */
934
935static int
Guido van Rossuma320fd31995-03-09 12:14:15 +0000936floatsleep(double secs)
Guido van Rossum426035c1991-02-19 12:27:35 +0000937{
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000938/* XXX Should test for MS_WINDOWS first! */
Skip Montanaroeb33e5a2007-08-17 12:57:41 +0000939#if defined(HAVE_SELECT) && !defined(__EMX__)
Guido van Rossum426035c1991-02-19 12:27:35 +0000940 struct timeval t;
Guido van Rossum775f4da1993-01-09 17:18:52 +0000941 double frac;
Guido van Rossum775f4da1993-01-09 17:18:52 +0000942 frac = fmod(secs, 1.0);
943 secs = floor(secs);
944 t.tv_sec = (long)secs;
945 t.tv_usec = (long)(frac*1000000.0);
Guido van Rossum8607ae21997-11-03 22:04:46 +0000946 Py_BEGIN_ALLOW_THREADS
Guido van Rossumb6775db1994-08-01 11:34:53 +0000947 if (select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &t) != 0) {
Guido van Rossum09cbb011999-11-08 15:32:27 +0000948#ifdef EINTR
Guido van Rossuma5456d51999-08-19 14:40:27 +0000949 if (errno != EINTR) {
Guido van Rossum09cbb011999-11-08 15:32:27 +0000950#else
951 if (1) {
952#endif
Andrew M. Kuchlingc24ca4b2000-03-24 20:35:20 +0000953 Py_BLOCK_THREADS
Guido van Rossuma5456d51999-08-19 14:40:27 +0000954 PyErr_SetFromErrno(PyExc_IOError);
955 return -1;
956 }
Guido van Rossumb6775db1994-08-01 11:34:53 +0000957 }
Guido van Rossum8607ae21997-11-03 22:04:46 +0000958 Py_END_ALLOW_THREADS
Martin v. Löwis02af9642002-01-16 11:04:06 +0000959#elif defined(__WATCOMC__) && !defined(__QNX__)
Guido van Rossumbceeac81996-05-23 22:53:47 +0000960 /* XXX Can't interrupt this sleep */
Guido van Rossum8607ae21997-11-03 22:04:46 +0000961 Py_BEGIN_ALLOW_THREADS
Guido van Rossumbceeac81996-05-23 22:53:47 +0000962 delay((int)(secs * 1000 + 0.5)); /* delay() uses milliseconds */
Guido van Rossum8607ae21997-11-03 22:04:46 +0000963 Py_END_ALLOW_THREADS
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000964#elif defined(MS_WINDOWS)
Fred Drake0e123952000-06-29 21:31:02 +0000965 {
966 double millisecs = secs * 1000.0;
Tim Peters513a1cd2003-01-19 04:54:58 +0000967 unsigned long ul_millis;
968
Fred Drake0e123952000-06-29 21:31:02 +0000969 if (millisecs > (double)ULONG_MAX) {
Tim Peters513a1cd2003-01-19 04:54:58 +0000970 PyErr_SetString(PyExc_OverflowError,
971 "sleep length is too large");
Fred Drake0e123952000-06-29 21:31:02 +0000972 return -1;
973 }
Fred Drake0e123952000-06-29 21:31:02 +0000974 Py_BEGIN_ALLOW_THREADS
Tim Peters513a1cd2003-01-19 04:54:58 +0000975 /* Allow sleep(0) to maintain win32 semantics, and as decreed
976 * by Guido, only the main thread can be interrupted.
977 */
978 ul_millis = (unsigned long)millisecs;
979 if (ul_millis == 0 ||
980 main_thread != PyThread_get_thread_ident())
981 Sleep(ul_millis);
Mark Hammond975e3922002-07-16 01:29:19 +0000982 else {
983 DWORD rc;
984 ResetEvent(hInterruptEvent);
Tim Peters513a1cd2003-01-19 04:54:58 +0000985 rc = WaitForSingleObject(hInterruptEvent, ul_millis);
986 if (rc == WAIT_OBJECT_0) {
987 /* Yield to make sure real Python signal
988 * handler called.
989 */
Mark Hammond975e3922002-07-16 01:29:19 +0000990 Sleep(1);
991 Py_BLOCK_THREADS
Mark Hammond975e3922002-07-16 01:29:19 +0000992 errno = EINTR;
993 PyErr_SetFromErrno(PyExc_IOError);
994 return -1;
995 }
996 }
Fred Drake0e123952000-06-29 21:31:02 +0000997 Py_END_ALLOW_THREADS
998 }
Martin v. Löwis02af9642002-01-16 11:04:06 +0000999#elif defined(PYOS_OS2)
Guido van Rossum8e9ebfd1997-11-22 21:53:48 +00001000 /* This Sleep *IS* Interruptable by Exceptions */
Guido van Rossum1d0d7e41997-12-29 20:03:10 +00001001 Py_BEGIN_ALLOW_THREADS
Guido van Rossum8e9ebfd1997-11-22 21:53:48 +00001002 if (DosSleep(secs * 1000) != NO_ERROR) {
Guido van Rossum1d0d7e41997-12-29 20:03:10 +00001003 Py_BLOCK_THREADS
Guido van Rossum8e9ebfd1997-11-22 21:53:48 +00001004 PyErr_SetFromErrno(PyExc_IOError);
1005 return -1;
1006 }
Guido van Rossum1d0d7e41997-12-29 20:03:10 +00001007 Py_END_ALLOW_THREADS
Martin v. Löwis02af9642002-01-16 11:04:06 +00001008#elif defined(PLAN9)
1009 {
1010 double millisecs = secs * 1000.0;
1011 if (millisecs > (double)LONG_MAX) {
1012 PyErr_SetString(PyExc_OverflowError, "sleep length is too large");
1013 return -1;
1014 }
1015 /* This sleep *CAN BE* interrupted. */
1016 Py_BEGIN_ALLOW_THREADS
1017 if(sleep((long)millisecs) < 0){
1018 Py_BLOCK_THREADS
1019 PyErr_SetFromErrno(PyExc_IOError);
1020 return -1;
1021 }
1022 Py_END_ALLOW_THREADS
1023 }
1024#else
Guido van Rossumb6775db1994-08-01 11:34:53 +00001025 /* XXX Can't interrupt this sleep */
Guido van Rossum8607ae21997-11-03 22:04:46 +00001026 Py_BEGIN_ALLOW_THREADS
Guido van Rossumb6775db1994-08-01 11:34:53 +00001027 sleep((int)secs);
Guido van Rossum8607ae21997-11-03 22:04:46 +00001028 Py_END_ALLOW_THREADS
Martin v. Löwis02af9642002-01-16 11:04:06 +00001029#endif
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001030
Guido van Rossumb6775db1994-08-01 11:34:53 +00001031 return 0;
Guido van Rossum80c9d881991-04-16 08:47:51 +00001032}
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001033
1034