blob: 5e6cd6c91b42717964f5f822b3c3e4476a9e38e8 [file] [log] [blame]
Guido van Rossumf70e43a1991-02-19 12:39:46 +00001
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002/* Time module */
3
Barry Warsaw9a2a8a81996-12-06 23:32:14 +00004#include "Python.h"
Guido van Rossum98bf58f2001-10-18 20:34:25 +00005#include "structseq.h"
Alexander Belopolsky6fc4ade2010-08-05 17:34:27 +00006#include "_time.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +00007
Martin v. Löwis8a7c8662007-08-30 15:40:24 +00008#define TZNAME_ENCODING "utf-8"
9
Guido van Rossum87ce7bb1998-06-09 16:30:31 +000010#include <ctype.h>
11
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012#ifdef HAVE_SYS_TYPES_H
Guido van Rossumb6775db1994-08-01 11:34:53 +000013#include <sys/types.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014#endif /* HAVE_SYS_TYPES_H */
Guido van Rossum6d946f91992-08-14 13:49:30 +000015
Guido van Rossumb6775db1994-08-01 11:34:53 +000016#ifdef QUICKWIN
17#include <io.h>
18#endif
19
Guido van Rossum7bf22de1997-12-02 20:34:19 +000020#if defined(__WATCOMC__) && !defined(__QNX__)
Guido van Rossumbceeac81996-05-23 22:53:47 +000021#include <i86.h>
22#else
Guido van Rossumcac6c721996-09-06 13:34:02 +000023#ifdef MS_WINDOWS
Mark Hammond975e3922002-07-16 01:29:19 +000024#define WIN32_LEAN_AND_MEAN
Guido van Rossum258ccd42001-03-02 06:53:29 +000025#include <windows.h>
Mark Hammond975e3922002-07-16 01:29:19 +000026#include "pythread.h"
27
28/* helper to allow us to interrupt sleep() on Windows*/
29static HANDLE hInterruptEvent = NULL;
30static BOOL WINAPI PyCtrlHandler(DWORD dwCtrlType)
31{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000032 SetEvent(hInterruptEvent);
33 /* allow other default handlers to be called.
34 Default Python handler will setup the
35 KeyboardInterrupt exception.
36 */
37 return FALSE;
Mark Hammond975e3922002-07-16 01:29:19 +000038}
39static long main_thread;
40
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000041#if defined(__BORLANDC__)
Guido van Rossumb2fb3641996-09-07 00:47:35 +000042/* These overrides not needed for Win32 */
Guido van Rossumb6775db1994-08-01 11:34:53 +000043#define timezone _timezone
Guido van Rossumcc081121995-03-14 15:05:41 +000044#define tzname _tzname
45#define daylight _daylight
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000046#endif /* __BORLANDC__ */
Guido van Rossumcac6c721996-09-06 13:34:02 +000047#endif /* MS_WINDOWS */
Guido van Rossum7bf22de1997-12-02 20:34:19 +000048#endif /* !__WATCOMC__ || __QNX__ */
Guido van Rossum234f9421993-06-17 12:35:49 +000049
Thomas Wouters477c8d52006-05-27 19:21:47 +000050#if defined(MS_WINDOWS) && !defined(__BORLANDC__)
51/* Win32 has better clock replacement; we have our own version below. */
52#undef HAVE_CLOCK
Martin v. Löwis3bb00702007-08-30 14:37:48 +000053#undef TZNAME_ENCODING
54#define TZNAME_ENCODING "mbcs"
Thomas Wouters477c8d52006-05-27 19:21:47 +000055#endif /* MS_WINDOWS && !defined(__BORLANDC__) */
Guido van Rossum3917c221997-04-02 05:35:28 +000056
Andrew MacIntyre7bf68332002-03-03 02:59:16 +000057#if defined(PYOS_OS2)
58#define INCL_DOS
59#define INCL_ERRORS
60#include <os2.h>
61#endif
62
Guido van Rossum8e9ebfd1997-11-22 21:53:48 +000063#if defined(PYCC_VACPP)
Guido van Rossum26452411998-09-28 22:07:11 +000064#include <sys/time.h>
Guido van Rossum8e9ebfd1997-11-22 21:53:48 +000065#endif
66
Guido van Rossum234f9421993-06-17 12:35:49 +000067/* Forward declarations */
Tim Petersdbd9ba62000-07-09 03:09:57 +000068static int floatsleep(double);
Thomas Woutersed77bac2000-07-24 15:26:39 +000069static double floattime(void);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000070
Guido van Rossumcfbaecc1998-08-25 14:51:12 +000071/* For Y2K check */
72static PyObject *moddict;
73
Barry Warsaw9a2a8a81996-12-06 23:32:14 +000074static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000075time_time(PyObject *self, PyObject *unused)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000076{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000077 double secs;
78 secs = floattime();
79 if (secs == 0.0) {
80 PyErr_SetFromErrno(PyExc_IOError);
81 return NULL;
82 }
83 return PyFloat_FromDouble(secs);
Guido van Rossumb6775db1994-08-01 11:34:53 +000084}
85
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000086PyDoc_STRVAR(time_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +000087"time() -> floating point number\n\
88\n\
89Return the current time in seconds since the Epoch.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000090Fractions of a second may be present if the system clock provides them.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +000091
Guido van Rossumb6775db1994-08-01 11:34:53 +000092#ifdef HAVE_CLOCK
93
94#ifndef CLOCKS_PER_SEC
Guido van Rossum1b66a4f1996-02-25 04:50:33 +000095#ifdef CLK_TCK
96#define CLOCKS_PER_SEC CLK_TCK
97#else
Guido van Rossumb6775db1994-08-01 11:34:53 +000098#define CLOCKS_PER_SEC 1000000
99#endif
Guido van Rossum1b66a4f1996-02-25 04:50:33 +0000100#endif
Guido van Rossumb6775db1994-08-01 11:34:53 +0000101
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000102static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000103time_clock(PyObject *self, PyObject *unused)
Guido van Rossumb6775db1994-08-01 11:34:53 +0000104{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000105 return PyFloat_FromDouble(((double)clock()) / CLOCKS_PER_SEC);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000106}
Guido van Rossumb6775db1994-08-01 11:34:53 +0000107#endif /* HAVE_CLOCK */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000108
Thomas Wouters477c8d52006-05-27 19:21:47 +0000109#if defined(MS_WINDOWS) && !defined(__BORLANDC__)
Mark Hammond7ba5e812002-02-12 04:02:33 +0000110/* Due to Mark Hammond and Tim Peters */
Guido van Rossum3917c221997-04-02 05:35:28 +0000111static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000112time_clock(PyObject *self, PyObject *unused)
Guido van Rossum3917c221997-04-02 05:35:28 +0000113{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000114 static LARGE_INTEGER ctrStart;
115 static double divisor = 0.0;
116 LARGE_INTEGER now;
117 double diff;
Guido van Rossum3917c221997-04-02 05:35:28 +0000118
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000119 if (divisor == 0.0) {
120 LARGE_INTEGER freq;
121 QueryPerformanceCounter(&ctrStart);
122 if (!QueryPerformanceFrequency(&freq) || freq.QuadPart == 0) {
123 /* Unlikely to happen - this works on all intel
124 machines at least! Revert to clock() */
125 return PyFloat_FromDouble(((double)clock()) /
126 CLOCKS_PER_SEC);
127 }
128 divisor = (double)freq.QuadPart;
129 }
130 QueryPerformanceCounter(&now);
131 diff = (double)(now.QuadPart - ctrStart.QuadPart);
132 return PyFloat_FromDouble(diff / divisor);
Guido van Rossum3917c221997-04-02 05:35:28 +0000133}
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000134
Guido van Rossum3917c221997-04-02 05:35:28 +0000135#define HAVE_CLOCK /* So it gets included in the methods */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000136#endif /* MS_WINDOWS && !defined(__BORLANDC__) */
Guido van Rossum3917c221997-04-02 05:35:28 +0000137
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000138#ifdef HAVE_CLOCK
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000139PyDoc_STRVAR(clock_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000140"clock() -> floating point number\n\
141\n\
142Return the CPU time or real time since the start of the process or since\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000143the first call to clock(). This has as much precision as the system\n\
144records.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000145#endif
146
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000147static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000148time_sleep(PyObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000149{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000150 double secs;
151 if (!PyArg_ParseTuple(args, "d:sleep", &secs))
152 return NULL;
153 if (floatsleep(secs) != 0)
154 return NULL;
155 Py_INCREF(Py_None);
156 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000157}
158
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000159PyDoc_STRVAR(sleep_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000160"sleep(seconds)\n\
161\n\
162Delay execution for a given number of seconds. The argument may be\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000163a floating point number for subsecond precision.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000164
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000165static PyStructSequence_Field struct_time_type_fields[] = {
Alexander Belopolsky69f3fd02010-06-05 15:04:51 +0000166 {"tm_year", "year, for example, 1993"},
167 {"tm_mon", "month of year, range [1, 12]"},
168 {"tm_mday", "day of month, range [1, 31]"},
169 {"tm_hour", "hours, range [0, 23]"},
170 {"tm_min", "minutes, range [0, 59]"},
171 {"tm_sec", "seconds, range [0, 61])"},
172 {"tm_wday", "day of week, range [0, 6], Monday is 0"},
173 {"tm_yday", "day of year, range [1, 366]"},
174 {"tm_isdst", "1 if summer time is in effect, 0 if not, and -1 if unknown"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000175 {0}
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000176};
177
178static PyStructSequence_Desc struct_time_type_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000179 "time.struct_time",
Alexander Belopolsky69f3fd02010-06-05 15:04:51 +0000180 "The time value as returned by gmtime(), localtime(), and strptime(), and\n"
181 " accepted by asctime(), mktime() and strftime(). May be considered as a\n"
182 " sequence of 9 integers.\n\n"
183 " Note that several fields' values are not the same as those defined by\n"
184 " the C language standard for struct tm. For example, the value of the\n"
185 " field tm_year is the actual year, not year - 1900. See individual\n"
186 " fields' descriptions for details.",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000187 struct_time_type_fields,
188 9,
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000189};
Tim Peters9ad4b682002-02-13 05:14:18 +0000190
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000191static int initialized;
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000192static PyTypeObject StructTimeType;
193
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000194static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000195tmtotuple(struct tm *p)
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000196{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000197 PyObject *v = PyStructSequence_New(&StructTimeType);
198 if (v == NULL)
199 return NULL;
Tim Peters9ad4b682002-02-13 05:14:18 +0000200
Christian Heimes217cfd12007-12-02 14:31:20 +0000201#define SET(i,val) PyStructSequence_SET_ITEM(v, i, PyLong_FromLong((long) val))
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000202
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000203 SET(0, p->tm_year + 1900);
204 SET(1, p->tm_mon + 1); /* Want January == 1 */
205 SET(2, p->tm_mday);
206 SET(3, p->tm_hour);
207 SET(4, p->tm_min);
208 SET(5, p->tm_sec);
209 SET(6, (p->tm_wday + 6) % 7); /* Want Monday == 0 */
210 SET(7, p->tm_yday + 1); /* Want January, 1 == 1 */
211 SET(8, p->tm_isdst);
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000212#undef SET
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000213 if (PyErr_Occurred()) {
214 Py_XDECREF(v);
215 return NULL;
216 }
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000217
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000218 return v;
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000219}
220
221static PyObject *
Skip Montanaro41cfce92007-08-24 21:11:00 +0000222structtime_totuple(PyObject *t)
223{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000224 PyObject *x = NULL;
225 unsigned int i;
226 PyObject *v = PyTuple_New(9);
227 if (v == NULL)
228 return NULL;
Skip Montanaro41cfce92007-08-24 21:11:00 +0000229
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000230 for (i=0; i<9; i++) {
231 x = PyStructSequence_GET_ITEM(t, i);
232 Py_INCREF(x);
233 PyTuple_SET_ITEM(v, i, x);
234 }
Skip Montanaro41cfce92007-08-24 21:11:00 +0000235
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000236 if (PyErr_Occurred()) {
237 Py_XDECREF(v);
238 return NULL;
239 }
Skip Montanaro41cfce92007-08-24 21:11:00 +0000240
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000241 return v;
Skip Montanaro41cfce92007-08-24 21:11:00 +0000242}
243
244static PyObject *
Brett Cannon298c3802004-06-19 20:48:43 +0000245time_convert(double when, struct tm * (*function)(const time_t *))
Guido van Rossum234f9421993-06-17 12:35:49 +0000246{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000247 struct tm *p;
248 time_t whent = _PyTime_DoubleToTimet(when);
Brett Cannon298c3802004-06-19 20:48:43 +0000249
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000250 if (whent == (time_t)-1 && PyErr_Occurred())
251 return NULL;
252 errno = 0;
253 p = function(&whent);
254 if (p == NULL) {
Guido van Rossum6e8583d1996-10-08 14:19:52 +0000255#ifdef EINVAL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000256 if (errno == 0)
257 errno = EINVAL;
Guido van Rossum6e8583d1996-10-08 14:19:52 +0000258#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000259 return PyErr_SetFromErrno(PyExc_ValueError);
260 }
261 return tmtotuple(p);
Guido van Rossum234f9421993-06-17 12:35:49 +0000262}
263
Fred Drakef901abd2004-08-03 17:58:55 +0000264/* Parse arg tuple that can contain an optional float-or-None value;
265 format needs to be "|O:name".
266 Returns non-zero on success (parallels PyArg_ParseTuple).
267*/
268static int
269parse_time_double_args(PyObject *args, char *format, double *pwhen)
270{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000271 PyObject *ot = NULL;
Fred Drakef901abd2004-08-03 17:58:55 +0000272
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000273 if (!PyArg_ParseTuple(args, format, &ot))
274 return 0;
275 if (ot == NULL || ot == Py_None)
276 *pwhen = floattime();
277 else {
278 double when = PyFloat_AsDouble(ot);
279 if (PyErr_Occurred())
280 return 0;
281 *pwhen = when;
282 }
283 return 1;
Fred Drakef901abd2004-08-03 17:58:55 +0000284}
285
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000286static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000287time_gmtime(PyObject *self, PyObject *args)
Guido van Rossum234f9421993-06-17 12:35:49 +0000288{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000289 double when;
290 if (!parse_time_double_args(args, "|O:gmtime", &when))
291 return NULL;
292 return time_convert(when, gmtime);
Guido van Rossum234f9421993-06-17 12:35:49 +0000293}
294
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000295PyDoc_STRVAR(gmtime_doc,
Christian Heimes9a371592007-12-28 14:08:13 +0000296"gmtime([seconds]) -> (tm_year, tm_mon, tm_mday, tm_hour, tm_min,\n\
Fred Drake193a3f62002-03-12 21:38:49 +0000297 tm_sec, tm_wday, tm_yday, tm_isdst)\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000298\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000299Convert seconds since the Epoch to a time tuple expressing UTC (a.k.a.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000300GMT). When 'seconds' is not passed in, convert the current time instead.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000301
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000302static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000303time_localtime(PyObject *self, PyObject *args)
Guido van Rossum234f9421993-06-17 12:35:49 +0000304{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000305 double when;
306 if (!parse_time_double_args(args, "|O:localtime", &when))
307 return NULL;
308 return time_convert(when, localtime);
Guido van Rossum234f9421993-06-17 12:35:49 +0000309}
310
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000311PyDoc_STRVAR(localtime_doc,
Christian Heimes9a371592007-12-28 14:08:13 +0000312"localtime([seconds]) -> (tm_year,tm_mon,tm_mday,tm_hour,tm_min,\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000313 tm_sec,tm_wday,tm_yday,tm_isdst)\n\
Martin v. Löwisb3cfc1d2001-12-02 12:27:43 +0000314\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000315Convert seconds since the Epoch to a time tuple expressing local time.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000316When 'seconds' is not passed in, convert the current time instead.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000317
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000318/* Convert 9-item tuple to tm structure. Return 1 on success, set
319 * an exception and return 0 on error.
320 */
Guido van Rossum9e90a671993-06-24 11:10:19 +0000321static int
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000322gettmarg(PyObject *args, struct tm *p)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000323{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000324 int y;
325 PyObject *t = NULL;
Guido van Rossumcfbaecc1998-08-25 14:51:12 +0000326
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000327 memset((void *) p, '\0', sizeof(struct tm));
Guido van Rossumb9081262007-08-25 03:14:09 +0000328
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000329 if (PyTuple_Check(args)) {
330 t = args;
331 Py_INCREF(t);
332 }
333 else if (Py_TYPE(args) == &StructTimeType) {
334 t = structtime_totuple(args);
335 }
336 else {
337 PyErr_SetString(PyExc_TypeError,
338 "Tuple or struct_time argument required");
339 return 0;
340 }
Skip Montanaro41cfce92007-08-24 21:11:00 +0000341
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000342 if (t == NULL || !PyArg_ParseTuple(t, "iiiiiiiii",
343 &y,
344 &p->tm_mon,
345 &p->tm_mday,
346 &p->tm_hour,
347 &p->tm_min,
348 &p->tm_sec,
349 &p->tm_wday,
350 &p->tm_yday,
351 &p->tm_isdst)) {
352 Py_XDECREF(t);
353 return 0;
354 }
355 Py_DECREF(t);
Skip Montanaro41cfce92007-08-24 21:11:00 +0000356
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000357 if (y < 1900) {
358 PyObject *accept = PyDict_GetItemString(moddict,
359 "accept2dyear");
360 if (accept == NULL || !PyLong_CheckExact(accept) ||
361 !PyObject_IsTrue(accept)) {
362 PyErr_SetString(PyExc_ValueError,
363 "year >= 1900 required");
364 return 0;
365 }
366 if (69 <= y && y <= 99)
367 y += 1900;
368 else if (0 <= y && y <= 68)
369 y += 2000;
370 else {
371 PyErr_SetString(PyExc_ValueError,
372 "year out of range");
373 return 0;
374 }
375 }
376 p->tm_year = y - 1900;
377 p->tm_mon--;
378 p->tm_wday = (p->tm_wday + 1) % 7;
379 p->tm_yday--;
380 return 1;
Guido van Rossum9e90a671993-06-24 11:10:19 +0000381}
382
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000383/* Check values of the struct tm fields before it is passed to strftime() and
384 * asctime(). Return 1 if all values are valid, otherwise set an exception
385 * and returns 0.
386 */
Victor Stinneref128102010-10-07 01:00:52 +0000387static int
388checktm(struct tm* buf)
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000389{
Victor Stinneref128102010-10-07 01:00:52 +0000390 /* Checks added to make sure strftime() and asctime() does not crash Python by
391 indexing blindly into some array for a textual representation
392 by some bad index (fixes bug #897625 and #6608).
393
394 Also support values of zero from Python code for arguments in which
395 that is out of range by forcing that value to the lowest value that
396 is valid (fixed bug #1520914).
397
398 Valid ranges based on what is allowed in struct tm:
399
400 - tm_year: [0, max(int)] (1)
401 - tm_mon: [0, 11] (2)
402 - tm_mday: [1, 31]
403 - tm_hour: [0, 23]
404 - tm_min: [0, 59]
405 - tm_sec: [0, 60]
406 - tm_wday: [0, 6] (1)
407 - tm_yday: [0, 365] (2)
408 - tm_isdst: [-max(int), max(int)]
409
410 (1) gettmarg() handles bounds-checking.
411 (2) Python's acceptable range is one greater than the range in C,
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000412 thus need to check against automatic decrement by gettmarg().
413 */
414 if (buf->tm_mon == -1)
415 buf->tm_mon = 0;
416 else if (buf->tm_mon < 0 || buf->tm_mon > 11) {
417 PyErr_SetString(PyExc_ValueError, "month out of range");
418 return 0;
419 }
420 if (buf->tm_mday == 0)
421 buf->tm_mday = 1;
422 else if (buf->tm_mday < 0 || buf->tm_mday > 31) {
423 PyErr_SetString(PyExc_ValueError, "day of month out of range");
424 return 0;
425 }
426 if (buf->tm_hour < 0 || buf->tm_hour > 23) {
427 PyErr_SetString(PyExc_ValueError, "hour out of range");
428 return 0;
429 }
430 if (buf->tm_min < 0 || buf->tm_min > 59) {
431 PyErr_SetString(PyExc_ValueError, "minute out of range");
432 return 0;
433 }
434 if (buf->tm_sec < 0 || buf->tm_sec > 61) {
435 PyErr_SetString(PyExc_ValueError, "seconds out of range");
436 return 0;
437 }
438 /* tm_wday does not need checking of its upper-bound since taking
439 ``% 7`` in gettmarg() automatically restricts the range. */
440 if (buf->tm_wday < 0) {
441 PyErr_SetString(PyExc_ValueError, "day of week out of range");
442 return 0;
443 }
444 if (buf->tm_yday == -1)
445 buf->tm_yday = 0;
446 else if (buf->tm_yday < 0 || buf->tm_yday > 365) {
447 PyErr_SetString(PyExc_ValueError, "day of year out of range");
448 return 0;
449 }
450 return 1;
451}
452
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000453#ifdef HAVE_STRFTIME
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000454#ifdef HAVE_WCSFTIME
455#define time_char wchar_t
456#define format_time wcsftime
457#define time_strlen wcslen
458#else
459#define time_char char
460#define format_time strftime
461#define time_strlen strlen
462#endif
463
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000464static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000465time_strftime(PyObject *self, PyObject *args)
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000466{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000467 PyObject *tup = NULL;
468 struct tm buf;
469 const time_char *fmt;
Victor Stinnerb2904782010-09-29 10:34:19 +0000470#ifdef HAVE_WCSFTIME
471 wchar_t *format;
472#else
473 PyObject *format;
474#endif
Victor Stinneref128102010-10-07 01:00:52 +0000475 PyObject *format_arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000476 size_t fmtlen, buflen;
Victor Stinnerb2904782010-09-29 10:34:19 +0000477 time_char *outbuf = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000478 size_t i;
Victor Stinnerb2904782010-09-29 10:34:19 +0000479 PyObject *ret = NULL;
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000480
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000481 memset((void *) &buf, '\0', sizeof(buf));
Guido van Rossum1f41f841998-04-27 19:04:26 +0000482
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000483 /* Will always expect a unicode string to be passed as format.
484 Given that there's no str type anymore in py3k this seems safe.
485 */
Victor Stinneref128102010-10-07 01:00:52 +0000486 if (!PyArg_ParseTuple(args, "U|O:strftime", &format_arg, &tup))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000487 return NULL;
Thomas Woutersfe385252001-01-19 23:16:56 +0000488
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000489 if (tup == NULL) {
490 time_t tt = time(NULL);
491 buf = *localtime(&tt);
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000492 }
493 else if (!gettmarg(tup, &buf) || !checktm(&buf))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000494 return NULL;
Guido van Rossum10b164a2001-09-25 13:59:01 +0000495
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000496 /* Normalize tm_isdst just in case someone foolishly implements %Z
497 based on the assumption that tm_isdst falls within the range of
498 [-1, 1] */
499 if (buf.tm_isdst < -1)
500 buf.tm_isdst = -1;
501 else if (buf.tm_isdst > 1)
502 buf.tm_isdst = 1;
Brett Cannond1080a32004-03-02 04:38:10 +0000503
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000504#ifdef HAVE_WCSFTIME
Victor Stinnerbeb4135b2010-10-07 01:02:42 +0000505 format = PyUnicode_AsWideCharString(format_arg, NULL);
Victor Stinnerb2904782010-09-29 10:34:19 +0000506 if (format == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000507 return NULL;
Victor Stinnerb2904782010-09-29 10:34:19 +0000508 fmt = format;
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000509#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000510 /* Convert the unicode string to an ascii one */
Victor Stinneref128102010-10-07 01:00:52 +0000511 format = PyUnicode_AsEncodedString(format_arg, TZNAME_ENCODING, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000512 if (format == NULL)
513 return NULL;
514 fmt = PyBytes_AS_STRING(format);
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000515#endif
Amaury Forgeot d'Arcb5be6d42009-03-02 23:52:57 +0000516
Hirokazu Yamamoto6b0e51a2009-06-03 05:19:18 +0000517#if defined(MS_WINDOWS) && defined(HAVE_WCSFTIME)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000518 /* check that the format string contains only valid directives */
519 for(outbuf = wcschr(fmt, L'%');
520 outbuf != NULL;
521 outbuf = wcschr(outbuf+2, L'%'))
522 {
523 if (outbuf[1]=='#')
524 ++outbuf; /* not documented by python, */
525 if (outbuf[1]=='\0' ||
526 !wcschr(L"aAbBcdfHIjmMpSUwWxXyYzZ%", outbuf[1]))
527 {
528 PyErr_SetString(PyExc_ValueError, "Invalid format string");
529 return 0;
530 }
531 }
Amaury Forgeot d'Arcb5be6d42009-03-02 23:52:57 +0000532#endif
533
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000534 fmtlen = time_strlen(fmt);
Guido van Rossumc222ec21999-02-23 00:00:10 +0000535
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000536 /* I hate these functions that presume you know how big the output
537 * will be ahead of time...
538 */
539 for (i = 1024; ; i += i) {
540 outbuf = (time_char *)PyMem_Malloc(i*sizeof(time_char));
541 if (outbuf == NULL) {
Victor Stinnerb2904782010-09-29 10:34:19 +0000542 PyErr_NoMemory();
543 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000544 }
545 buflen = format_time(outbuf, i, fmt, &buf);
546 if (buflen > 0 || i >= 256 * fmtlen) {
547 /* If the buffer is 256 times as long as the format,
548 it's probably not failing for lack of room!
549 More likely, the format yields an empty result,
550 e.g. an empty format, or %Z when the timezone
551 is unknown. */
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000552#ifdef HAVE_WCSFTIME
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000553 ret = PyUnicode_FromWideChar(outbuf, buflen);
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000554#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000555 ret = PyUnicode_Decode(outbuf, buflen,
556 TZNAME_ENCODING, NULL);
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000557#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000558 PyMem_Free(outbuf);
Victor Stinnerb2904782010-09-29 10:34:19 +0000559 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000560 }
561 PyMem_Free(outbuf);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000562#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000563 /* VisualStudio .NET 2005 does this properly */
564 if (buflen == 0 && errno == EINVAL) {
565 PyErr_SetString(PyExc_ValueError, "Invalid format string");
Victor Stinnerb2904782010-09-29 10:34:19 +0000566 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000567 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000568#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000569 }
Victor Stinnerb2904782010-09-29 10:34:19 +0000570#ifdef HAVE_WCSFTIME
571 PyMem_Free(format);
572#else
573 Py_DECREF(format);
574#endif
575 return ret;
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000576}
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000577
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000578#undef time_char
579#undef format_time
580
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000581PyDoc_STRVAR(strftime_doc,
Thomas Woutersfe385252001-01-19 23:16:56 +0000582"strftime(format[, tuple]) -> string\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000583\n\
584Convert a time tuple to a string according to a format specification.\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000585See the library reference manual for formatting codes. When the time tuple\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000586is not present, current time as returned by localtime() is used.");
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000587#endif /* HAVE_STRFTIME */
588
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000589static PyObject *
590time_strptime(PyObject *self, PyObject *args)
591{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000592 PyObject *strptime_module = PyImport_ImportModuleNoBlock("_strptime");
593 PyObject *strptime_result;
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000594
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000595 if (!strptime_module)
596 return NULL;
597 strptime_result = PyObject_CallMethod(strptime_module,
598 "_strptime_time", "O", args);
599 Py_DECREF(strptime_module);
600 return strptime_result;
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000601}
602
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000603PyDoc_STRVAR(strptime_doc,
Brett Cannon20def8b2003-07-01 05:16:08 +0000604"strptime(string, format) -> struct_time\n\
Martin v. Löwisb3cfc1d2001-12-02 12:27:43 +0000605\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000606Parse a string to a time tuple according to a format specification.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000607See the library reference manual for formatting codes (same as strftime()).");
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000608
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000609
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000610static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000611time_asctime(PyObject *self, PyObject *args)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000612{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000613 PyObject *tup = NULL;
614 struct tm buf;
615 char *p;
616 if (!PyArg_UnpackTuple(args, "asctime", 0, 1, &tup))
617 return NULL;
618 if (tup == NULL) {
619 time_t tt = time(NULL);
620 buf = *localtime(&tt);
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000621 } else if (!gettmarg(tup, &buf) || !checktm(&buf))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000622 return NULL;
623 p = asctime(&buf);
624 if (p[24] == '\n')
625 p[24] = '\0';
626 return PyUnicode_FromString(p);
Guido van Rossum9e90a671993-06-24 11:10:19 +0000627}
628
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000629PyDoc_STRVAR(asctime_doc,
Thomas Woutersfe385252001-01-19 23:16:56 +0000630"asctime([tuple]) -> string\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000631\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000632Convert a time tuple to a string, e.g. 'Sat Jun 06 16:26:11 1998'.\n\
633When the time tuple is not present, current time as returned by localtime()\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000634is used.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000635
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000636static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000637time_ctime(PyObject *self, PyObject *args)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000638{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000639 PyObject *ot = NULL;
640 time_t tt;
641 char *p;
Guido van Rossum10b164a2001-09-25 13:59:01 +0000642
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000643 if (!PyArg_UnpackTuple(args, "ctime", 0, 1, &ot))
644 return NULL;
645 if (ot == NULL || ot == Py_None)
646 tt = time(NULL);
647 else {
648 double dt = PyFloat_AsDouble(ot);
649 if (PyErr_Occurred())
650 return NULL;
651 tt = _PyTime_DoubleToTimet(dt);
652 if (tt == (time_t)-1 && PyErr_Occurred())
653 return NULL;
654 }
655 p = ctime(&tt);
656 if (p == NULL) {
657 PyErr_SetString(PyExc_ValueError, "unconvertible time");
658 return NULL;
659 }
660 if (p[24] == '\n')
661 p[24] = '\0';
662 return PyUnicode_FromString(p);
Guido van Rossum9e90a671993-06-24 11:10:19 +0000663}
664
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000665PyDoc_STRVAR(ctime_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000666"ctime(seconds) -> string\n\
667\n\
668Convert a time in seconds since the Epoch to a string in local time.\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000669This is equivalent to asctime(localtime(seconds)). When the time tuple is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000670not present, current time as returned by localtime() is used.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000671
Guido van Rossum60cd8131998-03-06 17:16:21 +0000672#ifdef HAVE_MKTIME
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000673static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000674time_mktime(PyObject *self, PyObject *tup)
Guido van Rossum234f9421993-06-17 12:35:49 +0000675{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000676 struct tm buf;
677 time_t tt;
678 if (!gettmarg(tup, &buf))
679 return NULL;
680 tt = mktime(&buf);
681 if (tt == (time_t)(-1)) {
682 PyErr_SetString(PyExc_OverflowError,
683 "mktime argument out of range");
684 return NULL;
685 }
686 return PyFloat_FromDouble((double)tt);
Guido van Rossum234f9421993-06-17 12:35:49 +0000687}
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000688
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000689PyDoc_STRVAR(mktime_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000690"mktime(tuple) -> floating point number\n\
691\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000692Convert a time tuple in local time to seconds since the Epoch.");
Guido van Rossum60cd8131998-03-06 17:16:21 +0000693#endif /* HAVE_MKTIME */
Guido van Rossum234f9421993-06-17 12:35:49 +0000694
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000695#ifdef HAVE_WORKING_TZSET
Martin v. Löwis1a214512008-06-11 05:26:20 +0000696static void PyInit_timezone(PyObject *module);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000697
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000698static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000699time_tzset(PyObject *self, PyObject *unused)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000700{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000701 PyObject* m;
Fred Drake9bb74322002-04-01 14:49:59 +0000702
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000703 m = PyImport_ImportModuleNoBlock("time");
704 if (m == NULL) {
705 return NULL;
706 }
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000707
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000708 tzset();
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000709
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000710 /* Reset timezone, altzone, daylight and tzname */
711 PyInit_timezone(m);
712 Py_DECREF(m);
Tim Peters1b6f7a92004-06-20 02:50:16 +0000713
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000714 Py_INCREF(Py_None);
715 return Py_None;
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000716}
717
718PyDoc_STRVAR(tzset_doc,
719"tzset(zone)\n\
720\n\
721Initialize, or reinitialize, the local timezone to the value stored in\n\
722os.environ['TZ']. The TZ environment variable should be specified in\n\
Neal Norwitzdc8e1942004-07-20 22:34:37 +0000723standard Unix timezone format as documented in the tzset man page\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000724(eg. 'US/Eastern', 'Europe/Amsterdam'). Unknown timezones will silently\n\
725fall back to UTC. If the TZ environment variable is not set, the local\n\
726timezone is set to the systems best guess of wallclock time.\n\
727Changing the TZ environment variable without calling tzset *may* change\n\
728the local timezone used by methods such as localtime, but this behaviour\n\
729should not be relied on.");
730#endif /* HAVE_WORKING_TZSET */
731
Martin v. Löwisd218dc12008-04-07 03:17:54 +0000732static void
Martin v. Löwis1a214512008-06-11 05:26:20 +0000733PyInit_timezone(PyObject *m) {
734 /* This code moved from PyInit_time wholesale to allow calling it from
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000735 time_tzset. In the future, some parts of it can be moved back
736 (for platforms that don't HAVE_WORKING_TZSET, when we know what they
737 are), and the extraneous calls to tzset(3) should be removed.
738 I haven't done this yet, as I don't want to change this code as
739 little as possible when introducing the time.tzset and time.tzsetwall
740 methods. This should simply be a method of doing the following once,
741 at the top of this function and removing the call to tzset() from
742 time_tzset():
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000743
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000744 #ifdef HAVE_TZSET
745 tzset()
746 #endif
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000747
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000748 And I'm lazy and hate C so nyer.
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000749 */
Guido van Rossum10b164a2001-09-25 13:59:01 +0000750#if defined(HAVE_TZNAME) && !defined(__GLIBC__) && !defined(__CYGWIN__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000751 PyObject *otz0, *otz1;
752 tzset();
Guido van Rossum26452411998-09-28 22:07:11 +0000753#ifdef PYOS_OS2
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000754 PyModule_AddIntConstant(m, "timezone", _timezone);
Guido van Rossum26452411998-09-28 22:07:11 +0000755#else /* !PYOS_OS2 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000756 PyModule_AddIntConstant(m, "timezone", timezone);
Guido van Rossum26452411998-09-28 22:07:11 +0000757#endif /* PYOS_OS2 */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000758#ifdef HAVE_ALTZONE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000759 PyModule_AddIntConstant(m, "altzone", altzone);
Guido van Rossumb6775db1994-08-01 11:34:53 +0000760#else
Guido van Rossum26452411998-09-28 22:07:11 +0000761#ifdef PYOS_OS2
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000762 PyModule_AddIntConstant(m, "altzone", _timezone-3600);
Guido van Rossum26452411998-09-28 22:07:11 +0000763#else /* !PYOS_OS2 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000764 PyModule_AddIntConstant(m, "altzone", timezone-3600);
Guido van Rossum26452411998-09-28 22:07:11 +0000765#endif /* PYOS_OS2 */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000766#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000767 PyModule_AddIntConstant(m, "daylight", daylight);
768 otz0 = PyUnicode_Decode(tzname[0], strlen(tzname[0]), TZNAME_ENCODING, NULL);
769 otz1 = PyUnicode_Decode(tzname[1], strlen(tzname[1]), TZNAME_ENCODING, NULL);
770 PyModule_AddObject(m, "tzname", Py_BuildValue("(NN)", otz0, otz1));
Guido van Rossum10b164a2001-09-25 13:59:01 +0000771#else /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/
Martin v. Löwis60a5d722002-10-16 20:28:25 +0000772#ifdef HAVE_STRUCT_TM_TM_ZONE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000773 {
Guido van Rossum234f9421993-06-17 12:35:49 +0000774#define YEAR ((time_t)((365 * 24 + 6) * 3600))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000775 time_t t;
776 struct tm *p;
777 long janzone, julyzone;
778 char janname[10], julyname[10];
779 t = (time((time_t *)0) / YEAR) * YEAR;
780 p = localtime(&t);
781 janzone = -p->tm_gmtoff;
782 strncpy(janname, p->tm_zone ? p->tm_zone : " ", 9);
783 janname[9] = '\0';
784 t += YEAR/2;
785 p = localtime(&t);
786 julyzone = -p->tm_gmtoff;
787 strncpy(julyname, p->tm_zone ? p->tm_zone : " ", 9);
788 julyname[9] = '\0';
Guido van Rossum10b164a2001-09-25 13:59:01 +0000789
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000790 if( janzone < julyzone ) {
791 /* DST is reversed in the southern hemisphere */
792 PyModule_AddIntConstant(m, "timezone", julyzone);
793 PyModule_AddIntConstant(m, "altzone", janzone);
794 PyModule_AddIntConstant(m, "daylight",
795 janzone != julyzone);
796 PyModule_AddObject(m, "tzname",
797 Py_BuildValue("(zz)",
798 julyname, janname));
799 } else {
800 PyModule_AddIntConstant(m, "timezone", janzone);
801 PyModule_AddIntConstant(m, "altzone", julyzone);
802 PyModule_AddIntConstant(m, "daylight",
803 janzone != julyzone);
804 PyModule_AddObject(m, "tzname",
805 Py_BuildValue("(zz)",
806 janname, julyname));
807 }
808 }
Guido van Rossume6a4b7b1997-10-08 15:27:56 +0000809#else
Martin v. Löwis60a5d722002-10-16 20:28:25 +0000810#endif /* HAVE_STRUCT_TM_TM_ZONE */
Tim Peters26ae7cd2001-03-20 03:26:49 +0000811#ifdef __CYGWIN__
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000812 tzset();
813 PyModule_AddIntConstant(m, "timezone", _timezone);
814 PyModule_AddIntConstant(m, "altzone", _timezone-3600);
815 PyModule_AddIntConstant(m, "daylight", _daylight);
816 PyModule_AddObject(m, "tzname",
817 Py_BuildValue("(zz)", _tzname[0], _tzname[1]));
Tim Peters26ae7cd2001-03-20 03:26:49 +0000818#endif /* __CYGWIN__ */
Guido van Rossum10b164a2001-09-25 13:59:01 +0000819#endif /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000820}
821
822
823static PyMethodDef time_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000824 {"time", time_time, METH_NOARGS, time_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000825#ifdef HAVE_CLOCK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000826 {"clock", time_clock, METH_NOARGS, clock_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000827#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000828 {"sleep", time_sleep, METH_VARARGS, sleep_doc},
829 {"gmtime", time_gmtime, METH_VARARGS, gmtime_doc},
830 {"localtime", time_localtime, METH_VARARGS, localtime_doc},
831 {"asctime", time_asctime, METH_VARARGS, asctime_doc},
832 {"ctime", time_ctime, METH_VARARGS, ctime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000833#ifdef HAVE_MKTIME
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000834 {"mktime", time_mktime, METH_O, mktime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000835#endif
836#ifdef HAVE_STRFTIME
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000837 {"strftime", time_strftime, METH_VARARGS, strftime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000838#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000839 {"strptime", time_strptime, METH_VARARGS, strptime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000840#ifdef HAVE_WORKING_TZSET
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000841 {"tzset", time_tzset, METH_NOARGS, tzset_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000842#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000843 {NULL, NULL} /* sentinel */
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000844};
845
846
847PyDoc_STRVAR(module_doc,
848"This module provides various functions to manipulate time values.\n\
849\n\
850There are two standard representations of time. One is the number\n\
851of seconds since the Epoch, in UTC (a.k.a. GMT). It may be an integer\n\
852or a floating point number (to represent fractions of seconds).\n\
853The Epoch is system-defined; on Unix, it is generally January 1st, 1970.\n\
854The actual value can be retrieved by calling gmtime(0).\n\
855\n\
856The other representation is a tuple of 9 integers giving local time.\n\
857The tuple items are:\n\
858 year (four digits, e.g. 1998)\n\
859 month (1-12)\n\
860 day (1-31)\n\
861 hours (0-23)\n\
862 minutes (0-59)\n\
863 seconds (0-59)\n\
864 weekday (0-6, Monday is 0)\n\
865 Julian day (day in the year, 1-366)\n\
866 DST (Daylight Savings Time) flag (-1, 0 or 1)\n\
867If the DST flag is 0, the time is given in the regular time zone;\n\
868if it is 1, the time is given in the DST time zone;\n\
869if it is -1, mktime() should guess based on the date and time.\n\
870\n\
871Variables:\n\
872\n\
873timezone -- difference in seconds between UTC and local standard time\n\
874altzone -- difference in seconds between UTC and local DST time\n\
875daylight -- whether local time should reflect DST\n\
876tzname -- tuple of (standard time zone name, DST time zone name)\n\
877\n\
878Functions:\n\
879\n\
880time() -- return current time in seconds since the Epoch as a float\n\
881clock() -- return CPU time since process start as a float\n\
882sleep() -- delay for a number of seconds given as a float\n\
883gmtime() -- convert seconds since Epoch to UTC tuple\n\
884localtime() -- convert seconds since Epoch to local time tuple\n\
885asctime() -- convert time tuple to string\n\
886ctime() -- convert time in seconds to string\n\
887mktime() -- convert local time tuple to seconds since Epoch\n\
888strftime() -- convert time tuple to string according to format specification\n\
889strptime() -- parse string to time tuple according to format specification\n\
890tzset() -- change the local timezone");
891
892
Martin v. Löwis1a214512008-06-11 05:26:20 +0000893
894static struct PyModuleDef timemodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000895 PyModuleDef_HEAD_INIT,
896 "time",
897 module_doc,
898 -1,
899 time_methods,
900 NULL,
901 NULL,
902 NULL,
903 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +0000904};
905
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000906PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +0000907PyInit_time(void)
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000908{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000909 PyObject *m;
910 char *p;
911 m = PyModule_Create(&timemodule);
912 if (m == NULL)
913 return NULL;
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000914
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000915 /* Accept 2-digit dates unless PYTHONY2K is set and non-empty */
916 p = Py_GETENV("PYTHONY2K");
917 PyModule_AddIntConstant(m, "accept2dyear", (long) (!p || !*p));
918 /* Squirrel away the module's dictionary for the y2k check */
919 moddict = PyModule_GetDict(m);
920 Py_INCREF(moddict);
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000921
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000922 /* Set, or reset, module variables like time.timezone */
923 PyInit_timezone(m);
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000924
Mark Hammond975e3922002-07-16 01:29:19 +0000925#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000926 /* Helper to allow interrupts for Windows.
927 If Ctrl+C event delivered while not sleeping
928 it will be ignored.
929 */
930 main_thread = PyThread_get_thread_ident();
931 hInterruptEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
932 SetConsoleCtrlHandler( PyCtrlHandler, TRUE);
Mark Hammond975e3922002-07-16 01:29:19 +0000933#endif /* MS_WINDOWS */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000934 if (!initialized) {
935 PyStructSequence_InitType(&StructTimeType,
936 &struct_time_type_desc);
937 }
938 Py_INCREF(&StructTimeType);
939 PyModule_AddObject(m, "struct_time", (PyObject*) &StructTimeType);
940 initialized = 1;
941 return m;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000942}
943
Guido van Rossumb6775db1994-08-01 11:34:53 +0000944static double
Thomas Woutersf3f33dc2000-07-21 06:00:07 +0000945floattime(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000946{
Alexander Belopolsky6fc4ade2010-08-05 17:34:27 +0000947 _PyTime_timeval t;
948 _PyTime_gettimeofday(&t);
949 return (double)t.tv_sec + t.tv_usec*0.000001;
Guido van Rossum426035c1991-02-19 12:27:35 +0000950}
951
Guido van Rossumb6775db1994-08-01 11:34:53 +0000952
953/* Implement floatsleep() for various platforms.
954 When interrupted (or when another error occurs), return -1 and
955 set an exception; else return 0. */
956
957static int
Guido van Rossuma320fd31995-03-09 12:14:15 +0000958floatsleep(double secs)
Guido van Rossum426035c1991-02-19 12:27:35 +0000959{
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000960/* XXX Should test for MS_WINDOWS first! */
Skip Montanaroeb33e5a2007-08-17 12:57:41 +0000961#if defined(HAVE_SELECT) && !defined(__EMX__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000962 struct timeval t;
963 double frac;
964 frac = fmod(secs, 1.0);
965 secs = floor(secs);
966 t.tv_sec = (long)secs;
967 t.tv_usec = (long)(frac*1000000.0);
968 Py_BEGIN_ALLOW_THREADS
969 if (select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &t) != 0) {
Guido van Rossum09cbb011999-11-08 15:32:27 +0000970#ifdef EINTR
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000971 if (errno != EINTR) {
Guido van Rossum09cbb011999-11-08 15:32:27 +0000972#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000973 if (1) {
Guido van Rossum09cbb011999-11-08 15:32:27 +0000974#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000975 Py_BLOCK_THREADS
976 PyErr_SetFromErrno(PyExc_IOError);
977 return -1;
978 }
979 }
980 Py_END_ALLOW_THREADS
Martin v. Löwis02af9642002-01-16 11:04:06 +0000981#elif defined(__WATCOMC__) && !defined(__QNX__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000982 /* XXX Can't interrupt this sleep */
983 Py_BEGIN_ALLOW_THREADS
984 delay((int)(secs * 1000 + 0.5)); /* delay() uses milliseconds */
985 Py_END_ALLOW_THREADS
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000986#elif defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000987 {
988 double millisecs = secs * 1000.0;
989 unsigned long ul_millis;
Tim Peters513a1cd2003-01-19 04:54:58 +0000990
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000991 if (millisecs > (double)ULONG_MAX) {
992 PyErr_SetString(PyExc_OverflowError,
993 "sleep length is too large");
994 return -1;
995 }
996 Py_BEGIN_ALLOW_THREADS
997 /* Allow sleep(0) to maintain win32 semantics, and as decreed
998 * by Guido, only the main thread can be interrupted.
999 */
1000 ul_millis = (unsigned long)millisecs;
1001 if (ul_millis == 0 ||
1002 main_thread != PyThread_get_thread_ident())
1003 Sleep(ul_millis);
1004 else {
1005 DWORD rc;
1006 ResetEvent(hInterruptEvent);
1007 rc = WaitForSingleObject(hInterruptEvent, ul_millis);
1008 if (rc == WAIT_OBJECT_0) {
1009 /* Yield to make sure real Python signal
1010 * handler called.
1011 */
1012 Sleep(1);
1013 Py_BLOCK_THREADS
1014 errno = EINTR;
1015 PyErr_SetFromErrno(PyExc_IOError);
1016 return -1;
1017 }
1018 }
1019 Py_END_ALLOW_THREADS
1020 }
Martin v. Löwis02af9642002-01-16 11:04:06 +00001021#elif defined(PYOS_OS2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001022 /* This Sleep *IS* Interruptable by Exceptions */
1023 Py_BEGIN_ALLOW_THREADS
1024 if (DosSleep(secs * 1000) != NO_ERROR) {
1025 Py_BLOCK_THREADS
1026 PyErr_SetFromErrno(PyExc_IOError);
1027 return -1;
1028 }
1029 Py_END_ALLOW_THREADS
Martin v. Löwis02af9642002-01-16 11:04:06 +00001030#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001031 /* XXX Can't interrupt this sleep */
1032 Py_BEGIN_ALLOW_THREADS
1033 sleep((int)secs);
1034 Py_END_ALLOW_THREADS
Martin v. Löwis02af9642002-01-16 11:04:06 +00001035#endif
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001036
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001037 return 0;
Guido van Rossum80c9d881991-04-16 08:47:51 +00001038}