blob: 4bf3a9c7d4912640c9598fc3fee1abedeaba8c7f [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 Rossumbcc20741998-08-04 22:53:56 +000083#ifdef __BEOS__
Fred Drake56221a72000-08-15 18:52:33 +000084#include <time.h>
Guido van Rossumbcc20741998-08-04 22:53:56 +000085/* For bigtime_t, snooze(). - [cjh] */
86#include <support/SupportDefs.h>
87#include <kernel/OS.h>
88#endif
89
Guido van Rossum234f9421993-06-17 12:35:49 +000090/* Forward declarations */
Tim Petersdbd9ba62000-07-09 03:09:57 +000091static int floatsleep(double);
Thomas Woutersed77bac2000-07-24 15:26:39 +000092static double floattime(void);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000093
Guido van Rossumcfbaecc1998-08-25 14:51:12 +000094/* For Y2K check */
95static PyObject *moddict;
96
Tim Peters1b6f7a92004-06-20 02:50:16 +000097/* Exposed in timefuncs.h. */
98time_t
Brett Cannon298c3802004-06-19 20:48:43 +000099_PyTime_DoubleToTimet(double x)
100{
101 time_t result;
102 double diff;
103
104 result = (time_t)x;
105 /* How much info did we lose? time_t may be an integral or
106 * floating type, and we don't know which. If it's integral,
107 * we don't know whether C truncates, rounds, returns the floor,
108 * etc. If we lost a second or more, the C rounding is
109 * unreasonable, or the input just doesn't fit in a time_t;
110 * call it an error regardless. Note that the original cast to
111 * time_t can cause a C error too, but nothing we can do to
112 * worm around that.
113 */
114 diff = x - (double)result;
115 if (diff <= -1.0 || diff >= 1.0) {
116 PyErr_SetString(PyExc_ValueError,
117 "timestamp out of range for platform time_t");
118 result = (time_t)-1;
119 }
120 return result;
121}
122
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000123static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000124time_time(PyObject *self, PyObject *unused)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000125{
Guido van Rossumb6775db1994-08-01 11:34:53 +0000126 double secs;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000127 secs = floattime();
128 if (secs == 0.0) {
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000129 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossuma2b7f401993-01-04 09:09:59 +0000130 return NULL;
131 }
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000132 return PyFloat_FromDouble(secs);
Guido van Rossumb6775db1994-08-01 11:34:53 +0000133}
134
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000135PyDoc_STRVAR(time_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000136"time() -> floating point number\n\
137\n\
138Return the current time in seconds since the Epoch.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000139Fractions of a second may be present if the system clock provides them.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000140
Guido van Rossumb6775db1994-08-01 11:34:53 +0000141#ifdef HAVE_CLOCK
142
143#ifndef CLOCKS_PER_SEC
Guido van Rossum1b66a4f1996-02-25 04:50:33 +0000144#ifdef CLK_TCK
145#define CLOCKS_PER_SEC CLK_TCK
146#else
Guido van Rossumb6775db1994-08-01 11:34:53 +0000147#define CLOCKS_PER_SEC 1000000
148#endif
Guido van Rossum1b66a4f1996-02-25 04:50:33 +0000149#endif
Guido van Rossumb6775db1994-08-01 11:34:53 +0000150
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000151static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000152time_clock(PyObject *self, PyObject *unused)
Guido van Rossumb6775db1994-08-01 11:34:53 +0000153{
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000154 return PyFloat_FromDouble(((double)clock()) / CLOCKS_PER_SEC);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000155}
Guido van Rossumb6775db1994-08-01 11:34:53 +0000156#endif /* HAVE_CLOCK */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000157
Thomas Wouters477c8d52006-05-27 19:21:47 +0000158#if defined(MS_WINDOWS) && !defined(__BORLANDC__)
Mark Hammond7ba5e812002-02-12 04:02:33 +0000159/* Due to Mark Hammond and Tim Peters */
Guido van Rossum3917c221997-04-02 05:35:28 +0000160static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000161time_clock(PyObject *self, PyObject *unused)
Guido van Rossum3917c221997-04-02 05:35:28 +0000162{
Tim Peters9ad4b682002-02-13 05:14:18 +0000163 static LARGE_INTEGER ctrStart;
Mark Hammond7ba5e812002-02-12 04:02:33 +0000164 static double divisor = 0.0;
Tim Peters9ad4b682002-02-13 05:14:18 +0000165 LARGE_INTEGER now;
Mark Hammond7ba5e812002-02-12 04:02:33 +0000166 double diff;
Guido van Rossum3917c221997-04-02 05:35:28 +0000167
Mark Hammond7ba5e812002-02-12 04:02:33 +0000168 if (divisor == 0.0) {
Tim Peters9ad4b682002-02-13 05:14:18 +0000169 LARGE_INTEGER freq;
170 QueryPerformanceCounter(&ctrStart);
171 if (!QueryPerformanceFrequency(&freq) || freq.QuadPart == 0) {
Mark Hammond7ba5e812002-02-12 04:02:33 +0000172 /* Unlikely to happen - this works on all intel
173 machines at least! Revert to clock() */
Guido van Rossumd8faa362007-04-27 19:54:29 +0000174 return PyFloat_FromDouble(((double)clock()) /
175 CLOCKS_PER_SEC);
Guido van Rossum3917c221997-04-02 05:35:28 +0000176 }
Tim Peters9ad4b682002-02-13 05:14:18 +0000177 divisor = (double)freq.QuadPart;
Guido van Rossum3917c221997-04-02 05:35:28 +0000178 }
Tim Peters9ad4b682002-02-13 05:14:18 +0000179 QueryPerformanceCounter(&now);
180 diff = (double)(now.QuadPart - ctrStart.QuadPart);
Mark Hammond7ba5e812002-02-12 04:02:33 +0000181 return PyFloat_FromDouble(diff / divisor);
Guido van Rossum3917c221997-04-02 05:35:28 +0000182}
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000183
Guido van Rossum3917c221997-04-02 05:35:28 +0000184#define HAVE_CLOCK /* So it gets included in the methods */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000185#endif /* MS_WINDOWS && !defined(__BORLANDC__) */
Guido van Rossum3917c221997-04-02 05:35:28 +0000186
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000187#ifdef HAVE_CLOCK
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000188PyDoc_STRVAR(clock_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000189"clock() -> floating point number\n\
190\n\
191Return the CPU time or real time since the start of the process or since\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000192the first call to clock(). This has as much precision as the system\n\
193records.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000194#endif
195
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000196static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000197time_sleep(PyObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000198{
Guido van Rossum775f4da1993-01-09 17:18:52 +0000199 double secs;
Thomas Woutersfe385252001-01-19 23:16:56 +0000200 if (!PyArg_ParseTuple(args, "d:sleep", &secs))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000201 return NULL;
Guido van Rossum8607ae21997-11-03 22:04:46 +0000202 if (floatsleep(secs) != 0)
203 return NULL;
204 Py_INCREF(Py_None);
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000205 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000206}
207
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000208PyDoc_STRVAR(sleep_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000209"sleep(seconds)\n\
210\n\
211Delay execution for a given number of seconds. The argument may be\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000212a floating point number for subsecond precision.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000213
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000214static PyStructSequence_Field struct_time_type_fields[] = {
215 {"tm_year", NULL},
216 {"tm_mon", NULL},
217 {"tm_mday", NULL},
218 {"tm_hour", NULL},
219 {"tm_min", NULL},
220 {"tm_sec", NULL},
221 {"tm_wday", NULL},
222 {"tm_yday", NULL},
223 {"tm_isdst", NULL},
224 {0}
225};
226
227static PyStructSequence_Desc struct_time_type_desc = {
Guido van Rossum14648392001-12-08 18:02:58 +0000228 "time.struct_time",
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000229 NULL,
230 struct_time_type_fields,
231 9,
232};
Tim Peters9ad4b682002-02-13 05:14:18 +0000233
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000234static int initialized;
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000235static PyTypeObject StructTimeType;
236
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000237static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000238tmtotuple(struct tm *p)
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000239{
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000240 PyObject *v = PyStructSequence_New(&StructTimeType);
241 if (v == NULL)
242 return NULL;
Tim Peters9ad4b682002-02-13 05:14:18 +0000243
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000244#define SET(i,val) PyStructSequence_SET_ITEM(v, i, PyInt_FromLong((long) val))
245
246 SET(0, p->tm_year + 1900);
247 SET(1, p->tm_mon + 1); /* Want January == 1 */
248 SET(2, p->tm_mday);
249 SET(3, p->tm_hour);
250 SET(4, p->tm_min);
251 SET(5, p->tm_sec);
252 SET(6, (p->tm_wday + 6) % 7); /* Want Monday == 0 */
253 SET(7, p->tm_yday + 1); /* Want January, 1 == 1 */
254 SET(8, p->tm_isdst);
255#undef SET
256 if (PyErr_Occurred()) {
257 Py_XDECREF(v);
258 return NULL;
259 }
260
261 return v;
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000262}
263
264static PyObject *
Brett Cannon298c3802004-06-19 20:48:43 +0000265time_convert(double when, struct tm * (*function)(const time_t *))
Guido van Rossum234f9421993-06-17 12:35:49 +0000266{
Guido van Rossum6e8583d1996-10-08 14:19:52 +0000267 struct tm *p;
Brett Cannon298c3802004-06-19 20:48:43 +0000268 time_t whent = _PyTime_DoubleToTimet(when);
269
270 if (whent == (time_t)-1 && PyErr_Occurred())
271 return NULL;
Guido van Rossum6e8583d1996-10-08 14:19:52 +0000272 errno = 0;
Brett Cannon298c3802004-06-19 20:48:43 +0000273 p = function(&whent);
Guido van Rossum6e8583d1996-10-08 14:19:52 +0000274 if (p == NULL) {
275#ifdef EINVAL
Guido van Rossum0b1ff661996-11-02 17:31:22 +0000276 if (errno == 0)
Guido van Rossum6e8583d1996-10-08 14:19:52 +0000277 errno = EINVAL;
278#endif
Tim Peters8b19a932003-01-17 20:08:54 +0000279 return PyErr_SetFromErrno(PyExc_ValueError);
Guido van Rossum6e8583d1996-10-08 14:19:52 +0000280 }
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000281 return tmtotuple(p);
Guido van Rossum234f9421993-06-17 12:35:49 +0000282}
283
Fred Drakef901abd2004-08-03 17:58:55 +0000284/* Parse arg tuple that can contain an optional float-or-None value;
285 format needs to be "|O:name".
286 Returns non-zero on success (parallels PyArg_ParseTuple).
287*/
288static int
289parse_time_double_args(PyObject *args, char *format, double *pwhen)
290{
291 PyObject *ot = NULL;
292
293 if (!PyArg_ParseTuple(args, format, &ot))
294 return 0;
295 if (ot == NULL || ot == Py_None)
296 *pwhen = floattime();
297 else {
298 double when = PyFloat_AsDouble(ot);
299 if (PyErr_Occurred())
300 return 0;
301 *pwhen = when;
302 }
303 return 1;
304}
305
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000306static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000307time_gmtime(PyObject *self, PyObject *args)
Guido van Rossum234f9421993-06-17 12:35:49 +0000308{
309 double when;
Fred Drakef901abd2004-08-03 17:58:55 +0000310 if (!parse_time_double_args(args, "|O:gmtime", &when))
Guido van Rossum234f9421993-06-17 12:35:49 +0000311 return NULL;
Brett Cannon298c3802004-06-19 20:48:43 +0000312 return time_convert(when, gmtime);
Guido van Rossum234f9421993-06-17 12:35:49 +0000313}
314
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000315PyDoc_STRVAR(gmtime_doc,
Fred Drake193a3f62002-03-12 21:38:49 +0000316"gmtime([seconds]) -> (tm_year, tm_mon, tm_day, tm_hour, tm_min,\n\
317 tm_sec, tm_wday, tm_yday, tm_isdst)\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000318\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000319Convert seconds since the Epoch to a time tuple expressing UTC (a.k.a.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000320GMT). When 'seconds' is not passed in, convert the current time instead.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000321
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000322static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000323time_localtime(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:localtime", &when))
Guido van Rossum234f9421993-06-17 12:35:49 +0000327 return NULL;
Brett Cannon298c3802004-06-19 20:48:43 +0000328 return time_convert(when, localtime);
Guido van Rossum234f9421993-06-17 12:35:49 +0000329}
330
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000331PyDoc_STRVAR(localtime_doc,
Fred Drake193a3f62002-03-12 21:38:49 +0000332"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 +0000333\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000334Convert seconds since the Epoch to a time tuple expressing local time.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000335When 'seconds' is not passed in, convert the current time instead.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000336
Guido van Rossum9e90a671993-06-24 11:10:19 +0000337static int
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000338gettmarg(PyObject *args, struct tm *p)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000339{
Guido van Rossumcfbaecc1998-08-25 14:51:12 +0000340 int y;
Thomas Wouters334fb892000-07-25 12:56:38 +0000341 memset((void *) p, '\0', sizeof(struct tm));
Guido van Rossumcfbaecc1998-08-25 14:51:12 +0000342
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000343 if (!PyArg_Parse(args, "(iiiiiiiii)",
Guido van Rossumcfbaecc1998-08-25 14:51:12 +0000344 &y,
Barry Warsaw4a6cf411997-01-13 22:44:55 +0000345 &p->tm_mon,
346 &p->tm_mday,
347 &p->tm_hour,
348 &p->tm_min,
349 &p->tm_sec,
350 &p->tm_wday,
351 &p->tm_yday,
352 &p->tm_isdst))
Guido van Rossum9e90a671993-06-24 11:10:19 +0000353 return 0;
Guido van Rossumcfbaecc1998-08-25 14:51:12 +0000354 if (y < 1900) {
355 PyObject *accept = PyDict_GetItemString(moddict,
356 "accept2dyear");
Guido van Rossumddefaf32007-01-14 03:31:43 +0000357 if (accept == NULL || !PyInt_CheckExact(accept) ||
Guido van Rossumcfbaecc1998-08-25 14:51:12 +0000358 PyInt_AsLong(accept) == 0) {
359 PyErr_SetString(PyExc_ValueError,
360 "year >= 1900 required");
361 return 0;
362 }
363 if (69 <= y && y <= 99)
364 y += 1900;
365 else if (0 <= y && y <= 68)
366 y += 2000;
367 else {
368 PyErr_SetString(PyExc_ValueError,
Skip Montanaro1a10aac2001-08-22 12:39:16 +0000369 "year out of range");
Guido van Rossumcfbaecc1998-08-25 14:51:12 +0000370 return 0;
371 }
372 }
373 p->tm_year = y - 1900;
Guido van Rossum9e90a671993-06-24 11:10:19 +0000374 p->tm_mon--;
375 p->tm_wday = (p->tm_wday + 1) % 7;
376 p->tm_yday--;
377 return 1;
378}
379
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000380#ifdef HAVE_STRFTIME
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000381static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000382time_strftime(PyObject *self, PyObject *args)
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000383{
Thomas Woutersfe385252001-01-19 23:16:56 +0000384 PyObject *tup = NULL;
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000385 struct tm buf;
386 const char *fmt;
Guido van Rossumfa481162000-06-28 21:33:59 +0000387 size_t fmtlen, buflen;
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000388 char *outbuf = 0;
Guido van Rossumfa481162000-06-28 21:33:59 +0000389 size_t i;
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000390
Thomas Wouters334fb892000-07-25 12:56:38 +0000391 memset((void *) &buf, '\0', sizeof(buf));
Guido van Rossum1f41f841998-04-27 19:04:26 +0000392
Thomas Woutersfe385252001-01-19 23:16:56 +0000393 if (!PyArg_ParseTuple(args, "s|O:strftime", &fmt, &tup))
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000394 return NULL;
Thomas Woutersfe385252001-01-19 23:16:56 +0000395
396 if (tup == NULL) {
397 time_t tt = time(NULL);
398 buf = *localtime(&tt);
399 } else if (!gettmarg(tup, &buf))
400 return NULL;
Guido van Rossum10b164a2001-09-25 13:59:01 +0000401
Brett Cannond1080a32004-03-02 04:38:10 +0000402 /* Checks added to make sure strftime() does not crash Python by
403 indexing blindly into some array for a textual representation
404 by some bad index (fixes bug #897625).
Tim Peters1b6f7a92004-06-20 02:50:16 +0000405
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000406 Also support values of zero from Python code for arguments in which
407 that is out of range by forcing that value to the lowest value that
408 is valid (fixed bug #1520914).
409
410 Valid ranges based on what is allowed in struct tm:
411
412 - tm_year: [0, max(int)] (1)
413 - tm_mon: [0, 11] (2)
414 - tm_mday: [1, 31]
415 - tm_hour: [0, 23]
416 - tm_min: [0, 59]
417 - tm_sec: [0, 60]
418 - tm_wday: [0, 6] (1)
419 - tm_yday: [0, 365] (2)
420 - tm_isdst: [-max(int), max(int)]
421
422 (1) gettmarg() handles bounds-checking.
423 (2) Python's acceptable range is one greater than the range in C,
424 thus need to check against automatic decrement by gettmarg().
Brett Cannond1080a32004-03-02 04:38:10 +0000425 */
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000426 if (buf.tm_mon == -1)
427 buf.tm_mon = 0;
428 else if (buf.tm_mon < 0 || buf.tm_mon > 11) {
Brett Cannond1080a32004-03-02 04:38:10 +0000429 PyErr_SetString(PyExc_ValueError, "month out of range");
430 return NULL;
431 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000432 if (buf.tm_mday == 0)
433 buf.tm_mday = 1;
434 else if (buf.tm_mday < 0 || buf.tm_mday > 31) {
Brett Cannond1080a32004-03-02 04:38:10 +0000435 PyErr_SetString(PyExc_ValueError, "day of month out of range");
436 return NULL;
437 }
438 if (buf.tm_hour < 0 || buf.tm_hour > 23) {
439 PyErr_SetString(PyExc_ValueError, "hour out of range");
440 return NULL;
441 }
442 if (buf.tm_min < 0 || buf.tm_min > 59) {
443 PyErr_SetString(PyExc_ValueError, "minute out of range");
444 return NULL;
445 }
446 if (buf.tm_sec < 0 || buf.tm_sec > 61) {
447 PyErr_SetString(PyExc_ValueError, "seconds out of range");
448 return NULL;
449 }
450 /* tm_wday does not need checking of its upper-bound since taking
451 ``% 7`` in gettmarg() automatically restricts the range. */
452 if (buf.tm_wday < 0) {
453 PyErr_SetString(PyExc_ValueError, "day of week out of range");
454 return NULL;
455 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000456 if (buf.tm_yday == -1)
457 buf.tm_yday = 0;
458 else if (buf.tm_yday < 0 || buf.tm_yday > 365) {
Brett Cannond1080a32004-03-02 04:38:10 +0000459 PyErr_SetString(PyExc_ValueError, "day of year out of range");
460 return NULL;
461 }
462 if (buf.tm_isdst < -1 || buf.tm_isdst > 1) {
463 PyErr_SetString(PyExc_ValueError,
464 "daylight savings flag out of range");
465 return NULL;
466 }
467
Guido van Rossumc222ec21999-02-23 00:00:10 +0000468 fmtlen = strlen(fmt);
469
Barry Warsaw4a6cf411997-01-13 22:44:55 +0000470 /* I hate these functions that presume you know how big the output
471 * will be ahead of time...
472 */
Guido van Rossumc222ec21999-02-23 00:00:10 +0000473 for (i = 1024; ; i += i) {
Walter Dörwaldcf47af42007-05-31 19:23:17 +0000474 outbuf = (char *)PyMem_Malloc(i);
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000475 if (outbuf == NULL) {
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000476 return PyErr_NoMemory();
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000477 }
Guido van Rossumc222ec21999-02-23 00:00:10 +0000478 buflen = strftime(outbuf, i, fmt, &buf);
479 if (buflen > 0 || i >= 256 * fmtlen) {
480 /* If the buffer is 256 times as long as the format,
481 it's probably not failing for lack of room!
482 More likely, the format yields an empty result,
483 e.g. an empty format, or %Z when the timezone
484 is unknown. */
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000485 PyObject *ret;
Walter Dörwaldcf47af42007-05-31 19:23:17 +0000486 ret = PyUnicode_FromStringAndSize(outbuf, buflen);
487 PyMem_Free(outbuf);
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000488 return ret;
489 }
Walter Dörwaldcf47af42007-05-31 19:23:17 +0000490 PyMem_Free(outbuf);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000491#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
492 /* VisualStudio .NET 2005 does this properly */
493 if (buflen == 0 && errno == EINVAL) {
494 PyErr_SetString(PyExc_ValueError, "Invalid format string");
495 return 0;
496 }
497#endif
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000498 }
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000499}
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000500
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000501PyDoc_STRVAR(strftime_doc,
Thomas Woutersfe385252001-01-19 23:16:56 +0000502"strftime(format[, tuple]) -> string\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000503\n\
504Convert a time tuple to a string according to a format specification.\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000505See the library reference manual for formatting codes. When the time tuple\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000506is not present, current time as returned by localtime() is used.");
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000507#endif /* HAVE_STRFTIME */
508
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000509static PyObject *
510time_strptime(PyObject *self, PyObject *args)
511{
512 PyObject *strptime_module = PyImport_ImportModule("_strptime");
Raymond Hettinger502168a2003-04-10 16:03:22 +0000513 PyObject *strptime_result;
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000514
Tim Peters513a1cd2003-01-19 04:54:58 +0000515 if (!strptime_module)
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000516 return NULL;
Raymond Hettinger502168a2003-04-10 16:03:22 +0000517 strptime_result = PyObject_CallMethod(strptime_module, "strptime", "O", args);
518 Py_DECREF(strptime_module);
519 return strptime_result;
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000520}
521
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000522PyDoc_STRVAR(strptime_doc,
Brett Cannon20def8b2003-07-01 05:16:08 +0000523"strptime(string, format) -> struct_time\n\
Martin v. Löwisb3cfc1d2001-12-02 12:27:43 +0000524\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000525Parse a string to a time tuple according to a format specification.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000526See the library reference manual for formatting codes (same as strftime()).");
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000527
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000528
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000529static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000530time_asctime(PyObject *self, PyObject *args)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000531{
Thomas Woutersfe385252001-01-19 23:16:56 +0000532 PyObject *tup = NULL;
Guido van Rossum9e90a671993-06-24 11:10:19 +0000533 struct tm buf;
534 char *p;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000535 if (!PyArg_UnpackTuple(args, "asctime", 0, 1, &tup))
Guido van Rossumb2b42dd2000-01-12 16:38:20 +0000536 return NULL;
Thomas Woutersfe385252001-01-19 23:16:56 +0000537 if (tup == NULL) {
538 time_t tt = time(NULL);
539 buf = *localtime(&tt);
540 } else if (!gettmarg(tup, &buf))
Guido van Rossum9e90a671993-06-24 11:10:19 +0000541 return NULL;
542 p = asctime(&buf);
543 if (p[24] == '\n')
544 p[24] = '\0';
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000545 return PyString_FromString(p);
Guido van Rossum9e90a671993-06-24 11:10:19 +0000546}
547
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000548PyDoc_STRVAR(asctime_doc,
Thomas Woutersfe385252001-01-19 23:16:56 +0000549"asctime([tuple]) -> string\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000550\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000551Convert a time tuple to a string, e.g. 'Sat Jun 06 16:26:11 1998'.\n\
552When the time tuple is not present, current time as returned by localtime()\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000553is used.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000554
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000555static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000556time_ctime(PyObject *self, PyObject *args)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000557{
Fred Drakef901abd2004-08-03 17:58:55 +0000558 PyObject *ot = NULL;
Guido van Rossum9e90a671993-06-24 11:10:19 +0000559 time_t tt;
560 char *p;
Guido van Rossum10b164a2001-09-25 13:59:01 +0000561
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000562 if (!PyArg_UnpackTuple(args, "ctime", 0, 1, &ot))
Fred Drakef901abd2004-08-03 17:58:55 +0000563 return NULL;
564 if (ot == NULL || ot == Py_None)
Thomas Woutersfe385252001-01-19 23:16:56 +0000565 tt = time(NULL);
566 else {
Fred Drakef901abd2004-08-03 17:58:55 +0000567 double dt = PyFloat_AsDouble(ot);
568 if (PyErr_Occurred())
Thomas Woutersfe385252001-01-19 23:16:56 +0000569 return NULL;
Brett Cannon298c3802004-06-19 20:48:43 +0000570 tt = _PyTime_DoubleToTimet(dt);
571 if (tt == (time_t)-1 && PyErr_Occurred())
572 return NULL;
Thomas Woutersfe385252001-01-19 23:16:56 +0000573 }
Guido van Rossum9e90a671993-06-24 11:10:19 +0000574 p = ctime(&tt);
Guido van Rossum78535701998-03-03 22:19:10 +0000575 if (p == NULL) {
576 PyErr_SetString(PyExc_ValueError, "unconvertible time");
577 return NULL;
578 }
Guido van Rossum9e90a671993-06-24 11:10:19 +0000579 if (p[24] == '\n')
580 p[24] = '\0';
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000581 return PyString_FromString(p);
Guido van Rossum9e90a671993-06-24 11:10:19 +0000582}
583
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000584PyDoc_STRVAR(ctime_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000585"ctime(seconds) -> string\n\
586\n\
587Convert a time in seconds since the Epoch to a string in local time.\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000588This is equivalent to asctime(localtime(seconds)). When the time tuple is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000589not present, current time as returned by localtime() is used.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000590
Guido van Rossum60cd8131998-03-06 17:16:21 +0000591#ifdef HAVE_MKTIME
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000592static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000593time_mktime(PyObject *self, PyObject *tup)
Guido van Rossum234f9421993-06-17 12:35:49 +0000594{
595 struct tm buf;
Guido van Rossumbceeac81996-05-23 22:53:47 +0000596 time_t tt;
597 tt = time(&tt);
598 buf = *localtime(&tt);
Guido van Rossumb2b42dd2000-01-12 16:38:20 +0000599 if (!gettmarg(tup, &buf))
Guido van Rossum234f9421993-06-17 12:35:49 +0000600 return NULL;
Guido van Rossumbceeac81996-05-23 22:53:47 +0000601 tt = mktime(&buf);
602 if (tt == (time_t)(-1)) {
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000603 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum10b164a2001-09-25 13:59:01 +0000604 "mktime argument out of range");
Guido van Rossumbceeac81996-05-23 22:53:47 +0000605 return NULL;
606 }
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000607 return PyFloat_FromDouble((double)tt);
Guido van Rossum234f9421993-06-17 12:35:49 +0000608}
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000609
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000610PyDoc_STRVAR(mktime_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000611"mktime(tuple) -> floating point number\n\
612\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000613Convert a time tuple in local time to seconds since the Epoch.");
Guido van Rossum60cd8131998-03-06 17:16:21 +0000614#endif /* HAVE_MKTIME */
Guido van Rossum234f9421993-06-17 12:35:49 +0000615
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000616#ifdef HAVE_WORKING_TZSET
617void inittimezone(PyObject *module);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000618
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000619static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000620time_tzset(PyObject *self, PyObject *unused)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000621{
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000622 PyObject* m;
Fred Drake9bb74322002-04-01 14:49:59 +0000623
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000624 m = PyImport_ImportModule("time");
625 if (m == NULL) {
626 return NULL;
627 }
628
629 tzset();
630
631 /* Reset timezone, altzone, daylight and tzname */
632 inittimezone(m);
633 Py_DECREF(m);
Tim Peters1b6f7a92004-06-20 02:50:16 +0000634
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000635 Py_INCREF(Py_None);
636 return Py_None;
637}
638
639PyDoc_STRVAR(tzset_doc,
640"tzset(zone)\n\
641\n\
642Initialize, or reinitialize, the local timezone to the value stored in\n\
643os.environ['TZ']. The TZ environment variable should be specified in\n\
Neal Norwitzdc8e1942004-07-20 22:34:37 +0000644standard Unix timezone format as documented in the tzset man page\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000645(eg. 'US/Eastern', 'Europe/Amsterdam'). Unknown timezones will silently\n\
646fall back to UTC. If the TZ environment variable is not set, the local\n\
647timezone is set to the systems best guess of wallclock time.\n\
648Changing the TZ environment variable without calling tzset *may* change\n\
649the local timezone used by methods such as localtime, but this behaviour\n\
650should not be relied on.");
651#endif /* HAVE_WORKING_TZSET */
652
653void inittimezone(PyObject *m) {
654 /* This code moved from inittime wholesale to allow calling it from
655 time_tzset. In the future, some parts of it can be moved back
656 (for platforms that don't HAVE_WORKING_TZSET, when we know what they
657 are), and the extranious calls to tzset(3) should be removed.
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000658 I haven't done this yet, as I don't want to change this code as
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000659 little as possible when introducing the time.tzset and time.tzsetwall
660 methods. This should simply be a method of doing the following once,
661 at the top of this function and removing the call to tzset() from
662 time_tzset():
663
664 #ifdef HAVE_TZSET
665 tzset()
666 #endif
667
668 And I'm lazy and hate C so nyer.
669 */
Guido van Rossum10b164a2001-09-25 13:59:01 +0000670#if defined(HAVE_TZNAME) && !defined(__GLIBC__) && !defined(__CYGWIN__)
Guido van Rossum234f9421993-06-17 12:35:49 +0000671 tzset();
Guido van Rossum26452411998-09-28 22:07:11 +0000672#ifdef PYOS_OS2
Fred Drake9bb74322002-04-01 14:49:59 +0000673 PyModule_AddIntConstant(m, "timezone", _timezone);
Guido van Rossum26452411998-09-28 22:07:11 +0000674#else /* !PYOS_OS2 */
Fred Drake9bb74322002-04-01 14:49:59 +0000675 PyModule_AddIntConstant(m, "timezone", timezone);
Guido van Rossum26452411998-09-28 22:07:11 +0000676#endif /* PYOS_OS2 */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000677#ifdef HAVE_ALTZONE
Fred Drake9bb74322002-04-01 14:49:59 +0000678 PyModule_AddIntConstant(m, "altzone", altzone);
Guido van Rossumb6775db1994-08-01 11:34:53 +0000679#else
Guido van Rossum26452411998-09-28 22:07:11 +0000680#ifdef PYOS_OS2
Fred Drake9bb74322002-04-01 14:49:59 +0000681 PyModule_AddIntConstant(m, "altzone", _timezone-3600);
Guido van Rossum26452411998-09-28 22:07:11 +0000682#else /* !PYOS_OS2 */
Fred Drake9bb74322002-04-01 14:49:59 +0000683 PyModule_AddIntConstant(m, "altzone", timezone-3600);
Guido van Rossum26452411998-09-28 22:07:11 +0000684#endif /* PYOS_OS2 */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000685#endif
Fred Drake9bb74322002-04-01 14:49:59 +0000686 PyModule_AddIntConstant(m, "daylight", daylight);
687 PyModule_AddObject(m, "tzname",
688 Py_BuildValue("(zz)", tzname[0], tzname[1]));
Guido van Rossum10b164a2001-09-25 13:59:01 +0000689#else /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/
Martin v. Löwis60a5d722002-10-16 20:28:25 +0000690#ifdef HAVE_STRUCT_TM_TM_ZONE
Guido van Rossum234f9421993-06-17 12:35:49 +0000691 {
692#define YEAR ((time_t)((365 * 24 + 6) * 3600))
693 time_t t;
694 struct tm *p;
Guido van Rossum57731601999-03-29 19:12:04 +0000695 long janzone, julyzone;
696 char janname[10], julyname[10];
Guido van Rossum234f9421993-06-17 12:35:49 +0000697 t = (time((time_t *)0) / YEAR) * YEAR;
698 p = localtime(&t);
Guido van Rossum57731601999-03-29 19:12:04 +0000699 janzone = -p->tm_gmtoff;
700 strncpy(janname, p->tm_zone ? p->tm_zone : " ", 9);
701 janname[9] = '\0';
Guido van Rossum234f9421993-06-17 12:35:49 +0000702 t += YEAR/2;
703 p = localtime(&t);
Guido van Rossum57731601999-03-29 19:12:04 +0000704 julyzone = -p->tm_gmtoff;
705 strncpy(julyname, p->tm_zone ? p->tm_zone : " ", 9);
706 julyname[9] = '\0';
Guido van Rossum10b164a2001-09-25 13:59:01 +0000707
Guido van Rossum57731601999-03-29 19:12:04 +0000708 if( janzone < julyzone ) {
709 /* DST is reversed in the southern hemisphere */
Fred Drake9bb74322002-04-01 14:49:59 +0000710 PyModule_AddIntConstant(m, "timezone", julyzone);
711 PyModule_AddIntConstant(m, "altzone", janzone);
712 PyModule_AddIntConstant(m, "daylight",
713 janzone != julyzone);
714 PyModule_AddObject(m, "tzname",
715 Py_BuildValue("(zz)",
716 julyname, janname));
Guido van Rossum57731601999-03-29 19:12:04 +0000717 } else {
Fred Drake9bb74322002-04-01 14:49:59 +0000718 PyModule_AddIntConstant(m, "timezone", janzone);
719 PyModule_AddIntConstant(m, "altzone", julyzone);
720 PyModule_AddIntConstant(m, "daylight",
721 janzone != julyzone);
722 PyModule_AddObject(m, "tzname",
723 Py_BuildValue("(zz)",
724 janname, julyname));
Guido van Rossum57731601999-03-29 19:12:04 +0000725 }
Guido van Rossum234f9421993-06-17 12:35:49 +0000726 }
Guido van Rossume6a4b7b1997-10-08 15:27:56 +0000727#else
Martin v. Löwis60a5d722002-10-16 20:28:25 +0000728#endif /* HAVE_STRUCT_TM_TM_ZONE */
Tim Peters26ae7cd2001-03-20 03:26:49 +0000729#ifdef __CYGWIN__
730 tzset();
Fred Drake9bb74322002-04-01 14:49:59 +0000731 PyModule_AddIntConstant(m, "timezone", _timezone);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000732 PyModule_AddIntConstant(m, "altzone", _timezone-3600);
Fred Drake9bb74322002-04-01 14:49:59 +0000733 PyModule_AddIntConstant(m, "daylight", _daylight);
734 PyModule_AddObject(m, "tzname",
735 Py_BuildValue("(zz)", _tzname[0], _tzname[1]));
Tim Peters26ae7cd2001-03-20 03:26:49 +0000736#endif /* __CYGWIN__ */
Guido van Rossum10b164a2001-09-25 13:59:01 +0000737#endif /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000738}
739
740
741static PyMethodDef time_methods[] = {
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000742 {"time", time_time, METH_NOARGS, time_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000743#ifdef HAVE_CLOCK
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000744 {"clock", time_clock, METH_NOARGS, clock_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000745#endif
746 {"sleep", time_sleep, METH_VARARGS, sleep_doc},
747 {"gmtime", time_gmtime, METH_VARARGS, gmtime_doc},
748 {"localtime", time_localtime, METH_VARARGS, localtime_doc},
749 {"asctime", time_asctime, METH_VARARGS, asctime_doc},
750 {"ctime", time_ctime, METH_VARARGS, ctime_doc},
751#ifdef HAVE_MKTIME
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000752 {"mktime", time_mktime, METH_O, mktime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000753#endif
754#ifdef HAVE_STRFTIME
755 {"strftime", time_strftime, METH_VARARGS, strftime_doc},
756#endif
757 {"strptime", time_strptime, METH_VARARGS, strptime_doc},
758#ifdef HAVE_WORKING_TZSET
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000759 {"tzset", time_tzset, METH_NOARGS, tzset_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000760#endif
761 {NULL, NULL} /* sentinel */
762};
763
764
765PyDoc_STRVAR(module_doc,
766"This module provides various functions to manipulate time values.\n\
767\n\
768There are two standard representations of time. One is the number\n\
769of seconds since the Epoch, in UTC (a.k.a. GMT). It may be an integer\n\
770or a floating point number (to represent fractions of seconds).\n\
771The Epoch is system-defined; on Unix, it is generally January 1st, 1970.\n\
772The actual value can be retrieved by calling gmtime(0).\n\
773\n\
774The other representation is a tuple of 9 integers giving local time.\n\
775The tuple items are:\n\
776 year (four digits, e.g. 1998)\n\
777 month (1-12)\n\
778 day (1-31)\n\
779 hours (0-23)\n\
780 minutes (0-59)\n\
781 seconds (0-59)\n\
782 weekday (0-6, Monday is 0)\n\
783 Julian day (day in the year, 1-366)\n\
784 DST (Daylight Savings Time) flag (-1, 0 or 1)\n\
785If the DST flag is 0, the time is given in the regular time zone;\n\
786if it is 1, the time is given in the DST time zone;\n\
787if it is -1, mktime() should guess based on the date and time.\n\
788\n\
789Variables:\n\
790\n\
791timezone -- difference in seconds between UTC and local standard time\n\
792altzone -- difference in seconds between UTC and local DST time\n\
793daylight -- whether local time should reflect DST\n\
794tzname -- tuple of (standard time zone name, DST time zone name)\n\
795\n\
796Functions:\n\
797\n\
798time() -- return current time in seconds since the Epoch as a float\n\
799clock() -- return CPU time since process start as a float\n\
800sleep() -- delay for a number of seconds given as a float\n\
801gmtime() -- convert seconds since Epoch to UTC tuple\n\
802localtime() -- convert seconds since Epoch to local time tuple\n\
803asctime() -- convert time tuple to string\n\
804ctime() -- convert time in seconds to string\n\
805mktime() -- convert local time tuple to seconds since Epoch\n\
806strftime() -- convert time tuple to string according to format specification\n\
807strptime() -- parse string to time tuple according to format specification\n\
808tzset() -- change the local timezone");
809
810
811PyMODINIT_FUNC
812inittime(void)
813{
814 PyObject *m;
815 char *p;
816 m = Py_InitModule3("time", time_methods, module_doc);
Neal Norwitz1ac754f2006-01-19 06:09:39 +0000817 if (m == NULL)
818 return;
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000819
820 /* Accept 2-digit dates unless PYTHONY2K is set and non-empty */
821 p = Py_GETENV("PYTHONY2K");
822 PyModule_AddIntConstant(m, "accept2dyear", (long) (!p || !*p));
823 /* Squirrel away the module's dictionary for the y2k check */
824 moddict = PyModule_GetDict(m);
825 Py_INCREF(moddict);
826
827 /* Set, or reset, module variables like time.timezone */
828 inittimezone(m);
829
Mark Hammond975e3922002-07-16 01:29:19 +0000830#ifdef MS_WINDOWS
831 /* Helper to allow interrupts for Windows.
832 If Ctrl+C event delivered while not sleeping
833 it will be ignored.
834 */
835 main_thread = PyThread_get_thread_ident();
836 hInterruptEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
837 SetConsoleCtrlHandler( PyCtrlHandler, TRUE);
838#endif /* MS_WINDOWS */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000839 if (!initialized) {
Thomas Wouters477c8d52006-05-27 19:21:47 +0000840 PyStructSequence_InitType(&StructTimeType,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000841 &struct_time_type_desc);
842 }
Fred Drake9bb74322002-04-01 14:49:59 +0000843 Py_INCREF(&StructTimeType);
844 PyModule_AddObject(m, "struct_time", (PyObject*) &StructTimeType);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000845 initialized = 1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000846}
847
848
Guido van Rossumb6775db1994-08-01 11:34:53 +0000849/* Implement floattime() for various platforms */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000850
Guido van Rossumb6775db1994-08-01 11:34:53 +0000851static double
Thomas Woutersf3f33dc2000-07-21 06:00:07 +0000852floattime(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000853{
Guido van Rossumb6775db1994-08-01 11:34:53 +0000854 /* There are three ways to get the time:
Barry Warsaw4a6cf411997-01-13 22:44:55 +0000855 (1) gettimeofday() -- resolution in microseconds
856 (2) ftime() -- resolution in milliseconds
857 (3) time() -- resolution in seconds
858 In all cases the return value is a float in seconds.
859 Since on some systems (e.g. SCO ODT 3.0) gettimeofday() may
860 fail, so we fall back on ftime() or time().
861 Note: clock resolution does not imply clock accuracy! */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000862#ifdef HAVE_GETTIMEOFDAY
Barry Warsaw4a6cf411997-01-13 22:44:55 +0000863 {
864 struct timeval t;
Guido van Rossum3bbc62e1995-01-02 19:30:30 +0000865#ifdef GETTIMEOFDAY_NO_TZ
Barry Warsaw4a6cf411997-01-13 22:44:55 +0000866 if (gettimeofday(&t) == 0)
867 return (double)t.tv_sec + t.tv_usec*0.000001;
Guido van Rossum3bbc62e1995-01-02 19:30:30 +0000868#else /* !GETTIMEOFDAY_NO_TZ */
Barry Warsaw4a6cf411997-01-13 22:44:55 +0000869 if (gettimeofday(&t, (struct timezone *)NULL) == 0)
870 return (double)t.tv_sec + t.tv_usec*0.000001;
Guido van Rossum3bbc62e1995-01-02 19:30:30 +0000871#endif /* !GETTIMEOFDAY_NO_TZ */
Barry Warsaw4a6cf411997-01-13 22:44:55 +0000872 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000873
Guido van Rossumb6775db1994-08-01 11:34:53 +0000874#endif /* !HAVE_GETTIMEOFDAY */
Barry Warsaw4a6cf411997-01-13 22:44:55 +0000875 {
Guido van Rossumd3eb5771999-03-09 16:07:23 +0000876#if defined(HAVE_FTIME)
Barry Warsaw4a6cf411997-01-13 22:44:55 +0000877 struct timeb t;
878 ftime(&t);
879 return (double)t.time + (double)t.millitm * (double)0.001;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000880#else /* !HAVE_FTIME */
Barry Warsaw4a6cf411997-01-13 22:44:55 +0000881 time_t secs;
882 time(&secs);
883 return (double)secs;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000884#endif /* !HAVE_FTIME */
Barry Warsaw4a6cf411997-01-13 22:44:55 +0000885 }
Guido van Rossum426035c1991-02-19 12:27:35 +0000886}
887
Guido van Rossumb6775db1994-08-01 11:34:53 +0000888
889/* Implement floatsleep() for various platforms.
890 When interrupted (or when another error occurs), return -1 and
891 set an exception; else return 0. */
892
893static int
Guido van Rossuma320fd31995-03-09 12:14:15 +0000894floatsleep(double secs)
Guido van Rossum426035c1991-02-19 12:27:35 +0000895{
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000896/* XXX Should test for MS_WINDOWS first! */
Andrew MacIntyre7bf68332002-03-03 02:59:16 +0000897#if defined(HAVE_SELECT) && !defined(__BEOS__) && !defined(__EMX__)
Guido van Rossum426035c1991-02-19 12:27:35 +0000898 struct timeval t;
Guido van Rossum775f4da1993-01-09 17:18:52 +0000899 double frac;
Guido van Rossum775f4da1993-01-09 17:18:52 +0000900 frac = fmod(secs, 1.0);
901 secs = floor(secs);
902 t.tv_sec = (long)secs;
903 t.tv_usec = (long)(frac*1000000.0);
Guido van Rossum8607ae21997-11-03 22:04:46 +0000904 Py_BEGIN_ALLOW_THREADS
Guido van Rossumb6775db1994-08-01 11:34:53 +0000905 if (select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &t) != 0) {
Guido van Rossum09cbb011999-11-08 15:32:27 +0000906#ifdef EINTR
Guido van Rossuma5456d51999-08-19 14:40:27 +0000907 if (errno != EINTR) {
Guido van Rossum09cbb011999-11-08 15:32:27 +0000908#else
909 if (1) {
910#endif
Andrew M. Kuchlingc24ca4b2000-03-24 20:35:20 +0000911 Py_BLOCK_THREADS
Guido van Rossuma5456d51999-08-19 14:40:27 +0000912 PyErr_SetFromErrno(PyExc_IOError);
913 return -1;
914 }
Guido van Rossumb6775db1994-08-01 11:34:53 +0000915 }
Guido van Rossum8607ae21997-11-03 22:04:46 +0000916 Py_END_ALLOW_THREADS
Martin v. Löwis02af9642002-01-16 11:04:06 +0000917#elif defined(__WATCOMC__) && !defined(__QNX__)
Guido van Rossumbceeac81996-05-23 22:53:47 +0000918 /* XXX Can't interrupt this sleep */
Guido van Rossum8607ae21997-11-03 22:04:46 +0000919 Py_BEGIN_ALLOW_THREADS
Guido van Rossumbceeac81996-05-23 22:53:47 +0000920 delay((int)(secs * 1000 + 0.5)); /* delay() uses milliseconds */
Guido van Rossum8607ae21997-11-03 22:04:46 +0000921 Py_END_ALLOW_THREADS
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000922#elif defined(MS_WINDOWS)
Fred Drake0e123952000-06-29 21:31:02 +0000923 {
924 double millisecs = secs * 1000.0;
Tim Peters513a1cd2003-01-19 04:54:58 +0000925 unsigned long ul_millis;
926
Fred Drake0e123952000-06-29 21:31:02 +0000927 if (millisecs > (double)ULONG_MAX) {
Tim Peters513a1cd2003-01-19 04:54:58 +0000928 PyErr_SetString(PyExc_OverflowError,
929 "sleep length is too large");
Fred Drake0e123952000-06-29 21:31:02 +0000930 return -1;
931 }
Fred Drake0e123952000-06-29 21:31:02 +0000932 Py_BEGIN_ALLOW_THREADS
Tim Peters513a1cd2003-01-19 04:54:58 +0000933 /* Allow sleep(0) to maintain win32 semantics, and as decreed
934 * by Guido, only the main thread can be interrupted.
935 */
936 ul_millis = (unsigned long)millisecs;
937 if (ul_millis == 0 ||
938 main_thread != PyThread_get_thread_ident())
939 Sleep(ul_millis);
Mark Hammond975e3922002-07-16 01:29:19 +0000940 else {
941 DWORD rc;
942 ResetEvent(hInterruptEvent);
Tim Peters513a1cd2003-01-19 04:54:58 +0000943 rc = WaitForSingleObject(hInterruptEvent, ul_millis);
944 if (rc == WAIT_OBJECT_0) {
945 /* Yield to make sure real Python signal
946 * handler called.
947 */
Mark Hammond975e3922002-07-16 01:29:19 +0000948 Sleep(1);
949 Py_BLOCK_THREADS
Mark Hammond975e3922002-07-16 01:29:19 +0000950 errno = EINTR;
951 PyErr_SetFromErrno(PyExc_IOError);
952 return -1;
953 }
954 }
Fred Drake0e123952000-06-29 21:31:02 +0000955 Py_END_ALLOW_THREADS
956 }
Martin v. Löwis02af9642002-01-16 11:04:06 +0000957#elif defined(PYOS_OS2)
Guido van Rossum8e9ebfd1997-11-22 21:53:48 +0000958 /* This Sleep *IS* Interruptable by Exceptions */
Guido van Rossum1d0d7e41997-12-29 20:03:10 +0000959 Py_BEGIN_ALLOW_THREADS
Guido van Rossum8e9ebfd1997-11-22 21:53:48 +0000960 if (DosSleep(secs * 1000) != NO_ERROR) {
Guido van Rossum1d0d7e41997-12-29 20:03:10 +0000961 Py_BLOCK_THREADS
Guido van Rossum8e9ebfd1997-11-22 21:53:48 +0000962 PyErr_SetFromErrno(PyExc_IOError);
963 return -1;
964 }
Guido van Rossum1d0d7e41997-12-29 20:03:10 +0000965 Py_END_ALLOW_THREADS
Martin v. Löwis02af9642002-01-16 11:04:06 +0000966#elif defined(__BEOS__)
Guido van Rossumbcc20741998-08-04 22:53:56 +0000967 /* This sleep *CAN BE* interrupted. */
968 {
Guido van Rossumbcc20741998-08-04 22:53:56 +0000969 if( secs <= 0.0 ) {
970 return;
971 }
Guido van Rossum10b164a2001-09-25 13:59:01 +0000972
Guido van Rossumbcc20741998-08-04 22:53:56 +0000973 Py_BEGIN_ALLOW_THREADS
Guido van Rossumd3eb5771999-03-09 16:07:23 +0000974 /* BeOS snooze() is in microseconds... */
975 if( snooze( (bigtime_t)( secs * 1000.0 * 1000.0 ) ) == B_INTERRUPTED ) {
Guido van Rossumbcc20741998-08-04 22:53:56 +0000976 Py_BLOCK_THREADS
977 PyErr_SetFromErrno( PyExc_IOError );
978 return -1;
979 }
980 Py_END_ALLOW_THREADS
981 }
Martin v. Löwis02af9642002-01-16 11:04:06 +0000982#elif defined(PLAN9)
983 {
984 double millisecs = secs * 1000.0;
985 if (millisecs > (double)LONG_MAX) {
986 PyErr_SetString(PyExc_OverflowError, "sleep length is too large");
987 return -1;
988 }
989 /* This sleep *CAN BE* interrupted. */
990 Py_BEGIN_ALLOW_THREADS
991 if(sleep((long)millisecs) < 0){
992 Py_BLOCK_THREADS
993 PyErr_SetFromErrno(PyExc_IOError);
994 return -1;
995 }
996 Py_END_ALLOW_THREADS
997 }
998#else
Guido van Rossumb6775db1994-08-01 11:34:53 +0000999 /* XXX Can't interrupt this sleep */
Guido van Rossum8607ae21997-11-03 22:04:46 +00001000 Py_BEGIN_ALLOW_THREADS
Guido van Rossumb6775db1994-08-01 11:34:53 +00001001 sleep((int)secs);
Guido van Rossum8607ae21997-11-03 22:04:46 +00001002 Py_END_ALLOW_THREADS
Martin v. Löwis02af9642002-01-16 11:04:06 +00001003#endif
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001004
Guido van Rossumb6775db1994-08-01 11:34:53 +00001005 return 0;
Guido van Rossum80c9d881991-04-16 08:47:51 +00001006}
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001007
1008