blob: 85614a6e5811b22fbc54272fe8ff496af6d1abfc [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
Guido van Rossum87ce7bb1998-06-09 16:30:31 +00006#include <ctype.h>
7
Thomas Wouters0e3f5912006-08-11 14:57:12 +00008#ifdef HAVE_SYS_TYPES_H
Guido van Rossumb6775db1994-08-01 11:34:53 +00009#include <sys/types.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +000010#endif /* HAVE_SYS_TYPES_H */
Guido van Rossum6d946f91992-08-14 13:49:30 +000011
Guido van Rossumb6775db1994-08-01 11:34:53 +000012#ifdef QUICKWIN
13#include <io.h>
14#endif
15
Guido van Rossum7bf22de1997-12-02 20:34:19 +000016#if defined(__WATCOMC__) && !defined(__QNX__)
Guido van Rossumbceeac81996-05-23 22:53:47 +000017#include <i86.h>
18#else
Guido van Rossumcac6c721996-09-06 13:34:02 +000019#ifdef MS_WINDOWS
Mark Hammond975e3922002-07-16 01:29:19 +000020#define WIN32_LEAN_AND_MEAN
Guido van Rossum258ccd42001-03-02 06:53:29 +000021#include <windows.h>
Mark Hammond975e3922002-07-16 01:29:19 +000022#include "pythread.h"
23
24/* helper to allow us to interrupt sleep() on Windows*/
25static HANDLE hInterruptEvent = NULL;
26static BOOL WINAPI PyCtrlHandler(DWORD dwCtrlType)
27{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000028 SetEvent(hInterruptEvent);
29 /* allow other default handlers to be called.
30 Default Python handler will setup the
31 KeyboardInterrupt exception.
32 */
33 return FALSE;
Mark Hammond975e3922002-07-16 01:29:19 +000034}
35static long main_thread;
36
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000037#if defined(__BORLANDC__)
Guido van Rossumb2fb3641996-09-07 00:47:35 +000038/* These overrides not needed for Win32 */
Guido van Rossumb6775db1994-08-01 11:34:53 +000039#define timezone _timezone
Guido van Rossumcc081121995-03-14 15:05:41 +000040#define tzname _tzname
41#define daylight _daylight
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000042#endif /* __BORLANDC__ */
Guido van Rossumcac6c721996-09-06 13:34:02 +000043#endif /* MS_WINDOWS */
Guido van Rossum7bf22de1997-12-02 20:34:19 +000044#endif /* !__WATCOMC__ || __QNX__ */
Guido van Rossum234f9421993-06-17 12:35:49 +000045
Victor Stinner99b95382011-07-04 14:23:54 +020046#if defined(HAVE_MBCS)
Victor Stinner9122fdd2011-07-04 13:55:40 +020047# define TZNAME_ENCODING "mbcs"
48#else
49# define TZNAME_ENCODING "utf-8"
50#endif
Guido van Rossum3917c221997-04-02 05:35:28 +000051
Andrew MacIntyre7bf68332002-03-03 02:59:16 +000052#if defined(PYOS_OS2)
53#define INCL_DOS
54#define INCL_ERRORS
55#include <os2.h>
56#endif
57
Guido van Rossum8e9ebfd1997-11-22 21:53:48 +000058#if defined(PYCC_VACPP)
Guido van Rossum26452411998-09-28 22:07:11 +000059#include <sys/time.h>
Guido van Rossum8e9ebfd1997-11-22 21:53:48 +000060#endif
61
Guido van Rossum234f9421993-06-17 12:35:49 +000062/* Forward declarations */
Tim Petersdbd9ba62000-07-09 03:09:57 +000063static int floatsleep(double);
Thomas Woutersed77bac2000-07-24 15:26:39 +000064static double floattime(void);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000065
Barry Warsaw9a2a8a81996-12-06 23:32:14 +000066static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000067time_time(PyObject *self, PyObject *unused)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000068{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000069 double secs;
70 secs = floattime();
71 if (secs == 0.0) {
72 PyErr_SetFromErrno(PyExc_IOError);
73 return NULL;
74 }
75 return PyFloat_FromDouble(secs);
Guido van Rossumb6775db1994-08-01 11:34:53 +000076}
77
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000078PyDoc_STRVAR(time_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +000079"time() -> floating point number\n\
80\n\
81Return the current time in seconds since the Epoch.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000082Fractions of a second may be present if the system clock provides them.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +000083
Thomas Wouters477c8d52006-05-27 19:21:47 +000084#if defined(MS_WINDOWS) && !defined(__BORLANDC__)
Victor Stinner9122fdd2011-07-04 13:55:40 +020085/* Win32 has better clock replacement; we have our own version, due to Mark
86 Hammond and Tim Peters */
Guido van Rossum3917c221997-04-02 05:35:28 +000087static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000088time_clock(PyObject *self, PyObject *unused)
Guido van Rossum3917c221997-04-02 05:35:28 +000089{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000090 static LARGE_INTEGER ctrStart;
91 static double divisor = 0.0;
92 LARGE_INTEGER now;
93 double diff;
Guido van Rossum3917c221997-04-02 05:35:28 +000094
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000095 if (divisor == 0.0) {
96 LARGE_INTEGER freq;
97 QueryPerformanceCounter(&ctrStart);
98 if (!QueryPerformanceFrequency(&freq) || freq.QuadPart == 0) {
99 /* Unlikely to happen - this works on all intel
100 machines at least! Revert to clock() */
101 return PyFloat_FromDouble(((double)clock()) /
102 CLOCKS_PER_SEC);
103 }
104 divisor = (double)freq.QuadPart;
105 }
106 QueryPerformanceCounter(&now);
107 diff = (double)(now.QuadPart - ctrStart.QuadPart);
108 return PyFloat_FromDouble(diff / divisor);
Guido van Rossum3917c221997-04-02 05:35:28 +0000109}
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000110
Victor Stinner9122fdd2011-07-04 13:55:40 +0200111#elif defined(HAVE_CLOCK)
112
113#ifndef CLOCKS_PER_SEC
114#ifdef CLK_TCK
115#define CLOCKS_PER_SEC CLK_TCK
116#else
117#define CLOCKS_PER_SEC 1000000
118#endif
119#endif
120
121static PyObject *
122time_clock(PyObject *self, PyObject *unused)
123{
124 return PyFloat_FromDouble(((double)clock()) / CLOCKS_PER_SEC);
125}
126#endif /* HAVE_CLOCK */
127
Guido van Rossum3917c221997-04-02 05:35:28 +0000128
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000129#ifdef HAVE_CLOCK
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000130PyDoc_STRVAR(clock_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000131"clock() -> floating point number\n\
132\n\
133Return the CPU time or real time since the start of the process or since\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000134the first call to clock(). This has as much precision as the system\n\
135records.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000136#endif
137
Victor Stinnere0be4232011-10-25 13:06:09 +0200138#ifdef HAVE_CLOCK_GETTIME
139static PyObject *
140time_clock_gettime(PyObject *self, PyObject *args)
141{
142 int ret;
143 clockid_t clk_id;
144 struct timespec tp;
145
146 if (!PyArg_ParseTuple(args, "i:clock_gettime", &clk_id))
147 return NULL;
148
149 ret = clock_gettime((clockid_t)clk_id, &tp);
150 if (ret != 0)
151 PyErr_SetFromErrno(PyExc_IOError);
152
153 return PyFloat_FromDouble(tp.tv_sec + tp.tv_nsec * 1e-9);
154}
155
156PyDoc_STRVAR(clock_gettime_doc,
157"clock_gettime(clk_id) -> floating point number\n\
158\n\
159Return the time of the specified clock clk_id.");
160#endif
161
162#ifdef HAVE_CLOCK_GETRES
163static PyObject *
164time_clock_getres(PyObject *self, PyObject *args)
165{
166 int ret;
167 clockid_t clk_id;
168 struct timespec tp;
169
170 if (!PyArg_ParseTuple(args, "i:clock_getres", &clk_id))
171 return NULL;
172
173 ret = clock_getres((clockid_t)clk_id, &tp);
174 if (ret != 0)
175 PyErr_SetFromErrno(PyExc_IOError);
176
177 return PyFloat_FromDouble(tp.tv_sec + tp.tv_nsec * 1e-9);
178}
179
180PyDoc_STRVAR(clock_getres_doc,
181"clock_getres(clk_id) -> floating point number\n\
182\n\
183Return the resolution (precision) of the specified clock clk_id.");
184#endif
185
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000186static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000187time_sleep(PyObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000188{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000189 double secs;
190 if (!PyArg_ParseTuple(args, "d:sleep", &secs))
191 return NULL;
Victor Stinner7f53a502011-07-05 22:00:25 +0200192 if (secs < 0) {
193 PyErr_SetString(PyExc_ValueError,
194 "sleep length must be non-negative");
195 return NULL;
196 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000197 if (floatsleep(secs) != 0)
198 return NULL;
199 Py_INCREF(Py_None);
200 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000201}
202
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000203PyDoc_STRVAR(sleep_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000204"sleep(seconds)\n\
205\n\
206Delay execution for a given number of seconds. The argument may be\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000207a floating point number for subsecond precision.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000208
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000209static PyStructSequence_Field struct_time_type_fields[] = {
Alexander Belopolsky69f3fd02010-06-05 15:04:51 +0000210 {"tm_year", "year, for example, 1993"},
211 {"tm_mon", "month of year, range [1, 12]"},
212 {"tm_mday", "day of month, range [1, 31]"},
213 {"tm_hour", "hours, range [0, 23]"},
214 {"tm_min", "minutes, range [0, 59]"},
215 {"tm_sec", "seconds, range [0, 61])"},
216 {"tm_wday", "day of week, range [0, 6], Monday is 0"},
217 {"tm_yday", "day of year, range [1, 366]"},
218 {"tm_isdst", "1 if summer time is in effect, 0 if not, and -1 if unknown"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000219 {0}
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000220};
221
222static PyStructSequence_Desc struct_time_type_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000223 "time.struct_time",
Alexander Belopolsky69f3fd02010-06-05 15:04:51 +0000224 "The time value as returned by gmtime(), localtime(), and strptime(), and\n"
225 " accepted by asctime(), mktime() and strftime(). May be considered as a\n"
226 " sequence of 9 integers.\n\n"
227 " Note that several fields' values are not the same as those defined by\n"
228 " the C language standard for struct tm. For example, the value of the\n"
229 " field tm_year is the actual year, not year - 1900. See individual\n"
230 " fields' descriptions for details.",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000231 struct_time_type_fields,
232 9,
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000233};
Tim Peters9ad4b682002-02-13 05:14:18 +0000234
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000235static int initialized;
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000236static PyTypeObject StructTimeType;
237
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000238static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000239tmtotuple(struct tm *p)
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000240{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000241 PyObject *v = PyStructSequence_New(&StructTimeType);
242 if (v == NULL)
243 return NULL;
Tim Peters9ad4b682002-02-13 05:14:18 +0000244
Christian Heimes217cfd12007-12-02 14:31:20 +0000245#define SET(i,val) PyStructSequence_SET_ITEM(v, i, PyLong_FromLong((long) val))
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000246
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000247 SET(0, p->tm_year + 1900);
248 SET(1, p->tm_mon + 1); /* Want January == 1 */
249 SET(2, p->tm_mday);
250 SET(3, p->tm_hour);
251 SET(4, p->tm_min);
252 SET(5, p->tm_sec);
253 SET(6, (p->tm_wday + 6) % 7); /* Want Monday == 0 */
254 SET(7, p->tm_yday + 1); /* Want January, 1 == 1 */
255 SET(8, p->tm_isdst);
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000256#undef SET
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000257 if (PyErr_Occurred()) {
258 Py_XDECREF(v);
259 return NULL;
260 }
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000261
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000262 return v;
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000263}
264
265static PyObject *
Brett Cannon298c3802004-06-19 20:48:43 +0000266time_convert(double when, struct tm * (*function)(const time_t *))
Guido van Rossum234f9421993-06-17 12:35:49 +0000267{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000268 struct tm *p;
269 time_t whent = _PyTime_DoubleToTimet(when);
Brett Cannon298c3802004-06-19 20:48:43 +0000270
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000271 if (whent == (time_t)-1 && PyErr_Occurred())
272 return NULL;
273 errno = 0;
274 p = function(&whent);
275 if (p == NULL) {
Guido van Rossum6e8583d1996-10-08 14:19:52 +0000276#ifdef EINVAL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000277 if (errno == 0)
278 errno = EINVAL;
Guido van Rossum6e8583d1996-10-08 14:19:52 +0000279#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000280 return PyErr_SetFromErrno(PyExc_ValueError);
281 }
282 return tmtotuple(p);
Guido van Rossum234f9421993-06-17 12:35:49 +0000283}
284
Fred Drakef901abd2004-08-03 17:58:55 +0000285/* Parse arg tuple that can contain an optional float-or-None value;
286 format needs to be "|O:name".
287 Returns non-zero on success (parallels PyArg_ParseTuple).
288*/
289static int
290parse_time_double_args(PyObject *args, char *format, double *pwhen)
291{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000292 PyObject *ot = NULL;
Fred Drakef901abd2004-08-03 17:58:55 +0000293
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000294 if (!PyArg_ParseTuple(args, format, &ot))
295 return 0;
296 if (ot == NULL || ot == Py_None)
297 *pwhen = floattime();
298 else {
299 double when = PyFloat_AsDouble(ot);
300 if (PyErr_Occurred())
301 return 0;
302 *pwhen = when;
303 }
304 return 1;
Fred Drakef901abd2004-08-03 17:58:55 +0000305}
306
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000307static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000308time_gmtime(PyObject *self, PyObject *args)
Guido van Rossum234f9421993-06-17 12:35:49 +0000309{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000310 double when;
311 if (!parse_time_double_args(args, "|O:gmtime", &when))
312 return NULL;
313 return time_convert(when, gmtime);
Guido van Rossum234f9421993-06-17 12:35:49 +0000314}
315
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000316PyDoc_STRVAR(gmtime_doc,
Christian Heimes9a371592007-12-28 14:08:13 +0000317"gmtime([seconds]) -> (tm_year, tm_mon, tm_mday, tm_hour, tm_min,\n\
Fred Drake193a3f62002-03-12 21:38:49 +0000318 tm_sec, tm_wday, tm_yday, tm_isdst)\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000319\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000320Convert seconds since the Epoch to a time tuple expressing UTC (a.k.a.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000321GMT). When 'seconds' is not passed in, convert the current time instead.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000322
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000323static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000324time_localtime(PyObject *self, PyObject *args)
Guido van Rossum234f9421993-06-17 12:35:49 +0000325{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000326 double when;
327 if (!parse_time_double_args(args, "|O:localtime", &when))
328 return NULL;
329 return time_convert(when, localtime);
Guido van Rossum234f9421993-06-17 12:35:49 +0000330}
331
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000332PyDoc_STRVAR(localtime_doc,
Christian Heimes9a371592007-12-28 14:08:13 +0000333"localtime([seconds]) -> (tm_year,tm_mon,tm_mday,tm_hour,tm_min,\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000334 tm_sec,tm_wday,tm_yday,tm_isdst)\n\
Martin v. Löwisb3cfc1d2001-12-02 12:27:43 +0000335\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000336Convert seconds since the Epoch to a time tuple expressing local time.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000337When 'seconds' is not passed in, convert the current time instead.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000338
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000339/* Convert 9-item tuple to tm structure. Return 1 on success, set
340 * an exception and return 0 on error.
341 */
Guido van Rossum9e90a671993-06-24 11:10:19 +0000342static int
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000343gettmarg(PyObject *args, struct tm *p)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000344{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000345 int y;
Guido van Rossumcfbaecc1998-08-25 14:51:12 +0000346
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000347 memset((void *) p, '\0', sizeof(struct tm));
Guido van Rossumb9081262007-08-25 03:14:09 +0000348
Alexander Belopolsky610e5442011-01-06 21:57:06 +0000349 if (!PyTuple_Check(args)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000350 PyErr_SetString(PyExc_TypeError,
351 "Tuple or struct_time argument required");
352 return 0;
353 }
Skip Montanaro41cfce92007-08-24 21:11:00 +0000354
Alexander Belopolsky610e5442011-01-06 21:57:06 +0000355 if (!PyArg_ParseTuple(args, "iiiiiiiii",
356 &y, &p->tm_mon, &p->tm_mday,
357 &p->tm_hour, &p->tm_min, &p->tm_sec,
358 &p->tm_wday, &p->tm_yday, &p->tm_isdst))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000359 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000360 p->tm_year = y - 1900;
361 p->tm_mon--;
362 p->tm_wday = (p->tm_wday + 1) % 7;
363 p->tm_yday--;
364 return 1;
Guido van Rossum9e90a671993-06-24 11:10:19 +0000365}
366
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000367/* Check values of the struct tm fields before it is passed to strftime() and
368 * asctime(). Return 1 if all values are valid, otherwise set an exception
369 * and returns 0.
370 */
Victor Stinneref128102010-10-07 01:00:52 +0000371static int
372checktm(struct tm* buf)
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000373{
Victor Stinneref128102010-10-07 01:00:52 +0000374 /* Checks added to make sure strftime() and asctime() does not crash Python by
375 indexing blindly into some array for a textual representation
376 by some bad index (fixes bug #897625 and #6608).
377
378 Also support values of zero from Python code for arguments in which
379 that is out of range by forcing that value to the lowest value that
380 is valid (fixed bug #1520914).
381
382 Valid ranges based on what is allowed in struct tm:
383
384 - tm_year: [0, max(int)] (1)
385 - tm_mon: [0, 11] (2)
386 - tm_mday: [1, 31]
387 - tm_hour: [0, 23]
388 - tm_min: [0, 59]
389 - tm_sec: [0, 60]
390 - tm_wday: [0, 6] (1)
391 - tm_yday: [0, 365] (2)
392 - tm_isdst: [-max(int), max(int)]
393
394 (1) gettmarg() handles bounds-checking.
395 (2) Python's acceptable range is one greater than the range in C,
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000396 thus need to check against automatic decrement by gettmarg().
397 */
398 if (buf->tm_mon == -1)
399 buf->tm_mon = 0;
400 else if (buf->tm_mon < 0 || buf->tm_mon > 11) {
401 PyErr_SetString(PyExc_ValueError, "month out of range");
402 return 0;
403 }
404 if (buf->tm_mday == 0)
405 buf->tm_mday = 1;
406 else if (buf->tm_mday < 0 || buf->tm_mday > 31) {
407 PyErr_SetString(PyExc_ValueError, "day of month out of range");
408 return 0;
409 }
410 if (buf->tm_hour < 0 || buf->tm_hour > 23) {
411 PyErr_SetString(PyExc_ValueError, "hour out of range");
412 return 0;
413 }
414 if (buf->tm_min < 0 || buf->tm_min > 59) {
415 PyErr_SetString(PyExc_ValueError, "minute out of range");
416 return 0;
417 }
418 if (buf->tm_sec < 0 || buf->tm_sec > 61) {
419 PyErr_SetString(PyExc_ValueError, "seconds out of range");
420 return 0;
421 }
422 /* tm_wday does not need checking of its upper-bound since taking
423 ``% 7`` in gettmarg() automatically restricts the range. */
424 if (buf->tm_wday < 0) {
425 PyErr_SetString(PyExc_ValueError, "day of week out of range");
426 return 0;
427 }
428 if (buf->tm_yday == -1)
429 buf->tm_yday = 0;
430 else if (buf->tm_yday < 0 || buf->tm_yday > 365) {
431 PyErr_SetString(PyExc_ValueError, "day of year out of range");
432 return 0;
433 }
434 return 1;
435}
436
Victor Stinnerc1f32ca2011-10-14 02:36:13 +0200437#ifdef MS_WINDOWS
438 /* wcsftime() doesn't format correctly time zones, see issue #10653 */
439# undef HAVE_WCSFTIME
440#endif
441
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000442#ifdef HAVE_STRFTIME
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000443#ifdef HAVE_WCSFTIME
444#define time_char wchar_t
445#define format_time wcsftime
446#define time_strlen wcslen
447#else
448#define time_char char
449#define format_time strftime
450#define time_strlen strlen
451#endif
452
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000453static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000454time_strftime(PyObject *self, PyObject *args)
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000455{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000456 PyObject *tup = NULL;
457 struct tm buf;
458 const time_char *fmt;
Victor Stinnerb2904782010-09-29 10:34:19 +0000459#ifdef HAVE_WCSFTIME
460 wchar_t *format;
461#else
462 PyObject *format;
463#endif
Victor Stinneref128102010-10-07 01:00:52 +0000464 PyObject *format_arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000465 size_t fmtlen, buflen;
Victor Stinnerb2904782010-09-29 10:34:19 +0000466 time_char *outbuf = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000467 size_t i;
Victor Stinnerb2904782010-09-29 10:34:19 +0000468 PyObject *ret = NULL;
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000469
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000470 memset((void *) &buf, '\0', sizeof(buf));
Guido van Rossum1f41f841998-04-27 19:04:26 +0000471
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000472 /* Will always expect a unicode string to be passed as format.
473 Given that there's no str type anymore in py3k this seems safe.
474 */
Victor Stinneref128102010-10-07 01:00:52 +0000475 if (!PyArg_ParseTuple(args, "U|O:strftime", &format_arg, &tup))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000476 return NULL;
Thomas Woutersfe385252001-01-19 23:16:56 +0000477
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000478 if (tup == NULL) {
479 time_t tt = time(NULL);
480 buf = *localtime(&tt);
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000481 }
482 else if (!gettmarg(tup, &buf) || !checktm(&buf))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000483 return NULL;
Guido van Rossum10b164a2001-09-25 13:59:01 +0000484
Victor Stinner06ec45e2011-01-08 03:35:36 +0000485#if defined(_MSC_VER) || defined(sun)
Victor Stinner73ea29c2011-01-08 01:56:31 +0000486 if (buf.tm_year + 1900 < 1 || 9999 < buf.tm_year + 1900) {
Victor Stinner6f0e4f92011-03-21 02:14:53 +0100487 PyErr_SetString(PyExc_ValueError,
488 "strftime() requires year in [1; 9999]");
Alexander Belopolsky0dd06f42011-01-08 01:23:02 +0000489 return NULL;
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000490 }
Victor Stinner73ea29c2011-01-08 01:56:31 +0000491#endif
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000492
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000493 /* Normalize tm_isdst just in case someone foolishly implements %Z
494 based on the assumption that tm_isdst falls within the range of
495 [-1, 1] */
496 if (buf.tm_isdst < -1)
497 buf.tm_isdst = -1;
498 else if (buf.tm_isdst > 1)
499 buf.tm_isdst = 1;
Brett Cannond1080a32004-03-02 04:38:10 +0000500
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000501#ifdef HAVE_WCSFTIME
Victor Stinnerbeb4135b2010-10-07 01:02:42 +0000502 format = PyUnicode_AsWideCharString(format_arg, NULL);
Victor Stinnerb2904782010-09-29 10:34:19 +0000503 if (format == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000504 return NULL;
Victor Stinnerb2904782010-09-29 10:34:19 +0000505 fmt = format;
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000506#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000507 /* Convert the unicode string to an ascii one */
Victor Stinneref128102010-10-07 01:00:52 +0000508 format = PyUnicode_AsEncodedString(format_arg, TZNAME_ENCODING, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000509 if (format == NULL)
510 return NULL;
511 fmt = PyBytes_AS_STRING(format);
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000512#endif
Amaury Forgeot d'Arcb5be6d42009-03-02 23:52:57 +0000513
Victor Stinner5a3ff792011-10-16 19:08:23 +0200514#if defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000515 /* check that the format string contains only valid directives */
Victor Stinner5a3ff792011-10-16 19:08:23 +0200516 for(outbuf = strchr(fmt, '%');
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000517 outbuf != NULL;
Victor Stinner5a3ff792011-10-16 19:08:23 +0200518 outbuf = strchr(outbuf+2, '%'))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000519 {
520 if (outbuf[1]=='#')
521 ++outbuf; /* not documented by python, */
522 if (outbuf[1]=='\0' ||
Victor Stinner5a3ff792011-10-16 19:08:23 +0200523 !strchr("aAbBcdHIjmMpSUwWxXyYzZ%", outbuf[1]))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000524 {
525 PyErr_SetString(PyExc_ValueError, "Invalid format string");
526 return 0;
527 }
528 }
Amaury Forgeot d'Arcb5be6d42009-03-02 23:52:57 +0000529#endif
530
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000531 fmtlen = time_strlen(fmt);
Guido van Rossumc222ec21999-02-23 00:00:10 +0000532
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000533 /* I hate these functions that presume you know how big the output
534 * will be ahead of time...
535 */
536 for (i = 1024; ; i += i) {
537 outbuf = (time_char *)PyMem_Malloc(i*sizeof(time_char));
538 if (outbuf == NULL) {
Victor Stinnerb2904782010-09-29 10:34:19 +0000539 PyErr_NoMemory();
540 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000541 }
542 buflen = format_time(outbuf, i, fmt, &buf);
543 if (buflen > 0 || i >= 256 * fmtlen) {
544 /* If the buffer is 256 times as long as the format,
545 it's probably not failing for lack of room!
546 More likely, the format yields an empty result,
547 e.g. an empty format, or %Z when the timezone
548 is unknown. */
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000549#ifdef HAVE_WCSFTIME
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000550 ret = PyUnicode_FromWideChar(outbuf, buflen);
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000551#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000552 ret = PyUnicode_Decode(outbuf, buflen,
553 TZNAME_ENCODING, NULL);
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000554#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000555 PyMem_Free(outbuf);
Victor Stinnerb2904782010-09-29 10:34:19 +0000556 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000557 }
558 PyMem_Free(outbuf);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000559#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000560 /* VisualStudio .NET 2005 does this properly */
561 if (buflen == 0 && errno == EINVAL) {
562 PyErr_SetString(PyExc_ValueError, "Invalid format string");
Victor Stinnerb2904782010-09-29 10:34:19 +0000563 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000564 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000565#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000566 }
Victor Stinnerb2904782010-09-29 10:34:19 +0000567#ifdef HAVE_WCSFTIME
568 PyMem_Free(format);
569#else
570 Py_DECREF(format);
571#endif
572 return ret;
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000573}
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000574
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000575#undef time_char
576#undef format_time
577
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000578PyDoc_STRVAR(strftime_doc,
Thomas Woutersfe385252001-01-19 23:16:56 +0000579"strftime(format[, tuple]) -> string\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000580\n\
581Convert a time tuple to a string according to a format specification.\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000582See the library reference manual for formatting codes. When the time tuple\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000583is not present, current time as returned by localtime() is used.");
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000584#endif /* HAVE_STRFTIME */
585
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000586static PyObject *
587time_strptime(PyObject *self, PyObject *args)
588{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000589 PyObject *strptime_module = PyImport_ImportModuleNoBlock("_strptime");
590 PyObject *strptime_result;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200591 _Py_IDENTIFIER(_strptime_time);
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000592
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000593 if (!strptime_module)
594 return NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200595 strptime_result = _PyObject_CallMethodId(strptime_module,
596 &PyId__strptime_time, "O", args);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000597 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 */
Victor Stinner499dfcf2011-03-21 13:26:24 +0100613 static char wday_name[7][4] = {
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000614 "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
615 };
Victor Stinner499dfcf2011-03-21 13:26:24 +0100616 static char mon_name[12][4] = {
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000617 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
618 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
619 };
Victor Stinner499dfcf2011-03-21 13:26:24 +0100620 return PyUnicode_FromFormat(
621 "%s %s%3d %.2d:%.2d:%.2d %d",
622 wday_name[timeptr->tm_wday],
623 mon_name[timeptr->tm_mon],
624 timeptr->tm_mday, timeptr->tm_hour,
625 timeptr->tm_min, timeptr->tm_sec,
626 1900 + timeptr->tm_year);
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000627}
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000628
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000629static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000630time_asctime(PyObject *self, PyObject *args)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000631{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000632 PyObject *tup = NULL;
633 struct tm buf;
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000634
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000635 if (!PyArg_UnpackTuple(args, "asctime", 0, 1, &tup))
636 return NULL;
637 if (tup == NULL) {
638 time_t tt = time(NULL);
639 buf = *localtime(&tt);
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000640 } else if (!gettmarg(tup, &buf) || !checktm(&buf))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000641 return NULL;
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000642 return _asctime(&buf);
Guido van Rossum9e90a671993-06-24 11:10:19 +0000643}
644
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000645PyDoc_STRVAR(asctime_doc,
Thomas Woutersfe385252001-01-19 23:16:56 +0000646"asctime([tuple]) -> string\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000647\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000648Convert a time tuple to a string, e.g. 'Sat Jun 06 16:26:11 1998'.\n\
649When the time tuple is not present, current time as returned by localtime()\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000650is used.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000651
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000652static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000653time_ctime(PyObject *self, PyObject *args)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000654{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000655 PyObject *ot = NULL;
656 time_t tt;
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000657 struct tm *timeptr;
Guido van Rossum10b164a2001-09-25 13:59:01 +0000658
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000659 if (!PyArg_UnpackTuple(args, "ctime", 0, 1, &ot))
660 return NULL;
661 if (ot == NULL || ot == Py_None)
662 tt = time(NULL);
663 else {
664 double dt = PyFloat_AsDouble(ot);
665 if (PyErr_Occurred())
666 return NULL;
667 tt = _PyTime_DoubleToTimet(dt);
668 if (tt == (time_t)-1 && PyErr_Occurred())
669 return NULL;
670 }
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000671 timeptr = localtime(&tt);
672 if (timeptr == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000673 PyErr_SetString(PyExc_ValueError, "unconvertible time");
Alexander Belopolsky5da468f2011-01-04 17:15:52 +0000674 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000675 }
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000676 return _asctime(timeptr);
Guido van Rossum9e90a671993-06-24 11:10:19 +0000677}
678
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000679PyDoc_STRVAR(ctime_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000680"ctime(seconds) -> string\n\
681\n\
682Convert a time in seconds since the Epoch to a string in local time.\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000683This is equivalent to asctime(localtime(seconds)). When the time tuple is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000684not present, current time as returned by localtime() is used.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000685
Guido van Rossum60cd8131998-03-06 17:16:21 +0000686#ifdef HAVE_MKTIME
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000687static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000688time_mktime(PyObject *self, PyObject *tup)
Guido van Rossum234f9421993-06-17 12:35:49 +0000689{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000690 struct tm buf;
691 time_t tt;
692 if (!gettmarg(tup, &buf))
693 return NULL;
Alexander Belopolskyb7d40d12011-01-11 01:21:25 +0000694 buf.tm_wday = -1; /* sentinel; original value ignored */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000695 tt = mktime(&buf);
Alexander Belopolskyb7d40d12011-01-11 01:21:25 +0000696 /* Return value of -1 does not necessarily mean an error, but tm_wday
Ezio Melotti13925002011-03-16 11:05:33 +0200697 * cannot remain set to -1 if mktime succeeded. */
Alexander Belopolskyb7d40d12011-01-11 01:21:25 +0000698 if (tt == (time_t)(-1) && buf.tm_wday == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000699 PyErr_SetString(PyExc_OverflowError,
700 "mktime argument out of range");
701 return NULL;
702 }
703 return PyFloat_FromDouble((double)tt);
Guido van Rossum234f9421993-06-17 12:35:49 +0000704}
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000705
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000706PyDoc_STRVAR(mktime_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000707"mktime(tuple) -> floating point number\n\
708\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000709Convert a time tuple in local time to seconds since the Epoch.");
Guido van Rossum60cd8131998-03-06 17:16:21 +0000710#endif /* HAVE_MKTIME */
Guido van Rossum234f9421993-06-17 12:35:49 +0000711
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000712#ifdef HAVE_WORKING_TZSET
Martin v. Löwis1a214512008-06-11 05:26:20 +0000713static void PyInit_timezone(PyObject *module);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000714
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000715static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000716time_tzset(PyObject *self, PyObject *unused)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000717{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000718 PyObject* m;
Fred Drake9bb74322002-04-01 14:49:59 +0000719
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000720 m = PyImport_ImportModuleNoBlock("time");
721 if (m == NULL) {
722 return NULL;
723 }
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000724
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000725 tzset();
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000726
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000727 /* Reset timezone, altzone, daylight and tzname */
728 PyInit_timezone(m);
729 Py_DECREF(m);
Tim Peters1b6f7a92004-06-20 02:50:16 +0000730
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000731 Py_INCREF(Py_None);
732 return Py_None;
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000733}
734
735PyDoc_STRVAR(tzset_doc,
R. David Murray4d55bf92010-12-14 00:55:46 +0000736"tzset()\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000737\n\
738Initialize, or reinitialize, the local timezone to the value stored in\n\
739os.environ['TZ']. The TZ environment variable should be specified in\n\
Neal Norwitzdc8e1942004-07-20 22:34:37 +0000740standard Unix timezone format as documented in the tzset man page\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000741(eg. 'US/Eastern', 'Europe/Amsterdam'). Unknown timezones will silently\n\
742fall back to UTC. If the TZ environment variable is not set, the local\n\
743timezone is set to the systems best guess of wallclock time.\n\
744Changing the TZ environment variable without calling tzset *may* change\n\
745the local timezone used by methods such as localtime, but this behaviour\n\
746should not be relied on.");
747#endif /* HAVE_WORKING_TZSET */
748
Martin v. Löwisd218dc12008-04-07 03:17:54 +0000749static void
Martin v. Löwis1a214512008-06-11 05:26:20 +0000750PyInit_timezone(PyObject *m) {
751 /* This code moved from PyInit_time wholesale to allow calling it from
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000752 time_tzset. In the future, some parts of it can be moved back
753 (for platforms that don't HAVE_WORKING_TZSET, when we know what they
754 are), and the extraneous calls to tzset(3) should be removed.
755 I haven't done this yet, as I don't want to change this code as
756 little as possible when introducing the time.tzset and time.tzsetwall
757 methods. This should simply be a method of doing the following once,
758 at the top of this function and removing the call to tzset() from
759 time_tzset():
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000760
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000761 #ifdef HAVE_TZSET
762 tzset()
763 #endif
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000764
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000765 And I'm lazy and hate C so nyer.
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000766 */
Guido van Rossum10b164a2001-09-25 13:59:01 +0000767#if defined(HAVE_TZNAME) && !defined(__GLIBC__) && !defined(__CYGWIN__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000768 PyObject *otz0, *otz1;
769 tzset();
Guido van Rossum26452411998-09-28 22:07:11 +0000770#ifdef PYOS_OS2
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000771 PyModule_AddIntConstant(m, "timezone", _timezone);
Guido van Rossum26452411998-09-28 22:07:11 +0000772#else /* !PYOS_OS2 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000773 PyModule_AddIntConstant(m, "timezone", timezone);
Guido van Rossum26452411998-09-28 22:07:11 +0000774#endif /* PYOS_OS2 */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000775#ifdef HAVE_ALTZONE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000776 PyModule_AddIntConstant(m, "altzone", altzone);
Guido van Rossumb6775db1994-08-01 11:34:53 +0000777#else
Guido van Rossum26452411998-09-28 22:07:11 +0000778#ifdef PYOS_OS2
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000779 PyModule_AddIntConstant(m, "altzone", _timezone-3600);
Guido van Rossum26452411998-09-28 22:07:11 +0000780#else /* !PYOS_OS2 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000781 PyModule_AddIntConstant(m, "altzone", timezone-3600);
Guido van Rossum26452411998-09-28 22:07:11 +0000782#endif /* PYOS_OS2 */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000783#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000784 PyModule_AddIntConstant(m, "daylight", daylight);
785 otz0 = PyUnicode_Decode(tzname[0], strlen(tzname[0]), TZNAME_ENCODING, NULL);
786 otz1 = PyUnicode_Decode(tzname[1], strlen(tzname[1]), TZNAME_ENCODING, NULL);
787 PyModule_AddObject(m, "tzname", Py_BuildValue("(NN)", otz0, otz1));
Guido van Rossum10b164a2001-09-25 13:59:01 +0000788#else /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/
Martin v. Löwis60a5d722002-10-16 20:28:25 +0000789#ifdef HAVE_STRUCT_TM_TM_ZONE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000790 {
Guido van Rossum234f9421993-06-17 12:35:49 +0000791#define YEAR ((time_t)((365 * 24 + 6) * 3600))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000792 time_t t;
793 struct tm *p;
794 long janzone, julyzone;
795 char janname[10], julyname[10];
796 t = (time((time_t *)0) / YEAR) * YEAR;
797 p = localtime(&t);
798 janzone = -p->tm_gmtoff;
799 strncpy(janname, p->tm_zone ? p->tm_zone : " ", 9);
800 janname[9] = '\0';
801 t += YEAR/2;
802 p = localtime(&t);
803 julyzone = -p->tm_gmtoff;
804 strncpy(julyname, p->tm_zone ? p->tm_zone : " ", 9);
805 julyname[9] = '\0';
Guido van Rossum10b164a2001-09-25 13:59:01 +0000806
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000807 if( janzone < julyzone ) {
808 /* DST is reversed in the southern hemisphere */
809 PyModule_AddIntConstant(m, "timezone", julyzone);
810 PyModule_AddIntConstant(m, "altzone", janzone);
811 PyModule_AddIntConstant(m, "daylight",
812 janzone != julyzone);
813 PyModule_AddObject(m, "tzname",
814 Py_BuildValue("(zz)",
815 julyname, janname));
816 } else {
817 PyModule_AddIntConstant(m, "timezone", janzone);
818 PyModule_AddIntConstant(m, "altzone", julyzone);
819 PyModule_AddIntConstant(m, "daylight",
820 janzone != julyzone);
821 PyModule_AddObject(m, "tzname",
822 Py_BuildValue("(zz)",
823 janname, julyname));
824 }
825 }
Guido van Rossume6a4b7b1997-10-08 15:27:56 +0000826#else
Martin v. Löwis60a5d722002-10-16 20:28:25 +0000827#endif /* HAVE_STRUCT_TM_TM_ZONE */
Tim Peters26ae7cd2001-03-20 03:26:49 +0000828#ifdef __CYGWIN__
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000829 tzset();
830 PyModule_AddIntConstant(m, "timezone", _timezone);
831 PyModule_AddIntConstant(m, "altzone", _timezone-3600);
832 PyModule_AddIntConstant(m, "daylight", _daylight);
833 PyModule_AddObject(m, "tzname",
834 Py_BuildValue("(zz)", _tzname[0], _tzname[1]));
Tim Peters26ae7cd2001-03-20 03:26:49 +0000835#endif /* __CYGWIN__ */
Guido van Rossum10b164a2001-09-25 13:59:01 +0000836#endif /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/
Victor Stinnere0be4232011-10-25 13:06:09 +0200837
838#if defined(HAVE_CLOCK_GETTIME) || defined(HAVE_CLOCK_GETRES)
839#ifdef CLOCK_REALTIME
840 PyModule_AddIntMacro(m, CLOCK_REALTIME);
841#endif
842#ifdef CLOCK_MONOTONIC
843 PyModule_AddIntMacro(m, CLOCK_MONOTONIC);
844#endif
845#ifdef CLOCK_MONOTONIC_RAW
846 PyModule_AddIntMacro(m, CLOCK_MONOTONIC_RAW);
847#endif
848#ifdef CLOCK_PROCESS_CPUTIME_ID
849 PyModule_AddIntMacro(m, CLOCK_PROCESS_CPUTIME_ID);
850#endif
851#ifdef CLOCK_THREAD_CPUTIME_ID
852 PyModule_AddIntMacro(m, CLOCK_THREAD_CPUTIME_ID);
853#endif
854#endif /* HAVE_CLOCK_GETTIME */
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000855}
856
857
858static PyMethodDef time_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000859 {"time", time_time, METH_NOARGS, time_doc},
Victor Stinner9122fdd2011-07-04 13:55:40 +0200860#if (defined(MS_WINDOWS) && !defined(__BORLANDC__)) || defined(HAVE_CLOCK)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000861 {"clock", time_clock, METH_NOARGS, clock_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000862#endif
Victor Stinnere0be4232011-10-25 13:06:09 +0200863#ifdef HAVE_CLOCK_GETTIME
864 {"clock_gettime", time_clock_gettime, METH_VARARGS, clock_gettime_doc},
865#endif
866#ifdef HAVE_CLOCK_GETRES
867 {"clock_getres", time_clock_getres, METH_VARARGS, clock_getres_doc},
868#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000869 {"sleep", time_sleep, METH_VARARGS, sleep_doc},
870 {"gmtime", time_gmtime, METH_VARARGS, gmtime_doc},
871 {"localtime", time_localtime, METH_VARARGS, localtime_doc},
872 {"asctime", time_asctime, METH_VARARGS, asctime_doc},
873 {"ctime", time_ctime, METH_VARARGS, ctime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000874#ifdef HAVE_MKTIME
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000875 {"mktime", time_mktime, METH_O, mktime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000876#endif
877#ifdef HAVE_STRFTIME
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000878 {"strftime", time_strftime, METH_VARARGS, strftime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000879#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000880 {"strptime", time_strptime, METH_VARARGS, strptime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000881#ifdef HAVE_WORKING_TZSET
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000882 {"tzset", time_tzset, METH_NOARGS, tzset_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000883#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000884 {NULL, NULL} /* sentinel */
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000885};
886
887
888PyDoc_STRVAR(module_doc,
889"This module provides various functions to manipulate time values.\n\
890\n\
891There are two standard representations of time. One is the number\n\
892of seconds since the Epoch, in UTC (a.k.a. GMT). It may be an integer\n\
893or a floating point number (to represent fractions of seconds).\n\
894The Epoch is system-defined; on Unix, it is generally January 1st, 1970.\n\
895The actual value can be retrieved by calling gmtime(0).\n\
896\n\
897The other representation is a tuple of 9 integers giving local time.\n\
898The tuple items are:\n\
Alexander Belopolsky03163ac2011-05-02 12:20:52 -0400899 year (including century, e.g. 1998)\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000900 month (1-12)\n\
901 day (1-31)\n\
902 hours (0-23)\n\
903 minutes (0-59)\n\
904 seconds (0-59)\n\
905 weekday (0-6, Monday is 0)\n\
906 Julian day (day in the year, 1-366)\n\
907 DST (Daylight Savings Time) flag (-1, 0 or 1)\n\
908If the DST flag is 0, the time is given in the regular time zone;\n\
909if it is 1, the time is given in the DST time zone;\n\
910if it is -1, mktime() should guess based on the date and time.\n\
911\n\
912Variables:\n\
913\n\
914timezone -- difference in seconds between UTC and local standard time\n\
915altzone -- difference in seconds between UTC and local DST time\n\
916daylight -- whether local time should reflect DST\n\
917tzname -- tuple of (standard time zone name, DST time zone name)\n\
918\n\
919Functions:\n\
920\n\
921time() -- return current time in seconds since the Epoch as a float\n\
922clock() -- return CPU time since process start as a float\n\
923sleep() -- delay for a number of seconds given as a float\n\
924gmtime() -- convert seconds since Epoch to UTC tuple\n\
925localtime() -- convert seconds since Epoch to local time tuple\n\
926asctime() -- convert time tuple to string\n\
927ctime() -- convert time in seconds to string\n\
928mktime() -- convert local time tuple to seconds since Epoch\n\
929strftime() -- convert time tuple to string according to format specification\n\
930strptime() -- parse string to time tuple according to format specification\n\
931tzset() -- change the local timezone");
932
933
Martin v. Löwis1a214512008-06-11 05:26:20 +0000934
935static struct PyModuleDef timemodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000936 PyModuleDef_HEAD_INIT,
937 "time",
938 module_doc,
939 -1,
940 time_methods,
941 NULL,
942 NULL,
943 NULL,
944 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +0000945};
946
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000947PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +0000948PyInit_time(void)
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000949{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000950 PyObject *m;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000951 m = PyModule_Create(&timemodule);
952 if (m == NULL)
953 return NULL;
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000954
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000955 /* Set, or reset, module variables like time.timezone */
956 PyInit_timezone(m);
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000957
Mark Hammond975e3922002-07-16 01:29:19 +0000958#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000959 /* Helper to allow interrupts for Windows.
960 If Ctrl+C event delivered while not sleeping
961 it will be ignored.
962 */
963 main_thread = PyThread_get_thread_ident();
964 hInterruptEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
965 SetConsoleCtrlHandler( PyCtrlHandler, TRUE);
Mark Hammond975e3922002-07-16 01:29:19 +0000966#endif /* MS_WINDOWS */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000967 if (!initialized) {
968 PyStructSequence_InitType(&StructTimeType,
969 &struct_time_type_desc);
970 }
971 Py_INCREF(&StructTimeType);
972 PyModule_AddObject(m, "struct_time", (PyObject*) &StructTimeType);
973 initialized = 1;
974 return m;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000975}
976
Guido van Rossumb6775db1994-08-01 11:34:53 +0000977static double
Thomas Woutersf3f33dc2000-07-21 06:00:07 +0000978floattime(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000979{
Alexander Belopolsky6fc4ade2010-08-05 17:34:27 +0000980 _PyTime_timeval t;
981 _PyTime_gettimeofday(&t);
982 return (double)t.tv_sec + t.tv_usec*0.000001;
Guido van Rossum426035c1991-02-19 12:27:35 +0000983}
984
Guido van Rossumb6775db1994-08-01 11:34:53 +0000985
986/* Implement floatsleep() for various platforms.
987 When interrupted (or when another error occurs), return -1 and
988 set an exception; else return 0. */
989
990static int
Guido van Rossuma320fd31995-03-09 12:14:15 +0000991floatsleep(double secs)
Guido van Rossum426035c1991-02-19 12:27:35 +0000992{
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000993/* XXX Should test for MS_WINDOWS first! */
Skip Montanaroeb33e5a2007-08-17 12:57:41 +0000994#if defined(HAVE_SELECT) && !defined(__EMX__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000995 struct timeval t;
996 double frac;
Victor Stinner48b1ce52011-07-01 13:50:09 +0200997 int err;
998
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000999 frac = fmod(secs, 1.0);
1000 secs = floor(secs);
1001 t.tv_sec = (long)secs;
1002 t.tv_usec = (long)(frac*1000000.0);
1003 Py_BEGIN_ALLOW_THREADS
Victor Stinner48b1ce52011-07-01 13:50:09 +02001004 err = select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &t);
1005 Py_END_ALLOW_THREADS
1006 if (err != 0) {
Guido van Rossum09cbb011999-11-08 15:32:27 +00001007#ifdef EINTR
Victor Stinner48b1ce52011-07-01 13:50:09 +02001008 if (errno == EINTR) {
1009 if (PyErr_CheckSignals())
1010 return -1;
1011 }
1012 else
Guido van Rossum09cbb011999-11-08 15:32:27 +00001013#endif
Victor Stinner48b1ce52011-07-01 13:50:09 +02001014 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001015 PyErr_SetFromErrno(PyExc_IOError);
1016 return -1;
1017 }
1018 }
Martin v. Löwis02af9642002-01-16 11:04:06 +00001019#elif defined(__WATCOMC__) && !defined(__QNX__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001020 /* XXX Can't interrupt this sleep */
1021 Py_BEGIN_ALLOW_THREADS
1022 delay((int)(secs * 1000 + 0.5)); /* delay() uses milliseconds */
1023 Py_END_ALLOW_THREADS
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001024#elif defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001025 {
1026 double millisecs = secs * 1000.0;
1027 unsigned long ul_millis;
Tim Peters513a1cd2003-01-19 04:54:58 +00001028
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001029 if (millisecs > (double)ULONG_MAX) {
1030 PyErr_SetString(PyExc_OverflowError,
1031 "sleep length is too large");
1032 return -1;
1033 }
1034 Py_BEGIN_ALLOW_THREADS
1035 /* Allow sleep(0) to maintain win32 semantics, and as decreed
1036 * by Guido, only the main thread can be interrupted.
1037 */
1038 ul_millis = (unsigned long)millisecs;
1039 if (ul_millis == 0 ||
1040 main_thread != PyThread_get_thread_ident())
1041 Sleep(ul_millis);
1042 else {
1043 DWORD rc;
1044 ResetEvent(hInterruptEvent);
1045 rc = WaitForSingleObject(hInterruptEvent, ul_millis);
1046 if (rc == WAIT_OBJECT_0) {
1047 /* Yield to make sure real Python signal
1048 * handler called.
1049 */
1050 Sleep(1);
1051 Py_BLOCK_THREADS
1052 errno = EINTR;
1053 PyErr_SetFromErrno(PyExc_IOError);
1054 return -1;
1055 }
1056 }
1057 Py_END_ALLOW_THREADS
1058 }
Martin v. Löwis02af9642002-01-16 11:04:06 +00001059#elif defined(PYOS_OS2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001060 /* This Sleep *IS* Interruptable by Exceptions */
1061 Py_BEGIN_ALLOW_THREADS
1062 if (DosSleep(secs * 1000) != NO_ERROR) {
1063 Py_BLOCK_THREADS
1064 PyErr_SetFromErrno(PyExc_IOError);
1065 return -1;
1066 }
1067 Py_END_ALLOW_THREADS
Martin v. Löwis02af9642002-01-16 11:04:06 +00001068#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001069 /* XXX Can't interrupt this sleep */
1070 Py_BEGIN_ALLOW_THREADS
1071 sleep((int)secs);
1072 Py_END_ALLOW_THREADS
Martin v. Löwis02af9642002-01-16 11:04:06 +00001073#endif
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001074
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001075 return 0;
Guido van Rossum80c9d881991-04-16 08:47:51 +00001076}