blob: 79803f4a01da5ca78ce8b368d96f2dce72f291d1 [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"
Alexander Belopolsky6fc4ade2010-08-05 17:34:27 +00005#include "_time.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +00006
Martin v. Löwis8a7c8662007-08-30 15:40:24 +00007#define TZNAME_ENCODING "utf-8"
8
Guido van Rossum87ce7bb1998-06-09 16:30:31 +00009#include <ctype.h>
10
Thomas Wouters0e3f5912006-08-11 14:57:12 +000011#ifdef HAVE_SYS_TYPES_H
Guido van Rossumb6775db1994-08-01 11:34:53 +000012#include <sys/types.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013#endif /* HAVE_SYS_TYPES_H */
Guido van Rossum6d946f91992-08-14 13:49:30 +000014
Guido van Rossumb6775db1994-08-01 11:34:53 +000015#ifdef QUICKWIN
16#include <io.h>
17#endif
18
Guido van Rossum7bf22de1997-12-02 20:34:19 +000019#if defined(__WATCOMC__) && !defined(__QNX__)
Guido van Rossumbceeac81996-05-23 22:53:47 +000020#include <i86.h>
21#else
Guido van Rossumcac6c721996-09-06 13:34:02 +000022#ifdef MS_WINDOWS
Mark Hammond975e3922002-07-16 01:29:19 +000023#define WIN32_LEAN_AND_MEAN
Guido van Rossum258ccd42001-03-02 06:53:29 +000024#include <windows.h>
Mark Hammond975e3922002-07-16 01:29:19 +000025#include "pythread.h"
26
27/* helper to allow us to interrupt sleep() on Windows*/
28static HANDLE hInterruptEvent = NULL;
29static BOOL WINAPI PyCtrlHandler(DWORD dwCtrlType)
30{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000031 SetEvent(hInterruptEvent);
32 /* allow other default handlers to be called.
33 Default Python handler will setup the
34 KeyboardInterrupt exception.
35 */
36 return FALSE;
Mark Hammond975e3922002-07-16 01:29:19 +000037}
38static long main_thread;
39
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000040#if defined(__BORLANDC__)
Guido van Rossumb2fb3641996-09-07 00:47:35 +000041/* These overrides not needed for Win32 */
Guido van Rossumb6775db1994-08-01 11:34:53 +000042#define timezone _timezone
Guido van Rossumcc081121995-03-14 15:05:41 +000043#define tzname _tzname
44#define daylight _daylight
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000045#endif /* __BORLANDC__ */
Guido van Rossumcac6c721996-09-06 13:34:02 +000046#endif /* MS_WINDOWS */
Guido van Rossum7bf22de1997-12-02 20:34:19 +000047#endif /* !__WATCOMC__ || __QNX__ */
Guido van Rossum234f9421993-06-17 12:35:49 +000048
Thomas Wouters477c8d52006-05-27 19:21:47 +000049#if defined(MS_WINDOWS) && !defined(__BORLANDC__)
50/* Win32 has better clock replacement; we have our own version below. */
51#undef HAVE_CLOCK
Martin v. Löwis3bb00702007-08-30 14:37:48 +000052#undef TZNAME_ENCODING
53#define TZNAME_ENCODING "mbcs"
Thomas Wouters477c8d52006-05-27 19:21:47 +000054#endif /* MS_WINDOWS && !defined(__BORLANDC__) */
Guido van Rossum3917c221997-04-02 05:35:28 +000055
Andrew MacIntyre7bf68332002-03-03 02:59:16 +000056#if defined(PYOS_OS2)
57#define INCL_DOS
58#define INCL_ERRORS
59#include <os2.h>
60#endif
61
Guido van Rossum8e9ebfd1997-11-22 21:53:48 +000062#if defined(PYCC_VACPP)
Guido van Rossum26452411998-09-28 22:07:11 +000063#include <sys/time.h>
Guido van Rossum8e9ebfd1997-11-22 21:53:48 +000064#endif
65
Guido van Rossum234f9421993-06-17 12:35:49 +000066/* Forward declarations */
Tim Petersdbd9ba62000-07-09 03:09:57 +000067static int floatsleep(double);
Thomas Woutersed77bac2000-07-24 15:26:39 +000068static double floattime(void);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000069
Guido van Rossumcfbaecc1998-08-25 14:51:12 +000070/* For Y2K check */
71static PyObject *moddict;
72
Barry Warsaw9a2a8a81996-12-06 23:32:14 +000073static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000074time_time(PyObject *self, PyObject *unused)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000075{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000076 double secs;
77 secs = floattime();
78 if (secs == 0.0) {
79 PyErr_SetFromErrno(PyExc_IOError);
80 return NULL;
81 }
82 return PyFloat_FromDouble(secs);
Guido van Rossumb6775db1994-08-01 11:34:53 +000083}
84
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000085PyDoc_STRVAR(time_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +000086"time() -> floating point number\n\
87\n\
88Return the current time in seconds since the Epoch.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000089Fractions of a second may be present if the system clock provides them.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +000090
Guido van Rossumb6775db1994-08-01 11:34:53 +000091#ifdef HAVE_CLOCK
92
93#ifndef CLOCKS_PER_SEC
Guido van Rossum1b66a4f1996-02-25 04:50:33 +000094#ifdef CLK_TCK
95#define CLOCKS_PER_SEC CLK_TCK
96#else
Guido van Rossumb6775db1994-08-01 11:34:53 +000097#define CLOCKS_PER_SEC 1000000
98#endif
Guido van Rossum1b66a4f1996-02-25 04:50:33 +000099#endif
Guido van Rossumb6775db1994-08-01 11:34:53 +0000100
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000101static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000102time_clock(PyObject *self, PyObject *unused)
Guido van Rossumb6775db1994-08-01 11:34:53 +0000103{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000104 return PyFloat_FromDouble(((double)clock()) / CLOCKS_PER_SEC);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000105}
Guido van Rossumb6775db1994-08-01 11:34:53 +0000106#endif /* HAVE_CLOCK */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000107
Thomas Wouters477c8d52006-05-27 19:21:47 +0000108#if defined(MS_WINDOWS) && !defined(__BORLANDC__)
Mark Hammond7ba5e812002-02-12 04:02:33 +0000109/* Due to Mark Hammond and Tim Peters */
Guido van Rossum3917c221997-04-02 05:35:28 +0000110static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000111time_clock(PyObject *self, PyObject *unused)
Guido van Rossum3917c221997-04-02 05:35:28 +0000112{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000113 static LARGE_INTEGER ctrStart;
114 static double divisor = 0.0;
115 LARGE_INTEGER now;
116 double diff;
Guido van Rossum3917c221997-04-02 05:35:28 +0000117
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000118 if (divisor == 0.0) {
119 LARGE_INTEGER freq;
120 QueryPerformanceCounter(&ctrStart);
121 if (!QueryPerformanceFrequency(&freq) || freq.QuadPart == 0) {
122 /* Unlikely to happen - this works on all intel
123 machines at least! Revert to clock() */
124 return PyFloat_FromDouble(((double)clock()) /
125 CLOCKS_PER_SEC);
126 }
127 divisor = (double)freq.QuadPart;
128 }
129 QueryPerformanceCounter(&now);
130 diff = (double)(now.QuadPart - ctrStart.QuadPart);
131 return PyFloat_FromDouble(diff / divisor);
Guido van Rossum3917c221997-04-02 05:35:28 +0000132}
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000133
Guido van Rossum3917c221997-04-02 05:35:28 +0000134#define HAVE_CLOCK /* So it gets included in the methods */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000135#endif /* MS_WINDOWS && !defined(__BORLANDC__) */
Guido van Rossum3917c221997-04-02 05:35:28 +0000136
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000137#ifdef HAVE_CLOCK
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000138PyDoc_STRVAR(clock_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000139"clock() -> floating point number\n\
140\n\
141Return the CPU time or real time since the start of the process or since\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000142the first call to clock(). This has as much precision as the system\n\
143records.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000144#endif
145
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000146static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000147time_sleep(PyObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000148{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000149 double secs;
150 if (!PyArg_ParseTuple(args, "d:sleep", &secs))
151 return NULL;
152 if (floatsleep(secs) != 0)
153 return NULL;
154 Py_INCREF(Py_None);
155 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000156}
157
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000158PyDoc_STRVAR(sleep_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000159"sleep(seconds)\n\
160\n\
161Delay execution for a given number of seconds. The argument may be\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000162a floating point number for subsecond precision.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000163
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000164static PyStructSequence_Field struct_time_type_fields[] = {
Alexander Belopolsky69f3fd02010-06-05 15:04:51 +0000165 {"tm_year", "year, for example, 1993"},
166 {"tm_mon", "month of year, range [1, 12]"},
167 {"tm_mday", "day of month, range [1, 31]"},
168 {"tm_hour", "hours, range [0, 23]"},
169 {"tm_min", "minutes, range [0, 59]"},
170 {"tm_sec", "seconds, range [0, 61])"},
171 {"tm_wday", "day of week, range [0, 6], Monday is 0"},
172 {"tm_yday", "day of year, range [1, 366]"},
173 {"tm_isdst", "1 if summer time is in effect, 0 if not, and -1 if unknown"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000174 {0}
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000175};
176
177static PyStructSequence_Desc struct_time_type_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000178 "time.struct_time",
Alexander Belopolsky69f3fd02010-06-05 15:04:51 +0000179 "The time value as returned by gmtime(), localtime(), and strptime(), and\n"
180 " accepted by asctime(), mktime() and strftime(). May be considered as a\n"
181 " sequence of 9 integers.\n\n"
182 " Note that several fields' values are not the same as those defined by\n"
183 " the C language standard for struct tm. For example, the value of the\n"
184 " field tm_year is the actual year, not year - 1900. See individual\n"
185 " fields' descriptions for details.",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000186 struct_time_type_fields,
187 9,
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000188};
Tim Peters9ad4b682002-02-13 05:14:18 +0000189
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000190static int initialized;
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000191static PyTypeObject StructTimeType;
192
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000193static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000194tmtotuple(struct tm *p)
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000195{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000196 PyObject *v = PyStructSequence_New(&StructTimeType);
197 if (v == NULL)
198 return NULL;
Tim Peters9ad4b682002-02-13 05:14:18 +0000199
Christian Heimes217cfd12007-12-02 14:31:20 +0000200#define SET(i,val) PyStructSequence_SET_ITEM(v, i, PyLong_FromLong((long) val))
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000201
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000202 SET(0, p->tm_year + 1900);
203 SET(1, p->tm_mon + 1); /* Want January == 1 */
204 SET(2, p->tm_mday);
205 SET(3, p->tm_hour);
206 SET(4, p->tm_min);
207 SET(5, p->tm_sec);
208 SET(6, (p->tm_wday + 6) % 7); /* Want Monday == 0 */
209 SET(7, p->tm_yday + 1); /* Want January, 1 == 1 */
210 SET(8, p->tm_isdst);
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000211#undef SET
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000212 if (PyErr_Occurred()) {
213 Py_XDECREF(v);
214 return NULL;
215 }
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000216
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000217 return v;
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000218}
219
220static PyObject *
Skip Montanaro41cfce92007-08-24 21:11:00 +0000221structtime_totuple(PyObject *t)
222{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000223 PyObject *x = NULL;
224 unsigned int i;
225 PyObject *v = PyTuple_New(9);
226 if (v == NULL)
227 return NULL;
Skip Montanaro41cfce92007-08-24 21:11:00 +0000228
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000229 for (i=0; i<9; i++) {
230 x = PyStructSequence_GET_ITEM(t, i);
231 Py_INCREF(x);
232 PyTuple_SET_ITEM(v, i, x);
233 }
Skip Montanaro41cfce92007-08-24 21:11:00 +0000234
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000235 if (PyErr_Occurred()) {
236 Py_XDECREF(v);
237 return NULL;
238 }
Skip Montanaro41cfce92007-08-24 21:11:00 +0000239
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000240 return v;
Skip Montanaro41cfce92007-08-24 21:11:00 +0000241}
242
243static PyObject *
Brett Cannon298c3802004-06-19 20:48:43 +0000244time_convert(double when, struct tm * (*function)(const time_t *))
Guido van Rossum234f9421993-06-17 12:35:49 +0000245{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000246 struct tm *p;
247 time_t whent = _PyTime_DoubleToTimet(when);
Brett Cannon298c3802004-06-19 20:48:43 +0000248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000249 if (whent == (time_t)-1 && PyErr_Occurred())
250 return NULL;
251 errno = 0;
252 p = function(&whent);
253 if (p == NULL) {
Guido van Rossum6e8583d1996-10-08 14:19:52 +0000254#ifdef EINVAL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000255 if (errno == 0)
256 errno = EINVAL;
Guido van Rossum6e8583d1996-10-08 14:19:52 +0000257#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000258 return PyErr_SetFromErrno(PyExc_ValueError);
259 }
260 return tmtotuple(p);
Guido van Rossum234f9421993-06-17 12:35:49 +0000261}
262
Fred Drakef901abd2004-08-03 17:58:55 +0000263/* Parse arg tuple that can contain an optional float-or-None value;
264 format needs to be "|O:name".
265 Returns non-zero on success (parallels PyArg_ParseTuple).
266*/
267static int
268parse_time_double_args(PyObject *args, char *format, double *pwhen)
269{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000270 PyObject *ot = NULL;
Fred Drakef901abd2004-08-03 17:58:55 +0000271
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000272 if (!PyArg_ParseTuple(args, format, &ot))
273 return 0;
274 if (ot == NULL || ot == Py_None)
275 *pwhen = floattime();
276 else {
277 double when = PyFloat_AsDouble(ot);
278 if (PyErr_Occurred())
279 return 0;
280 *pwhen = when;
281 }
282 return 1;
Fred Drakef901abd2004-08-03 17:58:55 +0000283}
284
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000285static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000286time_gmtime(PyObject *self, PyObject *args)
Guido van Rossum234f9421993-06-17 12:35:49 +0000287{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000288 double when;
289 if (!parse_time_double_args(args, "|O:gmtime", &when))
290 return NULL;
291 return time_convert(when, gmtime);
Guido van Rossum234f9421993-06-17 12:35:49 +0000292}
293
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000294PyDoc_STRVAR(gmtime_doc,
Christian Heimes9a371592007-12-28 14:08:13 +0000295"gmtime([seconds]) -> (tm_year, tm_mon, tm_mday, tm_hour, tm_min,\n\
Fred Drake193a3f62002-03-12 21:38:49 +0000296 tm_sec, tm_wday, tm_yday, tm_isdst)\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000297\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000298Convert seconds since the Epoch to a time tuple expressing UTC (a.k.a.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000299GMT). When 'seconds' is not passed in, convert the current time instead.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000300
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000301static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000302time_localtime(PyObject *self, PyObject *args)
Guido van Rossum234f9421993-06-17 12:35:49 +0000303{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000304 double when;
305 if (!parse_time_double_args(args, "|O:localtime", &when))
306 return NULL;
307 return time_convert(when, localtime);
Guido van Rossum234f9421993-06-17 12:35:49 +0000308}
309
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000310PyDoc_STRVAR(localtime_doc,
Christian Heimes9a371592007-12-28 14:08:13 +0000311"localtime([seconds]) -> (tm_year,tm_mon,tm_mday,tm_hour,tm_min,\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000312 tm_sec,tm_wday,tm_yday,tm_isdst)\n\
Martin v. Löwisb3cfc1d2001-12-02 12:27:43 +0000313\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000314Convert seconds since the Epoch to a time tuple expressing local time.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000315When 'seconds' is not passed in, convert the current time instead.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000316
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000317/* Convert 9-item tuple to tm structure. Return 1 on success, set
318 * an exception and return 0 on error.
319 */
Guido van Rossum9e90a671993-06-24 11:10:19 +0000320static int
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000321gettmarg(PyObject *args, struct tm *p)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000322{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000323 int y;
324 PyObject *t = NULL;
Guido van Rossumcfbaecc1998-08-25 14:51:12 +0000325
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000326 memset((void *) p, '\0', sizeof(struct tm));
Guido van Rossumb9081262007-08-25 03:14:09 +0000327
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000328 if (PyTuple_Check(args)) {
329 t = args;
330 Py_INCREF(t);
331 }
332 else if (Py_TYPE(args) == &StructTimeType) {
333 t = structtime_totuple(args);
334 }
335 else {
336 PyErr_SetString(PyExc_TypeError,
337 "Tuple or struct_time argument required");
338 return 0;
339 }
Skip Montanaro41cfce92007-08-24 21:11:00 +0000340
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000341 if (t == NULL || !PyArg_ParseTuple(t, "iiiiiiiii",
342 &y,
343 &p->tm_mon,
344 &p->tm_mday,
345 &p->tm_hour,
346 &p->tm_min,
347 &p->tm_sec,
348 &p->tm_wday,
349 &p->tm_yday,
350 &p->tm_isdst)) {
351 Py_XDECREF(t);
352 return 0;
353 }
354 Py_DECREF(t);
Skip Montanaro41cfce92007-08-24 21:11:00 +0000355
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000356 if (y < 1900) {
357 PyObject *accept = PyDict_GetItemString(moddict,
358 "accept2dyear");
359 if (accept == NULL || !PyLong_CheckExact(accept) ||
360 !PyObject_IsTrue(accept)) {
361 PyErr_SetString(PyExc_ValueError,
362 "year >= 1900 required");
363 return 0;
364 }
365 if (69 <= y && y <= 99)
366 y += 1900;
367 else if (0 <= y && y <= 68)
368 y += 2000;
369 else {
370 PyErr_SetString(PyExc_ValueError,
371 "year out of range");
372 return 0;
373 }
374 }
375 p->tm_year = y - 1900;
376 p->tm_mon--;
377 p->tm_wday = (p->tm_wday + 1) % 7;
378 p->tm_yday--;
379 return 1;
Guido van Rossum9e90a671993-06-24 11:10:19 +0000380}
381
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000382/* Check values of the struct tm fields before it is passed to strftime() and
383 * asctime(). Return 1 if all values are valid, otherwise set an exception
384 * and returns 0.
385 */
Victor Stinneref128102010-10-07 01:00:52 +0000386static int
387checktm(struct tm* buf)
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000388{
Victor Stinneref128102010-10-07 01:00:52 +0000389 /* Checks added to make sure strftime() and asctime() does not crash Python by
390 indexing blindly into some array for a textual representation
391 by some bad index (fixes bug #897625 and #6608).
392
393 Also support values of zero from Python code for arguments in which
394 that is out of range by forcing that value to the lowest value that
395 is valid (fixed bug #1520914).
396
397 Valid ranges based on what is allowed in struct tm:
398
399 - tm_year: [0, max(int)] (1)
400 - tm_mon: [0, 11] (2)
401 - tm_mday: [1, 31]
402 - tm_hour: [0, 23]
403 - tm_min: [0, 59]
404 - tm_sec: [0, 60]
405 - tm_wday: [0, 6] (1)
406 - tm_yday: [0, 365] (2)
407 - tm_isdst: [-max(int), max(int)]
408
409 (1) gettmarg() handles bounds-checking.
410 (2) Python's acceptable range is one greater than the range in C,
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000411 thus need to check against automatic decrement by gettmarg().
412 */
413 if (buf->tm_mon == -1)
414 buf->tm_mon = 0;
415 else if (buf->tm_mon < 0 || buf->tm_mon > 11) {
416 PyErr_SetString(PyExc_ValueError, "month out of range");
417 return 0;
418 }
419 if (buf->tm_mday == 0)
420 buf->tm_mday = 1;
421 else if (buf->tm_mday < 0 || buf->tm_mday > 31) {
422 PyErr_SetString(PyExc_ValueError, "day of month out of range");
423 return 0;
424 }
425 if (buf->tm_hour < 0 || buf->tm_hour > 23) {
426 PyErr_SetString(PyExc_ValueError, "hour out of range");
427 return 0;
428 }
429 if (buf->tm_min < 0 || buf->tm_min > 59) {
430 PyErr_SetString(PyExc_ValueError, "minute out of range");
431 return 0;
432 }
433 if (buf->tm_sec < 0 || buf->tm_sec > 61) {
434 PyErr_SetString(PyExc_ValueError, "seconds out of range");
435 return 0;
436 }
437 /* tm_wday does not need checking of its upper-bound since taking
438 ``% 7`` in gettmarg() automatically restricts the range. */
439 if (buf->tm_wday < 0) {
440 PyErr_SetString(PyExc_ValueError, "day of week out of range");
441 return 0;
442 }
443 if (buf->tm_yday == -1)
444 buf->tm_yday = 0;
445 else if (buf->tm_yday < 0 || buf->tm_yday > 365) {
446 PyErr_SetString(PyExc_ValueError, "day of year out of range");
447 return 0;
448 }
449 return 1;
450}
451
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000452#ifdef HAVE_STRFTIME
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000453#ifdef HAVE_WCSFTIME
454#define time_char wchar_t
455#define format_time wcsftime
456#define time_strlen wcslen
457#else
458#define time_char char
459#define format_time strftime
460#define time_strlen strlen
461#endif
462
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000463static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000464time_strftime(PyObject *self, PyObject *args)
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000465{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000466 PyObject *tup = NULL;
467 struct tm buf;
468 const time_char *fmt;
Victor Stinnerb2904782010-09-29 10:34:19 +0000469#ifdef HAVE_WCSFTIME
470 wchar_t *format;
471#else
472 PyObject *format;
473#endif
Victor Stinneref128102010-10-07 01:00:52 +0000474 PyObject *format_arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000475 size_t fmtlen, buflen;
Victor Stinnerb2904782010-09-29 10:34:19 +0000476 time_char *outbuf = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000477 size_t i;
Victor Stinnerb2904782010-09-29 10:34:19 +0000478 PyObject *ret = NULL;
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000479
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000480 memset((void *) &buf, '\0', sizeof(buf));
Guido van Rossum1f41f841998-04-27 19:04:26 +0000481
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000482 /* Will always expect a unicode string to be passed as format.
483 Given that there's no str type anymore in py3k this seems safe.
484 */
Victor Stinneref128102010-10-07 01:00:52 +0000485 if (!PyArg_ParseTuple(args, "U|O:strftime", &format_arg, &tup))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000486 return NULL;
Thomas Woutersfe385252001-01-19 23:16:56 +0000487
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000488 if (tup == NULL) {
489 time_t tt = time(NULL);
490 buf = *localtime(&tt);
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000491 }
492 else if (!gettmarg(tup, &buf) || !checktm(&buf))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000493 return NULL;
Guido van Rossum10b164a2001-09-25 13:59:01 +0000494
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000495 /* Normalize tm_isdst just in case someone foolishly implements %Z
496 based on the assumption that tm_isdst falls within the range of
497 [-1, 1] */
498 if (buf.tm_isdst < -1)
499 buf.tm_isdst = -1;
500 else if (buf.tm_isdst > 1)
501 buf.tm_isdst = 1;
Brett Cannond1080a32004-03-02 04:38:10 +0000502
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000503#ifdef HAVE_WCSFTIME
Victor Stinnerbeb4135b2010-10-07 01:02:42 +0000504 format = PyUnicode_AsWideCharString(format_arg, NULL);
Victor Stinnerb2904782010-09-29 10:34:19 +0000505 if (format == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000506 return NULL;
Victor Stinnerb2904782010-09-29 10:34:19 +0000507 fmt = format;
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000508#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000509 /* Convert the unicode string to an ascii one */
Victor Stinneref128102010-10-07 01:00:52 +0000510 format = PyUnicode_AsEncodedString(format_arg, TZNAME_ENCODING, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000511 if (format == NULL)
512 return NULL;
513 fmt = PyBytes_AS_STRING(format);
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000514#endif
Amaury Forgeot d'Arcb5be6d42009-03-02 23:52:57 +0000515
Hirokazu Yamamoto6b0e51a2009-06-03 05:19:18 +0000516#if defined(MS_WINDOWS) && defined(HAVE_WCSFTIME)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000517 /* check that the format string contains only valid directives */
518 for(outbuf = wcschr(fmt, L'%');
519 outbuf != NULL;
520 outbuf = wcschr(outbuf+2, L'%'))
521 {
522 if (outbuf[1]=='#')
523 ++outbuf; /* not documented by python, */
524 if (outbuf[1]=='\0' ||
525 !wcschr(L"aAbBcdfHIjmMpSUwWxXyYzZ%", outbuf[1]))
526 {
527 PyErr_SetString(PyExc_ValueError, "Invalid format string");
528 return 0;
529 }
530 }
Amaury Forgeot d'Arcb5be6d42009-03-02 23:52:57 +0000531#endif
532
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000533 fmtlen = time_strlen(fmt);
Guido van Rossumc222ec21999-02-23 00:00:10 +0000534
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000535 /* I hate these functions that presume you know how big the output
536 * will be ahead of time...
537 */
538 for (i = 1024; ; i += i) {
539 outbuf = (time_char *)PyMem_Malloc(i*sizeof(time_char));
540 if (outbuf == NULL) {
Victor Stinnerb2904782010-09-29 10:34:19 +0000541 PyErr_NoMemory();
542 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000543 }
544 buflen = format_time(outbuf, i, fmt, &buf);
545 if (buflen > 0 || i >= 256 * fmtlen) {
546 /* If the buffer is 256 times as long as the format,
547 it's probably not failing for lack of room!
548 More likely, the format yields an empty result,
549 e.g. an empty format, or %Z when the timezone
550 is unknown. */
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000551#ifdef HAVE_WCSFTIME
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000552 ret = PyUnicode_FromWideChar(outbuf, buflen);
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000553#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000554 ret = PyUnicode_Decode(outbuf, buflen,
555 TZNAME_ENCODING, NULL);
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000556#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000557 PyMem_Free(outbuf);
Victor Stinnerb2904782010-09-29 10:34:19 +0000558 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000559 }
560 PyMem_Free(outbuf);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000561#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000562 /* VisualStudio .NET 2005 does this properly */
563 if (buflen == 0 && errno == EINVAL) {
564 PyErr_SetString(PyExc_ValueError, "Invalid format string");
Victor Stinnerb2904782010-09-29 10:34:19 +0000565 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000566 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000567#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000568 }
Victor Stinnerb2904782010-09-29 10:34:19 +0000569#ifdef HAVE_WCSFTIME
570 PyMem_Free(format);
571#else
572 Py_DECREF(format);
573#endif
574 return ret;
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000575}
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000576
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000577#undef time_char
578#undef format_time
579
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000580PyDoc_STRVAR(strftime_doc,
Thomas Woutersfe385252001-01-19 23:16:56 +0000581"strftime(format[, tuple]) -> string\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000582\n\
583Convert a time tuple to a string according to a format specification.\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000584See the library reference manual for formatting codes. When the time tuple\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000585is not present, current time as returned by localtime() is used.");
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000586#endif /* HAVE_STRFTIME */
587
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000588static PyObject *
589time_strptime(PyObject *self, PyObject *args)
590{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000591 PyObject *strptime_module = PyImport_ImportModuleNoBlock("_strptime");
592 PyObject *strptime_result;
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000593
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000594 if (!strptime_module)
595 return NULL;
596 strptime_result = PyObject_CallMethod(strptime_module,
597 "_strptime_time", "O", args);
598 Py_DECREF(strptime_module);
599 return strptime_result;
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000600}
601
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000602PyDoc_STRVAR(strptime_doc,
Brett Cannon20def8b2003-07-01 05:16:08 +0000603"strptime(string, format) -> struct_time\n\
Martin v. Löwisb3cfc1d2001-12-02 12:27:43 +0000604\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000605Parse a string to a time tuple according to a format specification.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000606See the library reference manual for formatting codes (same as strftime()).");
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000607
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000608
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000609static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000610time_asctime(PyObject *self, PyObject *args)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000611{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000612 PyObject *tup = NULL;
613 struct tm buf;
614 char *p;
615 if (!PyArg_UnpackTuple(args, "asctime", 0, 1, &tup))
616 return NULL;
617 if (tup == NULL) {
618 time_t tt = time(NULL);
619 buf = *localtime(&tt);
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000620 } else if (!gettmarg(tup, &buf) || !checktm(&buf))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000621 return NULL;
622 p = asctime(&buf);
623 if (p[24] == '\n')
624 p[24] = '\0';
625 return PyUnicode_FromString(p);
Guido van Rossum9e90a671993-06-24 11:10:19 +0000626}
627
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000628PyDoc_STRVAR(asctime_doc,
Thomas Woutersfe385252001-01-19 23:16:56 +0000629"asctime([tuple]) -> string\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000630\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000631Convert a time tuple to a string, e.g. 'Sat Jun 06 16:26:11 1998'.\n\
632When the time tuple is not present, current time as returned by localtime()\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000633is used.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000634
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000635static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000636time_ctime(PyObject *self, PyObject *args)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000637{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000638 PyObject *ot = NULL;
639 time_t tt;
640 char *p;
Guido van Rossum10b164a2001-09-25 13:59:01 +0000641
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000642 if (!PyArg_UnpackTuple(args, "ctime", 0, 1, &ot))
643 return NULL;
644 if (ot == NULL || ot == Py_None)
645 tt = time(NULL);
646 else {
647 double dt = PyFloat_AsDouble(ot);
648 if (PyErr_Occurred())
649 return NULL;
650 tt = _PyTime_DoubleToTimet(dt);
651 if (tt == (time_t)-1 && PyErr_Occurred())
652 return NULL;
653 }
654 p = ctime(&tt);
655 if (p == NULL) {
656 PyErr_SetString(PyExc_ValueError, "unconvertible time");
657 return NULL;
658 }
659 if (p[24] == '\n')
660 p[24] = '\0';
661 return PyUnicode_FromString(p);
Guido van Rossum9e90a671993-06-24 11:10:19 +0000662}
663
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000664PyDoc_STRVAR(ctime_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000665"ctime(seconds) -> string\n\
666\n\
667Convert a time in seconds since the Epoch to a string in local time.\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000668This is equivalent to asctime(localtime(seconds)). When the time tuple is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000669not present, current time as returned by localtime() is used.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000670
Guido van Rossum60cd8131998-03-06 17:16:21 +0000671#ifdef HAVE_MKTIME
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000672static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000673time_mktime(PyObject *self, PyObject *tup)
Guido van Rossum234f9421993-06-17 12:35:49 +0000674{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000675 struct tm buf;
676 time_t tt;
677 if (!gettmarg(tup, &buf))
678 return NULL;
679 tt = mktime(&buf);
680 if (tt == (time_t)(-1)) {
681 PyErr_SetString(PyExc_OverflowError,
682 "mktime argument out of range");
683 return NULL;
684 }
685 return PyFloat_FromDouble((double)tt);
Guido van Rossum234f9421993-06-17 12:35:49 +0000686}
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000687
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000688PyDoc_STRVAR(mktime_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000689"mktime(tuple) -> floating point number\n\
690\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000691Convert a time tuple in local time to seconds since the Epoch.");
Guido van Rossum60cd8131998-03-06 17:16:21 +0000692#endif /* HAVE_MKTIME */
Guido van Rossum234f9421993-06-17 12:35:49 +0000693
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000694#ifdef HAVE_WORKING_TZSET
Martin v. Löwis1a214512008-06-11 05:26:20 +0000695static void PyInit_timezone(PyObject *module);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000696
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000697static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000698time_tzset(PyObject *self, PyObject *unused)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000699{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000700 PyObject* m;
Fred Drake9bb74322002-04-01 14:49:59 +0000701
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000702 m = PyImport_ImportModuleNoBlock("time");
703 if (m == NULL) {
704 return NULL;
705 }
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000706
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000707 tzset();
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000708
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000709 /* Reset timezone, altzone, daylight and tzname */
710 PyInit_timezone(m);
711 Py_DECREF(m);
Tim Peters1b6f7a92004-06-20 02:50:16 +0000712
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000713 Py_INCREF(Py_None);
714 return Py_None;
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000715}
716
717PyDoc_STRVAR(tzset_doc,
718"tzset(zone)\n\
719\n\
720Initialize, or reinitialize, the local timezone to the value stored in\n\
721os.environ['TZ']. The TZ environment variable should be specified in\n\
Neal Norwitzdc8e1942004-07-20 22:34:37 +0000722standard Unix timezone format as documented in the tzset man page\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000723(eg. 'US/Eastern', 'Europe/Amsterdam'). Unknown timezones will silently\n\
724fall back to UTC. If the TZ environment variable is not set, the local\n\
725timezone is set to the systems best guess of wallclock time.\n\
726Changing the TZ environment variable without calling tzset *may* change\n\
727the local timezone used by methods such as localtime, but this behaviour\n\
728should not be relied on.");
729#endif /* HAVE_WORKING_TZSET */
730
Martin v. Löwisd218dc12008-04-07 03:17:54 +0000731static void
Martin v. Löwis1a214512008-06-11 05:26:20 +0000732PyInit_timezone(PyObject *m) {
733 /* This code moved from PyInit_time wholesale to allow calling it from
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000734 time_tzset. In the future, some parts of it can be moved back
735 (for platforms that don't HAVE_WORKING_TZSET, when we know what they
736 are), and the extraneous calls to tzset(3) should be removed.
737 I haven't done this yet, as I don't want to change this code as
738 little as possible when introducing the time.tzset and time.tzsetwall
739 methods. This should simply be a method of doing the following once,
740 at the top of this function and removing the call to tzset() from
741 time_tzset():
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000742
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000743 #ifdef HAVE_TZSET
744 tzset()
745 #endif
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000746
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000747 And I'm lazy and hate C so nyer.
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000748 */
Guido van Rossum10b164a2001-09-25 13:59:01 +0000749#if defined(HAVE_TZNAME) && !defined(__GLIBC__) && !defined(__CYGWIN__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000750 PyObject *otz0, *otz1;
751 tzset();
Guido van Rossum26452411998-09-28 22:07:11 +0000752#ifdef PYOS_OS2
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000753 PyModule_AddIntConstant(m, "timezone", _timezone);
Guido van Rossum26452411998-09-28 22:07:11 +0000754#else /* !PYOS_OS2 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000755 PyModule_AddIntConstant(m, "timezone", timezone);
Guido van Rossum26452411998-09-28 22:07:11 +0000756#endif /* PYOS_OS2 */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000757#ifdef HAVE_ALTZONE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000758 PyModule_AddIntConstant(m, "altzone", altzone);
Guido van Rossumb6775db1994-08-01 11:34:53 +0000759#else
Guido van Rossum26452411998-09-28 22:07:11 +0000760#ifdef PYOS_OS2
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000761 PyModule_AddIntConstant(m, "altzone", _timezone-3600);
Guido van Rossum26452411998-09-28 22:07:11 +0000762#else /* !PYOS_OS2 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000763 PyModule_AddIntConstant(m, "altzone", timezone-3600);
Guido van Rossum26452411998-09-28 22:07:11 +0000764#endif /* PYOS_OS2 */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000765#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000766 PyModule_AddIntConstant(m, "daylight", daylight);
767 otz0 = PyUnicode_Decode(tzname[0], strlen(tzname[0]), TZNAME_ENCODING, NULL);
768 otz1 = PyUnicode_Decode(tzname[1], strlen(tzname[1]), TZNAME_ENCODING, NULL);
769 PyModule_AddObject(m, "tzname", Py_BuildValue("(NN)", otz0, otz1));
Guido van Rossum10b164a2001-09-25 13:59:01 +0000770#else /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/
Martin v. Löwis60a5d722002-10-16 20:28:25 +0000771#ifdef HAVE_STRUCT_TM_TM_ZONE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000772 {
Guido van Rossum234f9421993-06-17 12:35:49 +0000773#define YEAR ((time_t)((365 * 24 + 6) * 3600))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000774 time_t t;
775 struct tm *p;
776 long janzone, julyzone;
777 char janname[10], julyname[10];
778 t = (time((time_t *)0) / YEAR) * YEAR;
779 p = localtime(&t);
780 janzone = -p->tm_gmtoff;
781 strncpy(janname, p->tm_zone ? p->tm_zone : " ", 9);
782 janname[9] = '\0';
783 t += YEAR/2;
784 p = localtime(&t);
785 julyzone = -p->tm_gmtoff;
786 strncpy(julyname, p->tm_zone ? p->tm_zone : " ", 9);
787 julyname[9] = '\0';
Guido van Rossum10b164a2001-09-25 13:59:01 +0000788
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000789 if( janzone < julyzone ) {
790 /* DST is reversed in the southern hemisphere */
791 PyModule_AddIntConstant(m, "timezone", julyzone);
792 PyModule_AddIntConstant(m, "altzone", janzone);
793 PyModule_AddIntConstant(m, "daylight",
794 janzone != julyzone);
795 PyModule_AddObject(m, "tzname",
796 Py_BuildValue("(zz)",
797 julyname, janname));
798 } else {
799 PyModule_AddIntConstant(m, "timezone", janzone);
800 PyModule_AddIntConstant(m, "altzone", julyzone);
801 PyModule_AddIntConstant(m, "daylight",
802 janzone != julyzone);
803 PyModule_AddObject(m, "tzname",
804 Py_BuildValue("(zz)",
805 janname, julyname));
806 }
807 }
Guido van Rossume6a4b7b1997-10-08 15:27:56 +0000808#else
Martin v. Löwis60a5d722002-10-16 20:28:25 +0000809#endif /* HAVE_STRUCT_TM_TM_ZONE */
Tim Peters26ae7cd2001-03-20 03:26:49 +0000810#ifdef __CYGWIN__
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000811 tzset();
812 PyModule_AddIntConstant(m, "timezone", _timezone);
813 PyModule_AddIntConstant(m, "altzone", _timezone-3600);
814 PyModule_AddIntConstant(m, "daylight", _daylight);
815 PyModule_AddObject(m, "tzname",
816 Py_BuildValue("(zz)", _tzname[0], _tzname[1]));
Tim Peters26ae7cd2001-03-20 03:26:49 +0000817#endif /* __CYGWIN__ */
Guido van Rossum10b164a2001-09-25 13:59:01 +0000818#endif /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000819}
820
821
822static PyMethodDef time_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000823 {"time", time_time, METH_NOARGS, time_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000824#ifdef HAVE_CLOCK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000825 {"clock", time_clock, METH_NOARGS, clock_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000826#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000827 {"sleep", time_sleep, METH_VARARGS, sleep_doc},
828 {"gmtime", time_gmtime, METH_VARARGS, gmtime_doc},
829 {"localtime", time_localtime, METH_VARARGS, localtime_doc},
830 {"asctime", time_asctime, METH_VARARGS, asctime_doc},
831 {"ctime", time_ctime, METH_VARARGS, ctime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000832#ifdef HAVE_MKTIME
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000833 {"mktime", time_mktime, METH_O, mktime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000834#endif
835#ifdef HAVE_STRFTIME
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000836 {"strftime", time_strftime, METH_VARARGS, strftime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000837#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000838 {"strptime", time_strptime, METH_VARARGS, strptime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000839#ifdef HAVE_WORKING_TZSET
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000840 {"tzset", time_tzset, METH_NOARGS, tzset_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000841#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000842 {NULL, NULL} /* sentinel */
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000843};
844
845
846PyDoc_STRVAR(module_doc,
847"This module provides various functions to manipulate time values.\n\
848\n\
849There are two standard representations of time. One is the number\n\
850of seconds since the Epoch, in UTC (a.k.a. GMT). It may be an integer\n\
851or a floating point number (to represent fractions of seconds).\n\
852The Epoch is system-defined; on Unix, it is generally January 1st, 1970.\n\
853The actual value can be retrieved by calling gmtime(0).\n\
854\n\
855The other representation is a tuple of 9 integers giving local time.\n\
856The tuple items are:\n\
857 year (four digits, e.g. 1998)\n\
858 month (1-12)\n\
859 day (1-31)\n\
860 hours (0-23)\n\
861 minutes (0-59)\n\
862 seconds (0-59)\n\
863 weekday (0-6, Monday is 0)\n\
864 Julian day (day in the year, 1-366)\n\
865 DST (Daylight Savings Time) flag (-1, 0 or 1)\n\
866If the DST flag is 0, the time is given in the regular time zone;\n\
867if it is 1, the time is given in the DST time zone;\n\
868if it is -1, mktime() should guess based on the date and time.\n\
869\n\
870Variables:\n\
871\n\
872timezone -- difference in seconds between UTC and local standard time\n\
873altzone -- difference in seconds between UTC and local DST time\n\
874daylight -- whether local time should reflect DST\n\
875tzname -- tuple of (standard time zone name, DST time zone name)\n\
876\n\
877Functions:\n\
878\n\
879time() -- return current time in seconds since the Epoch as a float\n\
880clock() -- return CPU time since process start as a float\n\
881sleep() -- delay for a number of seconds given as a float\n\
882gmtime() -- convert seconds since Epoch to UTC tuple\n\
883localtime() -- convert seconds since Epoch to local time tuple\n\
884asctime() -- convert time tuple to string\n\
885ctime() -- convert time in seconds to string\n\
886mktime() -- convert local time tuple to seconds since Epoch\n\
887strftime() -- convert time tuple to string according to format specification\n\
888strptime() -- parse string to time tuple according to format specification\n\
889tzset() -- change the local timezone");
890
891
Martin v. Löwis1a214512008-06-11 05:26:20 +0000892
893static struct PyModuleDef timemodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000894 PyModuleDef_HEAD_INIT,
895 "time",
896 module_doc,
897 -1,
898 time_methods,
899 NULL,
900 NULL,
901 NULL,
902 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +0000903};
904
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000905PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +0000906PyInit_time(void)
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000907{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000908 PyObject *m;
909 char *p;
910 m = PyModule_Create(&timemodule);
911 if (m == NULL)
912 return NULL;
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000913
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000914 /* Accept 2-digit dates unless PYTHONY2K is set and non-empty */
915 p = Py_GETENV("PYTHONY2K");
916 PyModule_AddIntConstant(m, "accept2dyear", (long) (!p || !*p));
917 /* Squirrel away the module's dictionary for the y2k check */
918 moddict = PyModule_GetDict(m);
919 Py_INCREF(moddict);
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000920
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000921 /* Set, or reset, module variables like time.timezone */
922 PyInit_timezone(m);
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000923
Mark Hammond975e3922002-07-16 01:29:19 +0000924#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000925 /* Helper to allow interrupts for Windows.
926 If Ctrl+C event delivered while not sleeping
927 it will be ignored.
928 */
929 main_thread = PyThread_get_thread_ident();
930 hInterruptEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
931 SetConsoleCtrlHandler( PyCtrlHandler, TRUE);
Mark Hammond975e3922002-07-16 01:29:19 +0000932#endif /* MS_WINDOWS */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000933 if (!initialized) {
934 PyStructSequence_InitType(&StructTimeType,
935 &struct_time_type_desc);
936 }
937 Py_INCREF(&StructTimeType);
938 PyModule_AddObject(m, "struct_time", (PyObject*) &StructTimeType);
939 initialized = 1;
940 return m;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000941}
942
Guido van Rossumb6775db1994-08-01 11:34:53 +0000943static double
Thomas Woutersf3f33dc2000-07-21 06:00:07 +0000944floattime(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000945{
Alexander Belopolsky6fc4ade2010-08-05 17:34:27 +0000946 _PyTime_timeval t;
947 _PyTime_gettimeofday(&t);
948 return (double)t.tv_sec + t.tv_usec*0.000001;
Guido van Rossum426035c1991-02-19 12:27:35 +0000949}
950
Guido van Rossumb6775db1994-08-01 11:34:53 +0000951
952/* Implement floatsleep() for various platforms.
953 When interrupted (or when another error occurs), return -1 and
954 set an exception; else return 0. */
955
956static int
Guido van Rossuma320fd31995-03-09 12:14:15 +0000957floatsleep(double secs)
Guido van Rossum426035c1991-02-19 12:27:35 +0000958{
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000959/* XXX Should test for MS_WINDOWS first! */
Skip Montanaroeb33e5a2007-08-17 12:57:41 +0000960#if defined(HAVE_SELECT) && !defined(__EMX__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000961 struct timeval t;
962 double frac;
963 frac = fmod(secs, 1.0);
964 secs = floor(secs);
965 t.tv_sec = (long)secs;
966 t.tv_usec = (long)(frac*1000000.0);
967 Py_BEGIN_ALLOW_THREADS
968 if (select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &t) != 0) {
Guido van Rossum09cbb011999-11-08 15:32:27 +0000969#ifdef EINTR
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000970 if (errno != EINTR) {
Guido van Rossum09cbb011999-11-08 15:32:27 +0000971#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000972 if (1) {
Guido van Rossum09cbb011999-11-08 15:32:27 +0000973#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000974 Py_BLOCK_THREADS
975 PyErr_SetFromErrno(PyExc_IOError);
976 return -1;
977 }
978 }
979 Py_END_ALLOW_THREADS
Martin v. Löwis02af9642002-01-16 11:04:06 +0000980#elif defined(__WATCOMC__) && !defined(__QNX__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000981 /* XXX Can't interrupt this sleep */
982 Py_BEGIN_ALLOW_THREADS
983 delay((int)(secs * 1000 + 0.5)); /* delay() uses milliseconds */
984 Py_END_ALLOW_THREADS
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000985#elif defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000986 {
987 double millisecs = secs * 1000.0;
988 unsigned long ul_millis;
Tim Peters513a1cd2003-01-19 04:54:58 +0000989
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000990 if (millisecs > (double)ULONG_MAX) {
991 PyErr_SetString(PyExc_OverflowError,
992 "sleep length is too large");
993 return -1;
994 }
995 Py_BEGIN_ALLOW_THREADS
996 /* Allow sleep(0) to maintain win32 semantics, and as decreed
997 * by Guido, only the main thread can be interrupted.
998 */
999 ul_millis = (unsigned long)millisecs;
1000 if (ul_millis == 0 ||
1001 main_thread != PyThread_get_thread_ident())
1002 Sleep(ul_millis);
1003 else {
1004 DWORD rc;
1005 ResetEvent(hInterruptEvent);
1006 rc = WaitForSingleObject(hInterruptEvent, ul_millis);
1007 if (rc == WAIT_OBJECT_0) {
1008 /* Yield to make sure real Python signal
1009 * handler called.
1010 */
1011 Sleep(1);
1012 Py_BLOCK_THREADS
1013 errno = EINTR;
1014 PyErr_SetFromErrno(PyExc_IOError);
1015 return -1;
1016 }
1017 }
1018 Py_END_ALLOW_THREADS
1019 }
Martin v. Löwis02af9642002-01-16 11:04:06 +00001020#elif defined(PYOS_OS2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001021 /* This Sleep *IS* Interruptable by Exceptions */
1022 Py_BEGIN_ALLOW_THREADS
1023 if (DosSleep(secs * 1000) != NO_ERROR) {
1024 Py_BLOCK_THREADS
1025 PyErr_SetFromErrno(PyExc_IOError);
1026 return -1;
1027 }
1028 Py_END_ALLOW_THREADS
Martin v. Löwis02af9642002-01-16 11:04:06 +00001029#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001030 /* XXX Can't interrupt this sleep */
1031 Py_BEGIN_ALLOW_THREADS
1032 sleep((int)secs);
1033 Py_END_ALLOW_THREADS
Martin v. Löwis02af9642002-01-16 11:04:06 +00001034#endif
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001035
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001036 return 0;
Guido van Rossum80c9d881991-04-16 08:47:51 +00001037}