blob: ebc2b814bc747e1f3d42f07d72005a6142bc90e0 [file] [log] [blame]
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001/* Time module */
2
Barry Warsaw9a2a8a81996-12-06 23:32:14 +00003#include "Python.h"
Alexander Belopolsky6fc4ade2010-08-05 17:34:27 +00004#include "_time.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +00005
Martin v. Löwis8a7c8662007-08-30 15:40:24 +00006#define TZNAME_ENCODING "utf-8"
7
Guido van Rossum87ce7bb1998-06-09 16:30:31 +00008#include <ctype.h>
9
Thomas Wouters0e3f5912006-08-11 14:57:12 +000010#ifdef HAVE_SYS_TYPES_H
Guido van Rossumb6775db1994-08-01 11:34:53 +000011#include <sys/types.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012#endif /* HAVE_SYS_TYPES_H */
Guido van Rossum6d946f91992-08-14 13:49:30 +000013
Guido van Rossumb6775db1994-08-01 11:34:53 +000014#ifdef QUICKWIN
15#include <io.h>
16#endif
17
Guido van Rossum7bf22de1997-12-02 20:34:19 +000018#if defined(__WATCOMC__) && !defined(__QNX__)
Guido van Rossumbceeac81996-05-23 22:53:47 +000019#include <i86.h>
20#else
Guido van Rossumcac6c721996-09-06 13:34:02 +000021#ifdef MS_WINDOWS
Mark Hammond975e3922002-07-16 01:29:19 +000022#define WIN32_LEAN_AND_MEAN
Guido van Rossum258ccd42001-03-02 06:53:29 +000023#include <windows.h>
Mark Hammond975e3922002-07-16 01:29:19 +000024#include "pythread.h"
25
26/* helper to allow us to interrupt sleep() on Windows*/
27static HANDLE hInterruptEvent = NULL;
28static BOOL WINAPI PyCtrlHandler(DWORD dwCtrlType)
29{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000030 SetEvent(hInterruptEvent);
31 /* allow other default handlers to be called.
32 Default Python handler will setup the
33 KeyboardInterrupt exception.
34 */
35 return FALSE;
Mark Hammond975e3922002-07-16 01:29:19 +000036}
37static long main_thread;
38
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000039#if defined(__BORLANDC__)
Guido van Rossumb2fb3641996-09-07 00:47:35 +000040/* These overrides not needed for Win32 */
Guido van Rossumb6775db1994-08-01 11:34:53 +000041#define timezone _timezone
Guido van Rossumcc081121995-03-14 15:05:41 +000042#define tzname _tzname
43#define daylight _daylight
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000044#endif /* __BORLANDC__ */
Guido van Rossumcac6c721996-09-06 13:34:02 +000045#endif /* MS_WINDOWS */
Guido van Rossum7bf22de1997-12-02 20:34:19 +000046#endif /* !__WATCOMC__ || __QNX__ */
Guido van Rossum234f9421993-06-17 12:35:49 +000047
Thomas Wouters477c8d52006-05-27 19:21:47 +000048#if defined(MS_WINDOWS) && !defined(__BORLANDC__)
49/* Win32 has better clock replacement; we have our own version below. */
50#undef HAVE_CLOCK
Martin v. Löwis3bb00702007-08-30 14:37:48 +000051#undef TZNAME_ENCODING
52#define TZNAME_ENCODING "mbcs"
Thomas Wouters477c8d52006-05-27 19:21:47 +000053#endif /* MS_WINDOWS && !defined(__BORLANDC__) */
Guido van Rossum3917c221997-04-02 05:35:28 +000054
Andrew MacIntyre7bf68332002-03-03 02:59:16 +000055#if defined(PYOS_OS2)
56#define INCL_DOS
57#define INCL_ERRORS
58#include <os2.h>
59#endif
60
Guido van Rossum8e9ebfd1997-11-22 21:53:48 +000061#if defined(PYCC_VACPP)
Guido van Rossum26452411998-09-28 22:07:11 +000062#include <sys/time.h>
Guido van Rossum8e9ebfd1997-11-22 21:53:48 +000063#endif
64
Guido van Rossum234f9421993-06-17 12:35:49 +000065/* Forward declarations */
Tim Petersdbd9ba62000-07-09 03:09:57 +000066static int floatsleep(double);
Thomas Woutersed77bac2000-07-24 15:26:39 +000067static double floattime(void);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000068
Guido van Rossumcfbaecc1998-08-25 14:51:12 +000069/* For Y2K check */
70static PyObject *moddict;
71
Barry Warsaw9a2a8a81996-12-06 23:32:14 +000072static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000073time_time(PyObject *self, PyObject *unused)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000074{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000075 double secs;
76 secs = floattime();
77 if (secs == 0.0) {
78 PyErr_SetFromErrno(PyExc_IOError);
79 return NULL;
80 }
81 return PyFloat_FromDouble(secs);
Guido van Rossumb6775db1994-08-01 11:34:53 +000082}
83
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000084PyDoc_STRVAR(time_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +000085"time() -> floating point number\n\
86\n\
87Return the current time in seconds since the Epoch.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000088Fractions of a second may be present if the system clock provides them.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +000089
Guido van Rossumb6775db1994-08-01 11:34:53 +000090#ifdef HAVE_CLOCK
91
92#ifndef CLOCKS_PER_SEC
Guido van Rossum1b66a4f1996-02-25 04:50:33 +000093#ifdef CLK_TCK
94#define CLOCKS_PER_SEC CLK_TCK
95#else
Guido van Rossumb6775db1994-08-01 11:34:53 +000096#define CLOCKS_PER_SEC 1000000
97#endif
Guido van Rossum1b66a4f1996-02-25 04:50:33 +000098#endif
Guido van Rossumb6775db1994-08-01 11:34:53 +000099
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000100static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000101time_clock(PyObject *self, PyObject *unused)
Guido van Rossumb6775db1994-08-01 11:34:53 +0000102{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000103 return PyFloat_FromDouble(((double)clock()) / CLOCKS_PER_SEC);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000104}
Guido van Rossumb6775db1994-08-01 11:34:53 +0000105#endif /* HAVE_CLOCK */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000106
Thomas Wouters477c8d52006-05-27 19:21:47 +0000107#if defined(MS_WINDOWS) && !defined(__BORLANDC__)
Mark Hammond7ba5e812002-02-12 04:02:33 +0000108/* Due to Mark Hammond and Tim Peters */
Guido van Rossum3917c221997-04-02 05:35:28 +0000109static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000110time_clock(PyObject *self, PyObject *unused)
Guido van Rossum3917c221997-04-02 05:35:28 +0000111{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000112 static LARGE_INTEGER ctrStart;
113 static double divisor = 0.0;
114 LARGE_INTEGER now;
115 double diff;
Guido van Rossum3917c221997-04-02 05:35:28 +0000116
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000117 if (divisor == 0.0) {
118 LARGE_INTEGER freq;
119 QueryPerformanceCounter(&ctrStart);
120 if (!QueryPerformanceFrequency(&freq) || freq.QuadPart == 0) {
121 /* Unlikely to happen - this works on all intel
122 machines at least! Revert to clock() */
123 return PyFloat_FromDouble(((double)clock()) /
124 CLOCKS_PER_SEC);
125 }
126 divisor = (double)freq.QuadPart;
127 }
128 QueryPerformanceCounter(&now);
129 diff = (double)(now.QuadPart - ctrStart.QuadPart);
130 return PyFloat_FromDouble(diff / divisor);
Guido van Rossum3917c221997-04-02 05:35:28 +0000131}
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000132
Guido van Rossum3917c221997-04-02 05:35:28 +0000133#define HAVE_CLOCK /* So it gets included in the methods */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000134#endif /* MS_WINDOWS && !defined(__BORLANDC__) */
Guido van Rossum3917c221997-04-02 05:35:28 +0000135
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000136#ifdef HAVE_CLOCK
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000137PyDoc_STRVAR(clock_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000138"clock() -> floating point number\n\
139\n\
140Return the CPU time or real time since the start of the process or since\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000141the first call to clock(). This has as much precision as the system\n\
142records.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000143#endif
144
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000145static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000146time_sleep(PyObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000147{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000148 double secs;
149 if (!PyArg_ParseTuple(args, "d:sleep", &secs))
150 return NULL;
151 if (floatsleep(secs) != 0)
152 return NULL;
153 Py_INCREF(Py_None);
154 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000155}
156
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000157PyDoc_STRVAR(sleep_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000158"sleep(seconds)\n\
159\n\
160Delay execution for a given number of seconds. The argument may be\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000161a floating point number for subsecond precision.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000162
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000163static PyStructSequence_Field struct_time_type_fields[] = {
Alexander Belopolsky69f3fd02010-06-05 15:04:51 +0000164 {"tm_year", "year, for example, 1993"},
165 {"tm_mon", "month of year, range [1, 12]"},
166 {"tm_mday", "day of month, range [1, 31]"},
167 {"tm_hour", "hours, range [0, 23]"},
168 {"tm_min", "minutes, range [0, 59]"},
169 {"tm_sec", "seconds, range [0, 61])"},
170 {"tm_wday", "day of week, range [0, 6], Monday is 0"},
171 {"tm_yday", "day of year, range [1, 366]"},
172 {"tm_isdst", "1 if summer time is in effect, 0 if not, and -1 if unknown"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000173 {0}
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000174};
175
176static PyStructSequence_Desc struct_time_type_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000177 "time.struct_time",
Alexander Belopolsky69f3fd02010-06-05 15:04:51 +0000178 "The time value as returned by gmtime(), localtime(), and strptime(), and\n"
179 " accepted by asctime(), mktime() and strftime(). May be considered as a\n"
180 " sequence of 9 integers.\n\n"
181 " Note that several fields' values are not the same as those defined by\n"
182 " the C language standard for struct tm. For example, the value of the\n"
183 " field tm_year is the actual year, not year - 1900. See individual\n"
184 " fields' descriptions for details.",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000185 struct_time_type_fields,
186 9,
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000187};
Tim Peters9ad4b682002-02-13 05:14:18 +0000188
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000189static int initialized;
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000190static PyTypeObject StructTimeType;
191
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000192static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000193tmtotuple(struct tm *p)
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000194{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000195 PyObject *v = PyStructSequence_New(&StructTimeType);
196 if (v == NULL)
197 return NULL;
Tim Peters9ad4b682002-02-13 05:14:18 +0000198
Christian Heimes217cfd12007-12-02 14:31:20 +0000199#define SET(i,val) PyStructSequence_SET_ITEM(v, i, PyLong_FromLong((long) val))
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000200
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000201 SET(0, p->tm_year + 1900);
202 SET(1, p->tm_mon + 1); /* Want January == 1 */
203 SET(2, p->tm_mday);
204 SET(3, p->tm_hour);
205 SET(4, p->tm_min);
206 SET(5, p->tm_sec);
207 SET(6, (p->tm_wday + 6) % 7); /* Want Monday == 0 */
208 SET(7, p->tm_yday + 1); /* Want January, 1 == 1 */
209 SET(8, p->tm_isdst);
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000210#undef SET
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000211 if (PyErr_Occurred()) {
212 Py_XDECREF(v);
213 return NULL;
214 }
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000215
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000216 return v;
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000217}
218
219static PyObject *
Skip Montanaro41cfce92007-08-24 21:11:00 +0000220structtime_totuple(PyObject *t)
221{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000222 PyObject *x = NULL;
223 unsigned int i;
224 PyObject *v = PyTuple_New(9);
225 if (v == NULL)
226 return NULL;
Skip Montanaro41cfce92007-08-24 21:11:00 +0000227
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000228 for (i=0; i<9; i++) {
229 x = PyStructSequence_GET_ITEM(t, i);
230 Py_INCREF(x);
231 PyTuple_SET_ITEM(v, i, x);
232 }
Skip Montanaro41cfce92007-08-24 21:11:00 +0000233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000234 if (PyErr_Occurred()) {
235 Py_XDECREF(v);
236 return NULL;
237 }
Skip Montanaro41cfce92007-08-24 21:11:00 +0000238
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000239 return v;
Skip Montanaro41cfce92007-08-24 21:11:00 +0000240}
241
242static PyObject *
Brett Cannon298c3802004-06-19 20:48:43 +0000243time_convert(double when, struct tm * (*function)(const time_t *))
Guido van Rossum234f9421993-06-17 12:35:49 +0000244{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000245 struct tm *p;
246 time_t whent = _PyTime_DoubleToTimet(when);
Brett Cannon298c3802004-06-19 20:48:43 +0000247
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000248 if (whent == (time_t)-1 && PyErr_Occurred())
249 return NULL;
250 errno = 0;
251 p = function(&whent);
252 if (p == NULL) {
Guido van Rossum6e8583d1996-10-08 14:19:52 +0000253#ifdef EINVAL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000254 if (errno == 0)
255 errno = EINVAL;
Guido van Rossum6e8583d1996-10-08 14:19:52 +0000256#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000257 return PyErr_SetFromErrno(PyExc_ValueError);
258 }
259 return tmtotuple(p);
Guido van Rossum234f9421993-06-17 12:35:49 +0000260}
261
Fred Drakef901abd2004-08-03 17:58:55 +0000262/* Parse arg tuple that can contain an optional float-or-None value;
263 format needs to be "|O:name".
264 Returns non-zero on success (parallels PyArg_ParseTuple).
265*/
266static int
267parse_time_double_args(PyObject *args, char *format, double *pwhen)
268{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000269 PyObject *ot = NULL;
Fred Drakef901abd2004-08-03 17:58:55 +0000270
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000271 if (!PyArg_ParseTuple(args, format, &ot))
272 return 0;
273 if (ot == NULL || ot == Py_None)
274 *pwhen = floattime();
275 else {
276 double when = PyFloat_AsDouble(ot);
277 if (PyErr_Occurred())
278 return 0;
279 *pwhen = when;
280 }
281 return 1;
Fred Drakef901abd2004-08-03 17:58:55 +0000282}
283
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000284static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000285time_gmtime(PyObject *self, PyObject *args)
Guido van Rossum234f9421993-06-17 12:35:49 +0000286{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000287 double when;
288 if (!parse_time_double_args(args, "|O:gmtime", &when))
289 return NULL;
290 return time_convert(when, gmtime);
Guido van Rossum234f9421993-06-17 12:35:49 +0000291}
292
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000293PyDoc_STRVAR(gmtime_doc,
Christian Heimes9a371592007-12-28 14:08:13 +0000294"gmtime([seconds]) -> (tm_year, tm_mon, tm_mday, tm_hour, tm_min,\n\
Fred Drake193a3f62002-03-12 21:38:49 +0000295 tm_sec, tm_wday, tm_yday, tm_isdst)\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000296\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000297Convert seconds since the Epoch to a time tuple expressing UTC (a.k.a.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000298GMT). When 'seconds' is not passed in, convert the current time instead.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000299
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000300static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000301time_localtime(PyObject *self, PyObject *args)
Guido van Rossum234f9421993-06-17 12:35:49 +0000302{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000303 double when;
304 if (!parse_time_double_args(args, "|O:localtime", &when))
305 return NULL;
306 return time_convert(when, localtime);
Guido van Rossum234f9421993-06-17 12:35:49 +0000307}
308
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000309PyDoc_STRVAR(localtime_doc,
Christian Heimes9a371592007-12-28 14:08:13 +0000310"localtime([seconds]) -> (tm_year,tm_mon,tm_mday,tm_hour,tm_min,\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000311 tm_sec,tm_wday,tm_yday,tm_isdst)\n\
Martin v. Löwisb3cfc1d2001-12-02 12:27:43 +0000312\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000313Convert seconds since the Epoch to a time tuple expressing local time.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000314When 'seconds' is not passed in, convert the current time instead.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000315
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000316/* Convert 9-item tuple to tm structure. Return 1 on success, set
317 * an exception and return 0 on error.
318 */
Guido van Rossum9e90a671993-06-24 11:10:19 +0000319static int
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000320gettmarg(PyObject *args, struct tm *p)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000321{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000322 int y;
323 PyObject *t = NULL;
Guido van Rossumcfbaecc1998-08-25 14:51:12 +0000324
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000325 memset((void *) p, '\0', sizeof(struct tm));
Guido van Rossumb9081262007-08-25 03:14:09 +0000326
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000327 if (PyTuple_Check(args)) {
328 t = args;
329 Py_INCREF(t);
330 }
331 else if (Py_TYPE(args) == &StructTimeType) {
332 t = structtime_totuple(args);
333 }
334 else {
335 PyErr_SetString(PyExc_TypeError,
336 "Tuple or struct_time argument required");
337 return 0;
338 }
Skip Montanaro41cfce92007-08-24 21:11:00 +0000339
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000340 if (t == NULL || !PyArg_ParseTuple(t, "iiiiiiiii",
341 &y,
342 &p->tm_mon,
343 &p->tm_mday,
344 &p->tm_hour,
345 &p->tm_min,
346 &p->tm_sec,
347 &p->tm_wday,
348 &p->tm_yday,
349 &p->tm_isdst)) {
350 Py_XDECREF(t);
351 return 0;
352 }
353 Py_DECREF(t);
Skip Montanaro41cfce92007-08-24 21:11:00 +0000354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000355 if (y < 1900) {
356 PyObject *accept = PyDict_GetItemString(moddict,
357 "accept2dyear");
358 if (accept == NULL || !PyLong_CheckExact(accept) ||
359 !PyObject_IsTrue(accept)) {
360 PyErr_SetString(PyExc_ValueError,
361 "year >= 1900 required");
362 return 0;
363 }
364 if (69 <= y && y <= 99)
365 y += 1900;
366 else if (0 <= y && y <= 68)
367 y += 2000;
368 else {
369 PyErr_SetString(PyExc_ValueError,
370 "year out of range");
371 return 0;
372 }
373 }
374 p->tm_year = y - 1900;
375 p->tm_mon--;
376 p->tm_wday = (p->tm_wday + 1) % 7;
377 p->tm_yday--;
378 return 1;
Guido van Rossum9e90a671993-06-24 11:10:19 +0000379}
380
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000381/* Check values of the struct tm fields before it is passed to strftime() and
382 * asctime(). Return 1 if all values are valid, otherwise set an exception
383 * and returns 0.
384 */
Victor Stinneref128102010-10-07 01:00:52 +0000385static int
386checktm(struct tm* buf)
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000387{
Victor Stinneref128102010-10-07 01:00:52 +0000388 /* Checks added to make sure strftime() and asctime() does not crash Python by
389 indexing blindly into some array for a textual representation
390 by some bad index (fixes bug #897625 and #6608).
391
392 Also support values of zero from Python code for arguments in which
393 that is out of range by forcing that value to the lowest value that
394 is valid (fixed bug #1520914).
395
396 Valid ranges based on what is allowed in struct tm:
397
398 - tm_year: [0, max(int)] (1)
399 - tm_mon: [0, 11] (2)
400 - tm_mday: [1, 31]
401 - tm_hour: [0, 23]
402 - tm_min: [0, 59]
403 - tm_sec: [0, 60]
404 - tm_wday: [0, 6] (1)
405 - tm_yday: [0, 365] (2)
406 - tm_isdst: [-max(int), max(int)]
407
408 (1) gettmarg() handles bounds-checking.
409 (2) Python's acceptable range is one greater than the range in C,
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000410 thus need to check against automatic decrement by gettmarg().
411 */
412 if (buf->tm_mon == -1)
413 buf->tm_mon = 0;
414 else if (buf->tm_mon < 0 || buf->tm_mon > 11) {
415 PyErr_SetString(PyExc_ValueError, "month out of range");
416 return 0;
417 }
418 if (buf->tm_mday == 0)
419 buf->tm_mday = 1;
420 else if (buf->tm_mday < 0 || buf->tm_mday > 31) {
421 PyErr_SetString(PyExc_ValueError, "day of month out of range");
422 return 0;
423 }
424 if (buf->tm_hour < 0 || buf->tm_hour > 23) {
425 PyErr_SetString(PyExc_ValueError, "hour out of range");
426 return 0;
427 }
428 if (buf->tm_min < 0 || buf->tm_min > 59) {
429 PyErr_SetString(PyExc_ValueError, "minute out of range");
430 return 0;
431 }
432 if (buf->tm_sec < 0 || buf->tm_sec > 61) {
433 PyErr_SetString(PyExc_ValueError, "seconds out of range");
434 return 0;
435 }
436 /* tm_wday does not need checking of its upper-bound since taking
437 ``% 7`` in gettmarg() automatically restricts the range. */
438 if (buf->tm_wday < 0) {
439 PyErr_SetString(PyExc_ValueError, "day of week out of range");
440 return 0;
441 }
442 if (buf->tm_yday == -1)
443 buf->tm_yday = 0;
444 else if (buf->tm_yday < 0 || buf->tm_yday > 365) {
445 PyErr_SetString(PyExc_ValueError, "day of year out of range");
446 return 0;
447 }
448 return 1;
449}
450
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000451#ifdef HAVE_STRFTIME
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000452#ifdef HAVE_WCSFTIME
453#define time_char wchar_t
454#define format_time wcsftime
455#define time_strlen wcslen
456#else
457#define time_char char
458#define format_time strftime
459#define time_strlen strlen
460#endif
461
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000462static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000463time_strftime(PyObject *self, PyObject *args)
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000464{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000465 PyObject *tup = NULL;
466 struct tm buf;
467 const time_char *fmt;
Victor Stinnerb2904782010-09-29 10:34:19 +0000468#ifdef HAVE_WCSFTIME
469 wchar_t *format;
470#else
471 PyObject *format;
472#endif
Victor Stinneref128102010-10-07 01:00:52 +0000473 PyObject *format_arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000474 size_t fmtlen, buflen;
Victor Stinnerb2904782010-09-29 10:34:19 +0000475 time_char *outbuf = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000476 size_t i;
Victor Stinnerb2904782010-09-29 10:34:19 +0000477 PyObject *ret = NULL;
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000478
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000479 memset((void *) &buf, '\0', sizeof(buf));
Guido van Rossum1f41f841998-04-27 19:04:26 +0000480
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000481 /* Will always expect a unicode string to be passed as format.
482 Given that there's no str type anymore in py3k this seems safe.
483 */
Victor Stinneref128102010-10-07 01:00:52 +0000484 if (!PyArg_ParseTuple(args, "U|O:strftime", &format_arg, &tup))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000485 return NULL;
Thomas Woutersfe385252001-01-19 23:16:56 +0000486
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000487 if (tup == NULL) {
488 time_t tt = time(NULL);
489 buf = *localtime(&tt);
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000490 }
491 else if (!gettmarg(tup, &buf) || !checktm(&buf))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000492 return NULL;
Guido van Rossum10b164a2001-09-25 13:59:01 +0000493
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000494 /* Normalize tm_isdst just in case someone foolishly implements %Z
495 based on the assumption that tm_isdst falls within the range of
496 [-1, 1] */
497 if (buf.tm_isdst < -1)
498 buf.tm_isdst = -1;
499 else if (buf.tm_isdst > 1)
500 buf.tm_isdst = 1;
Brett Cannond1080a32004-03-02 04:38:10 +0000501
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000502#ifdef HAVE_WCSFTIME
Victor Stinnerbeb4135b2010-10-07 01:02:42 +0000503 format = PyUnicode_AsWideCharString(format_arg, NULL);
Victor Stinnerb2904782010-09-29 10:34:19 +0000504 if (format == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000505 return NULL;
Victor Stinnerb2904782010-09-29 10:34:19 +0000506 fmt = format;
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000507#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000508 /* Convert the unicode string to an ascii one */
Victor Stinneref128102010-10-07 01:00:52 +0000509 format = PyUnicode_AsEncodedString(format_arg, TZNAME_ENCODING, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000510 if (format == NULL)
511 return NULL;
512 fmt = PyBytes_AS_STRING(format);
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000513#endif
Amaury Forgeot d'Arcb5be6d42009-03-02 23:52:57 +0000514
Hirokazu Yamamoto6b0e51a2009-06-03 05:19:18 +0000515#if defined(MS_WINDOWS) && defined(HAVE_WCSFTIME)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000516 /* check that the format string contains only valid directives */
517 for(outbuf = wcschr(fmt, L'%');
518 outbuf != NULL;
519 outbuf = wcschr(outbuf+2, L'%'))
520 {
521 if (outbuf[1]=='#')
522 ++outbuf; /* not documented by python, */
523 if (outbuf[1]=='\0' ||
524 !wcschr(L"aAbBcdfHIjmMpSUwWxXyYzZ%", outbuf[1]))
525 {
526 PyErr_SetString(PyExc_ValueError, "Invalid format string");
527 return 0;
528 }
529 }
Amaury Forgeot d'Arcb5be6d42009-03-02 23:52:57 +0000530#endif
531
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000532 fmtlen = time_strlen(fmt);
Guido van Rossumc222ec21999-02-23 00:00:10 +0000533
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000534 /* I hate these functions that presume you know how big the output
535 * will be ahead of time...
536 */
537 for (i = 1024; ; i += i) {
538 outbuf = (time_char *)PyMem_Malloc(i*sizeof(time_char));
539 if (outbuf == NULL) {
Victor Stinnerb2904782010-09-29 10:34:19 +0000540 PyErr_NoMemory();
541 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000542 }
543 buflen = format_time(outbuf, i, fmt, &buf);
544 if (buflen > 0 || i >= 256 * fmtlen) {
545 /* If the buffer is 256 times as long as the format,
546 it's probably not failing for lack of room!
547 More likely, the format yields an empty result,
548 e.g. an empty format, or %Z when the timezone
549 is unknown. */
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000550#ifdef HAVE_WCSFTIME
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000551 ret = PyUnicode_FromWideChar(outbuf, buflen);
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000552#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000553 ret = PyUnicode_Decode(outbuf, buflen,
554 TZNAME_ENCODING, NULL);
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000555#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000556 PyMem_Free(outbuf);
Victor Stinnerb2904782010-09-29 10:34:19 +0000557 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000558 }
559 PyMem_Free(outbuf);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000560#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000561 /* VisualStudio .NET 2005 does this properly */
562 if (buflen == 0 && errno == EINVAL) {
563 PyErr_SetString(PyExc_ValueError, "Invalid format string");
Victor Stinnerb2904782010-09-29 10:34:19 +0000564 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000565 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000566#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000567 }
Victor Stinnerb2904782010-09-29 10:34:19 +0000568#ifdef HAVE_WCSFTIME
569 PyMem_Free(format);
570#else
571 Py_DECREF(format);
572#endif
573 return ret;
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000574}
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000575
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000576#undef time_char
577#undef format_time
578
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000579PyDoc_STRVAR(strftime_doc,
Thomas Woutersfe385252001-01-19 23:16:56 +0000580"strftime(format[, tuple]) -> string\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000581\n\
582Convert a time tuple to a string according to a format specification.\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000583See the library reference manual for formatting codes. When the time tuple\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000584is not present, current time as returned by localtime() is used.");
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000585#endif /* HAVE_STRFTIME */
586
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000587static PyObject *
588time_strptime(PyObject *self, PyObject *args)
589{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000590 PyObject *strptime_module = PyImport_ImportModuleNoBlock("_strptime");
591 PyObject *strptime_result;
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000592
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000593 if (!strptime_module)
594 return NULL;
595 strptime_result = PyObject_CallMethod(strptime_module,
596 "_strptime_time", "O", args);
597 Py_DECREF(strptime_module);
598 return strptime_result;
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000599}
600
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000601
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
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000608static PyObject *
609_asctime(struct tm *timeptr)
610{
611 /* Inspired by Open Group reference implementation available at
612 * http://pubs.opengroup.org/onlinepubs/009695399/functions/asctime.html */
613 static char wday_name[7][3] = {
614 "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
615 };
616 static char mon_name[12][3] = {
617 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
618 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
619 };
620 char buf[20]; /* 'Sun Sep 16 01:03:52\0' */
621 int n;
622
623 n = snprintf(buf, sizeof(buf), "%.3s %.3s%3d %.2d:%.2d:%.2d",
624 wday_name[timeptr->tm_wday],
625 mon_name[timeptr->tm_mon],
626 timeptr->tm_mday, timeptr->tm_hour,
627 timeptr->tm_min, timeptr->tm_sec);
628 /* XXX: since the fields used by snprintf above are validated in checktm,
629 * the following condition should never trigger. We keep the check because
630 * historically fixed size buffer used in asctime was the source of
631 * crashes. */
632 if (n + 1 != sizeof(buf)) {
633 PyErr_SetString(PyExc_ValueError, "unconvertible time");
634 return NULL;
635 }
636
637 return PyUnicode_FromFormat("%s %d", buf, 1900 + timeptr->tm_year);
638}
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000639
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000640static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000641time_asctime(PyObject *self, PyObject *args)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000642{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000643 PyObject *tup = NULL;
644 struct tm buf;
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000645
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000646 if (!PyArg_UnpackTuple(args, "asctime", 0, 1, &tup))
647 return NULL;
648 if (tup == NULL) {
649 time_t tt = time(NULL);
650 buf = *localtime(&tt);
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000651 } else if (!gettmarg(tup, &buf) || !checktm(&buf))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000652 return NULL;
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000653 return _asctime(&buf);
Guido van Rossum9e90a671993-06-24 11:10:19 +0000654}
655
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000656PyDoc_STRVAR(asctime_doc,
Thomas Woutersfe385252001-01-19 23:16:56 +0000657"asctime([tuple]) -> string\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000658\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000659Convert a time tuple to a string, e.g. 'Sat Jun 06 16:26:11 1998'.\n\
660When the time tuple is not present, current time as returned by localtime()\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000661is used.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000662
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000663static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000664time_ctime(PyObject *self, PyObject *args)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000665{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000666 PyObject *ot = NULL;
667 time_t tt;
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000668 struct tm *timeptr;
Guido van Rossum10b164a2001-09-25 13:59:01 +0000669
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000670 if (!PyArg_UnpackTuple(args, "ctime", 0, 1, &ot))
671 return NULL;
672 if (ot == NULL || ot == Py_None)
673 tt = time(NULL);
674 else {
675 double dt = PyFloat_AsDouble(ot);
676 if (PyErr_Occurred())
677 return NULL;
678 tt = _PyTime_DoubleToTimet(dt);
679 if (tt == (time_t)-1 && PyErr_Occurred())
680 return NULL;
681 }
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000682 timeptr = localtime(&tt);
683 if (timeptr == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000684 PyErr_SetString(PyExc_ValueError, "unconvertible time");
Alexander Belopolsky5da468f2011-01-04 17:15:52 +0000685 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000686 }
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000687 return _asctime(timeptr);
Guido van Rossum9e90a671993-06-24 11:10:19 +0000688}
689
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000690PyDoc_STRVAR(ctime_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000691"ctime(seconds) -> string\n\
692\n\
693Convert a time in seconds since the Epoch to a string in local time.\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000694This is equivalent to asctime(localtime(seconds)). When the time tuple is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000695not present, current time as returned by localtime() is used.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000696
Guido van Rossum60cd8131998-03-06 17:16:21 +0000697#ifdef HAVE_MKTIME
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000698static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000699time_mktime(PyObject *self, PyObject *tup)
Guido van Rossum234f9421993-06-17 12:35:49 +0000700{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000701 struct tm buf;
702 time_t tt;
703 if (!gettmarg(tup, &buf))
704 return NULL;
705 tt = mktime(&buf);
706 if (tt == (time_t)(-1)) {
707 PyErr_SetString(PyExc_OverflowError,
708 "mktime argument out of range");
709 return NULL;
710 }
711 return PyFloat_FromDouble((double)tt);
Guido van Rossum234f9421993-06-17 12:35:49 +0000712}
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000713
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000714PyDoc_STRVAR(mktime_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000715"mktime(tuple) -> floating point number\n\
716\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000717Convert a time tuple in local time to seconds since the Epoch.");
Guido van Rossum60cd8131998-03-06 17:16:21 +0000718#endif /* HAVE_MKTIME */
Guido van Rossum234f9421993-06-17 12:35:49 +0000719
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000720#ifdef HAVE_WORKING_TZSET
Martin v. Löwis1a214512008-06-11 05:26:20 +0000721static void PyInit_timezone(PyObject *module);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000722
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000723static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000724time_tzset(PyObject *self, PyObject *unused)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000725{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000726 PyObject* m;
Fred Drake9bb74322002-04-01 14:49:59 +0000727
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000728 m = PyImport_ImportModuleNoBlock("time");
729 if (m == NULL) {
730 return NULL;
731 }
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000732
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000733 tzset();
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000734
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000735 /* Reset timezone, altzone, daylight and tzname */
736 PyInit_timezone(m);
737 Py_DECREF(m);
Tim Peters1b6f7a92004-06-20 02:50:16 +0000738
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000739 Py_INCREF(Py_None);
740 return Py_None;
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000741}
742
743PyDoc_STRVAR(tzset_doc,
R. David Murray4d55bf92010-12-14 00:55:46 +0000744"tzset()\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000745\n\
746Initialize, or reinitialize, the local timezone to the value stored in\n\
747os.environ['TZ']. The TZ environment variable should be specified in\n\
Neal Norwitzdc8e1942004-07-20 22:34:37 +0000748standard Unix timezone format as documented in the tzset man page\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000749(eg. 'US/Eastern', 'Europe/Amsterdam'). Unknown timezones will silently\n\
750fall back to UTC. If the TZ environment variable is not set, the local\n\
751timezone is set to the systems best guess of wallclock time.\n\
752Changing the TZ environment variable without calling tzset *may* change\n\
753the local timezone used by methods such as localtime, but this behaviour\n\
754should not be relied on.");
755#endif /* HAVE_WORKING_TZSET */
756
Martin v. Löwisd218dc12008-04-07 03:17:54 +0000757static void
Martin v. Löwis1a214512008-06-11 05:26:20 +0000758PyInit_timezone(PyObject *m) {
759 /* This code moved from PyInit_time wholesale to allow calling it from
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000760 time_tzset. In the future, some parts of it can be moved back
761 (for platforms that don't HAVE_WORKING_TZSET, when we know what they
762 are), and the extraneous calls to tzset(3) should be removed.
763 I haven't done this yet, as I don't want to change this code as
764 little as possible when introducing the time.tzset and time.tzsetwall
765 methods. This should simply be a method of doing the following once,
766 at the top of this function and removing the call to tzset() from
767 time_tzset():
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000768
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000769 #ifdef HAVE_TZSET
770 tzset()
771 #endif
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000772
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000773 And I'm lazy and hate C so nyer.
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000774 */
Guido van Rossum10b164a2001-09-25 13:59:01 +0000775#if defined(HAVE_TZNAME) && !defined(__GLIBC__) && !defined(__CYGWIN__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000776 PyObject *otz0, *otz1;
777 tzset();
Guido van Rossum26452411998-09-28 22:07:11 +0000778#ifdef PYOS_OS2
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000779 PyModule_AddIntConstant(m, "timezone", _timezone);
Guido van Rossum26452411998-09-28 22:07:11 +0000780#else /* !PYOS_OS2 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000781 PyModule_AddIntConstant(m, "timezone", timezone);
Guido van Rossum26452411998-09-28 22:07:11 +0000782#endif /* PYOS_OS2 */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000783#ifdef HAVE_ALTZONE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000784 PyModule_AddIntConstant(m, "altzone", altzone);
Guido van Rossumb6775db1994-08-01 11:34:53 +0000785#else
Guido van Rossum26452411998-09-28 22:07:11 +0000786#ifdef PYOS_OS2
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000787 PyModule_AddIntConstant(m, "altzone", _timezone-3600);
Guido van Rossum26452411998-09-28 22:07:11 +0000788#else /* !PYOS_OS2 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000789 PyModule_AddIntConstant(m, "altzone", timezone-3600);
Guido van Rossum26452411998-09-28 22:07:11 +0000790#endif /* PYOS_OS2 */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000791#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000792 PyModule_AddIntConstant(m, "daylight", daylight);
793 otz0 = PyUnicode_Decode(tzname[0], strlen(tzname[0]), TZNAME_ENCODING, NULL);
794 otz1 = PyUnicode_Decode(tzname[1], strlen(tzname[1]), TZNAME_ENCODING, NULL);
795 PyModule_AddObject(m, "tzname", Py_BuildValue("(NN)", otz0, otz1));
Guido van Rossum10b164a2001-09-25 13:59:01 +0000796#else /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/
Martin v. Löwis60a5d722002-10-16 20:28:25 +0000797#ifdef HAVE_STRUCT_TM_TM_ZONE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000798 {
Guido van Rossum234f9421993-06-17 12:35:49 +0000799#define YEAR ((time_t)((365 * 24 + 6) * 3600))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000800 time_t t;
801 struct tm *p;
802 long janzone, julyzone;
803 char janname[10], julyname[10];
804 t = (time((time_t *)0) / YEAR) * YEAR;
805 p = localtime(&t);
806 janzone = -p->tm_gmtoff;
807 strncpy(janname, p->tm_zone ? p->tm_zone : " ", 9);
808 janname[9] = '\0';
809 t += YEAR/2;
810 p = localtime(&t);
811 julyzone = -p->tm_gmtoff;
812 strncpy(julyname, p->tm_zone ? p->tm_zone : " ", 9);
813 julyname[9] = '\0';
Guido van Rossum10b164a2001-09-25 13:59:01 +0000814
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000815 if( janzone < julyzone ) {
816 /* DST is reversed in the southern hemisphere */
817 PyModule_AddIntConstant(m, "timezone", julyzone);
818 PyModule_AddIntConstant(m, "altzone", janzone);
819 PyModule_AddIntConstant(m, "daylight",
820 janzone != julyzone);
821 PyModule_AddObject(m, "tzname",
822 Py_BuildValue("(zz)",
823 julyname, janname));
824 } else {
825 PyModule_AddIntConstant(m, "timezone", janzone);
826 PyModule_AddIntConstant(m, "altzone", julyzone);
827 PyModule_AddIntConstant(m, "daylight",
828 janzone != julyzone);
829 PyModule_AddObject(m, "tzname",
830 Py_BuildValue("(zz)",
831 janname, julyname));
832 }
833 }
Guido van Rossume6a4b7b1997-10-08 15:27:56 +0000834#else
Martin v. Löwis60a5d722002-10-16 20:28:25 +0000835#endif /* HAVE_STRUCT_TM_TM_ZONE */
Tim Peters26ae7cd2001-03-20 03:26:49 +0000836#ifdef __CYGWIN__
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000837 tzset();
838 PyModule_AddIntConstant(m, "timezone", _timezone);
839 PyModule_AddIntConstant(m, "altzone", _timezone-3600);
840 PyModule_AddIntConstant(m, "daylight", _daylight);
841 PyModule_AddObject(m, "tzname",
842 Py_BuildValue("(zz)", _tzname[0], _tzname[1]));
Tim Peters26ae7cd2001-03-20 03:26:49 +0000843#endif /* __CYGWIN__ */
Guido van Rossum10b164a2001-09-25 13:59:01 +0000844#endif /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000845}
846
847
848static PyMethodDef time_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000849 {"time", time_time, METH_NOARGS, time_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000850#ifdef HAVE_CLOCK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000851 {"clock", time_clock, METH_NOARGS, clock_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000852#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000853 {"sleep", time_sleep, METH_VARARGS, sleep_doc},
854 {"gmtime", time_gmtime, METH_VARARGS, gmtime_doc},
855 {"localtime", time_localtime, METH_VARARGS, localtime_doc},
856 {"asctime", time_asctime, METH_VARARGS, asctime_doc},
857 {"ctime", time_ctime, METH_VARARGS, ctime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000858#ifdef HAVE_MKTIME
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000859 {"mktime", time_mktime, METH_O, mktime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000860#endif
861#ifdef HAVE_STRFTIME
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000862 {"strftime", time_strftime, METH_VARARGS, strftime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000863#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000864 {"strptime", time_strptime, METH_VARARGS, strptime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000865#ifdef HAVE_WORKING_TZSET
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000866 {"tzset", time_tzset, METH_NOARGS, tzset_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000867#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000868 {NULL, NULL} /* sentinel */
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000869};
870
871
872PyDoc_STRVAR(module_doc,
873"This module provides various functions to manipulate time values.\n\
874\n\
875There are two standard representations of time. One is the number\n\
876of seconds since the Epoch, in UTC (a.k.a. GMT). It may be an integer\n\
877or a floating point number (to represent fractions of seconds).\n\
878The Epoch is system-defined; on Unix, it is generally January 1st, 1970.\n\
879The actual value can be retrieved by calling gmtime(0).\n\
880\n\
881The other representation is a tuple of 9 integers giving local time.\n\
882The tuple items are:\n\
883 year (four digits, e.g. 1998)\n\
884 month (1-12)\n\
885 day (1-31)\n\
886 hours (0-23)\n\
887 minutes (0-59)\n\
888 seconds (0-59)\n\
889 weekday (0-6, Monday is 0)\n\
890 Julian day (day in the year, 1-366)\n\
891 DST (Daylight Savings Time) flag (-1, 0 or 1)\n\
892If the DST flag is 0, the time is given in the regular time zone;\n\
893if it is 1, the time is given in the DST time zone;\n\
894if it is -1, mktime() should guess based on the date and time.\n\
895\n\
896Variables:\n\
897\n\
898timezone -- difference in seconds between UTC and local standard time\n\
899altzone -- difference in seconds between UTC and local DST time\n\
900daylight -- whether local time should reflect DST\n\
901tzname -- tuple of (standard time zone name, DST time zone name)\n\
902\n\
903Functions:\n\
904\n\
905time() -- return current time in seconds since the Epoch as a float\n\
906clock() -- return CPU time since process start as a float\n\
907sleep() -- delay for a number of seconds given as a float\n\
908gmtime() -- convert seconds since Epoch to UTC tuple\n\
909localtime() -- convert seconds since Epoch to local time tuple\n\
910asctime() -- convert time tuple to string\n\
911ctime() -- convert time in seconds to string\n\
912mktime() -- convert local time tuple to seconds since Epoch\n\
913strftime() -- convert time tuple to string according to format specification\n\
914strptime() -- parse string to time tuple according to format specification\n\
915tzset() -- change the local timezone");
916
917
Martin v. Löwis1a214512008-06-11 05:26:20 +0000918
919static struct PyModuleDef timemodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000920 PyModuleDef_HEAD_INIT,
921 "time",
922 module_doc,
923 -1,
924 time_methods,
925 NULL,
926 NULL,
927 NULL,
928 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +0000929};
930
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000931PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +0000932PyInit_time(void)
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000933{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000934 PyObject *m;
935 char *p;
936 m = PyModule_Create(&timemodule);
937 if (m == NULL)
938 return NULL;
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000939
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000940 /* Accept 2-digit dates unless PYTHONY2K is set and non-empty */
941 p = Py_GETENV("PYTHONY2K");
942 PyModule_AddIntConstant(m, "accept2dyear", (long) (!p || !*p));
943 /* Squirrel away the module's dictionary for the y2k check */
944 moddict = PyModule_GetDict(m);
945 Py_INCREF(moddict);
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000946
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000947 /* Set, or reset, module variables like time.timezone */
948 PyInit_timezone(m);
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000949
Mark Hammond975e3922002-07-16 01:29:19 +0000950#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000951 /* Helper to allow interrupts for Windows.
952 If Ctrl+C event delivered while not sleeping
953 it will be ignored.
954 */
955 main_thread = PyThread_get_thread_ident();
956 hInterruptEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
957 SetConsoleCtrlHandler( PyCtrlHandler, TRUE);
Mark Hammond975e3922002-07-16 01:29:19 +0000958#endif /* MS_WINDOWS */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000959 if (!initialized) {
960 PyStructSequence_InitType(&StructTimeType,
961 &struct_time_type_desc);
962 }
963 Py_INCREF(&StructTimeType);
964 PyModule_AddObject(m, "struct_time", (PyObject*) &StructTimeType);
965 initialized = 1;
966 return m;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000967}
968
Guido van Rossumb6775db1994-08-01 11:34:53 +0000969static double
Thomas Woutersf3f33dc2000-07-21 06:00:07 +0000970floattime(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000971{
Alexander Belopolsky6fc4ade2010-08-05 17:34:27 +0000972 _PyTime_timeval t;
973 _PyTime_gettimeofday(&t);
974 return (double)t.tv_sec + t.tv_usec*0.000001;
Guido van Rossum426035c1991-02-19 12:27:35 +0000975}
976
Guido van Rossumb6775db1994-08-01 11:34:53 +0000977
978/* Implement floatsleep() for various platforms.
979 When interrupted (or when another error occurs), return -1 and
980 set an exception; else return 0. */
981
982static int
Guido van Rossuma320fd31995-03-09 12:14:15 +0000983floatsleep(double secs)
Guido van Rossum426035c1991-02-19 12:27:35 +0000984{
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000985/* XXX Should test for MS_WINDOWS first! */
Skip Montanaroeb33e5a2007-08-17 12:57:41 +0000986#if defined(HAVE_SELECT) && !defined(__EMX__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000987 struct timeval t;
988 double frac;
989 frac = fmod(secs, 1.0);
990 secs = floor(secs);
991 t.tv_sec = (long)secs;
992 t.tv_usec = (long)(frac*1000000.0);
993 Py_BEGIN_ALLOW_THREADS
994 if (select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &t) != 0) {
Guido van Rossum09cbb011999-11-08 15:32:27 +0000995#ifdef EINTR
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000996 if (errno != EINTR) {
Guido van Rossum09cbb011999-11-08 15:32:27 +0000997#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000998 if (1) {
Guido van Rossum09cbb011999-11-08 15:32:27 +0000999#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001000 Py_BLOCK_THREADS
1001 PyErr_SetFromErrno(PyExc_IOError);
1002 return -1;
1003 }
1004 }
1005 Py_END_ALLOW_THREADS
Martin v. Löwis02af9642002-01-16 11:04:06 +00001006#elif defined(__WATCOMC__) && !defined(__QNX__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001007 /* XXX Can't interrupt this sleep */
1008 Py_BEGIN_ALLOW_THREADS
1009 delay((int)(secs * 1000 + 0.5)); /* delay() uses milliseconds */
1010 Py_END_ALLOW_THREADS
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001011#elif defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001012 {
1013 double millisecs = secs * 1000.0;
1014 unsigned long ul_millis;
Tim Peters513a1cd2003-01-19 04:54:58 +00001015
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001016 if (millisecs > (double)ULONG_MAX) {
1017 PyErr_SetString(PyExc_OverflowError,
1018 "sleep length is too large");
1019 return -1;
1020 }
1021 Py_BEGIN_ALLOW_THREADS
1022 /* Allow sleep(0) to maintain win32 semantics, and as decreed
1023 * by Guido, only the main thread can be interrupted.
1024 */
1025 ul_millis = (unsigned long)millisecs;
1026 if (ul_millis == 0 ||
1027 main_thread != PyThread_get_thread_ident())
1028 Sleep(ul_millis);
1029 else {
1030 DWORD rc;
1031 ResetEvent(hInterruptEvent);
1032 rc = WaitForSingleObject(hInterruptEvent, ul_millis);
1033 if (rc == WAIT_OBJECT_0) {
1034 /* Yield to make sure real Python signal
1035 * handler called.
1036 */
1037 Sleep(1);
1038 Py_BLOCK_THREADS
1039 errno = EINTR;
1040 PyErr_SetFromErrno(PyExc_IOError);
1041 return -1;
1042 }
1043 }
1044 Py_END_ALLOW_THREADS
1045 }
Martin v. Löwis02af9642002-01-16 11:04:06 +00001046#elif defined(PYOS_OS2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001047 /* This Sleep *IS* Interruptable by Exceptions */
1048 Py_BEGIN_ALLOW_THREADS
1049 if (DosSleep(secs * 1000) != NO_ERROR) {
1050 Py_BLOCK_THREADS
1051 PyErr_SetFromErrno(PyExc_IOError);
1052 return -1;
1053 }
1054 Py_END_ALLOW_THREADS
Martin v. Löwis02af9642002-01-16 11:04:06 +00001055#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001056 /* XXX Can't interrupt this sleep */
1057 Py_BEGIN_ALLOW_THREADS
1058 sleep((int)secs);
1059 Py_END_ALLOW_THREADS
Martin v. Löwis02af9642002-01-16 11:04:06 +00001060#endif
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001061
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001062 return 0;
Guido van Rossum80c9d881991-04-16 08:47:51 +00001063}