blob: 59fe3eef03e2650b0efd4c0424622cb2da2a4ba4 [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
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000024#if defined(__BORLANDC__)
Guido van Rossumb2fb3641996-09-07 00:47:35 +000025/* These overrides not needed for Win32 */
Guido van Rossumb6775db1994-08-01 11:34:53 +000026#define timezone _timezone
Guido van Rossumcc081121995-03-14 15:05:41 +000027#define tzname _tzname
28#define daylight _daylight
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000029#endif /* __BORLANDC__ */
Guido van Rossumcac6c721996-09-06 13:34:02 +000030#endif /* MS_WINDOWS */
Guido van Rossum7bf22de1997-12-02 20:34:19 +000031#endif /* !__WATCOMC__ || __QNX__ */
Guido van Rossum234f9421993-06-17 12:35:49 +000032
Andrew MacIntyre7bf68332002-03-03 02:59:16 +000033#if defined(PYOS_OS2)
34#define INCL_DOS
35#define INCL_ERRORS
36#include <os2.h>
37#endif
38
Guido van Rossum8e9ebfd1997-11-22 21:53:48 +000039#if defined(PYCC_VACPP)
Guido van Rossum26452411998-09-28 22:07:11 +000040#include <sys/time.h>
Guido van Rossum8e9ebfd1997-11-22 21:53:48 +000041#endif
42
Guido van Rossum234f9421993-06-17 12:35:49 +000043/* Forward declarations */
Tim Petersdbd9ba62000-07-09 03:09:57 +000044static int floatsleep(double);
Victor Stinner4195b5c2012-02-08 23:03:19 +010045static double floattime(void);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000046
Barry Warsaw9a2a8a81996-12-06 23:32:14 +000047static PyObject *
Victor Stinner4195b5c2012-02-08 23:03:19 +010048time_time(PyObject *self, PyObject *unused)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000049{
Victor Stinner4195b5c2012-02-08 23:03:19 +010050 double secs;
51 secs = floattime();
52 if (secs == 0.0) {
53 PyErr_SetFromErrno(PyExc_IOError);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000054 return NULL;
Victor Stinner4195b5c2012-02-08 23:03:19 +010055 }
56 return PyFloat_FromDouble(secs);
Guido van Rossumb6775db1994-08-01 11:34:53 +000057}
58
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000059PyDoc_STRVAR(time_doc,
Victor Stinner4195b5c2012-02-08 23:03:19 +010060"time() -> floating point number\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +000061\n\
62Return the current time in seconds since the Epoch.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000063Fractions of a second may be present if the system clock provides them.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +000064
Victor Stinner85fdfa82012-01-27 00:38:48 +010065#if defined(HAVE_CLOCK)
66
67#ifndef CLOCKS_PER_SEC
68#ifdef CLK_TCK
69#define CLOCKS_PER_SEC CLK_TCK
70#else
71#define CLOCKS_PER_SEC 1000000
72#endif
73#endif
74
Victor Stinner4195b5c2012-02-08 23:03:19 +010075static PyObject *
76pyclock(void)
Victor Stinner85fdfa82012-01-27 00:38:48 +010077{
Victor Stinner4195b5c2012-02-08 23:03:19 +010078 clock_t value;
79 value = clock();
80 if (value == (clock_t)-1) {
Victor Stinner85fdfa82012-01-27 00:38:48 +010081 PyErr_SetString(PyExc_RuntimeError,
82 "the processor time used is not available "
83 "or its value cannot be represented");
Victor Stinner4195b5c2012-02-08 23:03:19 +010084 return NULL;
Victor Stinner85fdfa82012-01-27 00:38:48 +010085 }
Victor Stinner4195b5c2012-02-08 23:03:19 +010086 return PyFloat_FromDouble((double)value / CLOCKS_PER_SEC);
Victor Stinner85fdfa82012-01-27 00:38:48 +010087}
88#endif /* HAVE_CLOCK */
89
Thomas Wouters477c8d52006-05-27 19:21:47 +000090#if defined(MS_WINDOWS) && !defined(__BORLANDC__)
Victor Stinner9122fdd2011-07-04 13:55:40 +020091/* Win32 has better clock replacement; we have our own version, due to Mark
92 Hammond and Tim Peters */
Victor Stinner4195b5c2012-02-08 23:03:19 +010093static PyObject *
94win32_clock(int fallback)
Guido van Rossum3917c221997-04-02 05:35:28 +000095{
Victor Stinner8b302012012-02-07 23:29:46 +010096 static LONGLONG cpu_frequency = 0;
Victor Stinner4195b5c2012-02-08 23:03:19 +010097 static LONGLONG ctrStart;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000098 LARGE_INTEGER now;
Victor Stinner4195b5c2012-02-08 23:03:19 +010099 double diff;
Guido van Rossum3917c221997-04-02 05:35:28 +0000100
Victor Stinner8b302012012-02-07 23:29:46 +0100101 if (cpu_frequency == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000102 LARGE_INTEGER freq;
Victor Stinner8b302012012-02-07 23:29:46 +0100103 QueryPerformanceCounter(&now);
Victor Stinner4195b5c2012-02-08 23:03:19 +0100104 ctrStart = now.QuadPart;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000105 if (!QueryPerformanceFrequency(&freq) || freq.QuadPart == 0) {
106 /* Unlikely to happen - this works on all intel
107 machines at least! Revert to clock() */
Victor Stinner4195b5c2012-02-08 23:03:19 +0100108 if (fallback)
109 return pyclock();
110 else
111 return PyErr_SetFromWindowsErr(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000112 }
Victor Stinner8b302012012-02-07 23:29:46 +0100113 cpu_frequency = freq.QuadPart;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000114 }
115 QueryPerformanceCounter(&now);
Victor Stinner4195b5c2012-02-08 23:03:19 +0100116 diff = (double)(now.QuadPart - ctrStart);
117 return PyFloat_FromDouble(diff / (double)cpu_frequency);
Guido van Rossum3917c221997-04-02 05:35:28 +0000118}
Victor Stinner8b302012012-02-07 23:29:46 +0100119#endif
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000120
Victor Stinner8b302012012-02-07 23:29:46 +0100121#if (defined(MS_WINDOWS) && !defined(__BORLANDC__)) || defined(HAVE_CLOCK)
Victor Stinner9122fdd2011-07-04 13:55:40 +0200122static PyObject *
Victor Stinner4195b5c2012-02-08 23:03:19 +0100123time_clock(PyObject *self, PyObject *unused)
Victor Stinner9122fdd2011-07-04 13:55:40 +0200124{
Victor Stinner8b302012012-02-07 23:29:46 +0100125#if defined(MS_WINDOWS) && !defined(__BORLANDC__)
Victor Stinner4195b5c2012-02-08 23:03:19 +0100126 return win32_clock(1);
Victor Stinner8b302012012-02-07 23:29:46 +0100127#else
Victor Stinner4195b5c2012-02-08 23:03:19 +0100128 return pyclock();
Victor Stinner8b302012012-02-07 23:29:46 +0100129#endif
Victor Stinner9122fdd2011-07-04 13:55:40 +0200130}
Victor Stinner9122fdd2011-07-04 13:55:40 +0200131
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000132PyDoc_STRVAR(clock_doc,
Victor Stinner4195b5c2012-02-08 23:03:19 +0100133"clock() -> floating point number\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000134\n\
135Return the CPU time or real time since the start of the process or since\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000136the first call to clock(). This has as much precision as the system\n\
137records.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000138#endif
139
Victor Stinnere0be4232011-10-25 13:06:09 +0200140#ifdef HAVE_CLOCK_GETTIME
141static PyObject *
Victor Stinner4195b5c2012-02-08 23:03:19 +0100142time_clock_gettime(PyObject *self, PyObject *args)
Victor Stinnere0be4232011-10-25 13:06:09 +0200143{
144 int ret;
145 clockid_t clk_id;
146 struct timespec tp;
147
Victor Stinner4195b5c2012-02-08 23:03:19 +0100148 if (!PyArg_ParseTuple(args, "i:clock_gettime", &clk_id))
Victor Stinnere0be4232011-10-25 13:06:09 +0200149 return NULL;
150
151 ret = clock_gettime((clockid_t)clk_id, &tp);
Antoine Pitrou2c085602012-01-18 01:41:44 +0100152 if (ret != 0) {
Victor Stinnere0be4232011-10-25 13:06:09 +0200153 PyErr_SetFromErrno(PyExc_IOError);
Antoine Pitrou2c085602012-01-18 01:41:44 +0100154 return NULL;
155 }
Victor Stinner4195b5c2012-02-08 23:03:19 +0100156
157 return PyFloat_FromDouble(tp.tv_sec + tp.tv_nsec * 1e-9);
Victor Stinnere0be4232011-10-25 13:06:09 +0200158}
159
160PyDoc_STRVAR(clock_gettime_doc,
Victor Stinner4195b5c2012-02-08 23:03:19 +0100161"clock_gettime(clk_id) -> floating point number\n\
Victor Stinnere0be4232011-10-25 13:06:09 +0200162\n\
163Return the time of the specified clock clk_id.");
164#endif
165
166#ifdef HAVE_CLOCK_GETRES
167static PyObject *
Victor Stinner4195b5c2012-02-08 23:03:19 +0100168time_clock_getres(PyObject *self, PyObject *args)
Victor Stinnere0be4232011-10-25 13:06:09 +0200169{
170 int ret;
171 clockid_t clk_id;
172 struct timespec tp;
173
Victor Stinner4195b5c2012-02-08 23:03:19 +0100174 if (!PyArg_ParseTuple(args, "i:clock_getres", &clk_id))
Victor Stinnere0be4232011-10-25 13:06:09 +0200175 return NULL;
176
177 ret = clock_getres((clockid_t)clk_id, &tp);
Antoine Pitrou2c085602012-01-18 01:41:44 +0100178 if (ret != 0) {
Victor Stinnere0be4232011-10-25 13:06:09 +0200179 PyErr_SetFromErrno(PyExc_IOError);
Antoine Pitrou2c085602012-01-18 01:41:44 +0100180 return NULL;
181 }
Victor Stinner4195b5c2012-02-08 23:03:19 +0100182
183 return PyFloat_FromDouble(tp.tv_sec + tp.tv_nsec * 1e-9);
Victor Stinnere0be4232011-10-25 13:06:09 +0200184}
185
186PyDoc_STRVAR(clock_getres_doc,
Victor Stinner4195b5c2012-02-08 23:03:19 +0100187"clock_getres(clk_id) -> floating point number\n\
Victor Stinnere0be4232011-10-25 13:06:09 +0200188\n\
189Return the resolution (precision) of the specified clock clk_id.");
190#endif
191
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000192static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000193time_sleep(PyObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000194{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000195 double secs;
196 if (!PyArg_ParseTuple(args, "d:sleep", &secs))
197 return NULL;
Victor Stinner7f53a502011-07-05 22:00:25 +0200198 if (secs < 0) {
199 PyErr_SetString(PyExc_ValueError,
200 "sleep length must be non-negative");
201 return NULL;
202 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000203 if (floatsleep(secs) != 0)
204 return NULL;
205 Py_INCREF(Py_None);
206 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000207}
208
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000209PyDoc_STRVAR(sleep_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000210"sleep(seconds)\n\
211\n\
212Delay execution for a given number of seconds. The argument may be\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000213a floating point number for subsecond precision.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000214
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000215static PyStructSequence_Field struct_time_type_fields[] = {
Alexander Belopolsky69f3fd02010-06-05 15:04:51 +0000216 {"tm_year", "year, for example, 1993"},
217 {"tm_mon", "month of year, range [1, 12]"},
218 {"tm_mday", "day of month, range [1, 31]"},
219 {"tm_hour", "hours, range [0, 23]"},
220 {"tm_min", "minutes, range [0, 59]"},
221 {"tm_sec", "seconds, range [0, 61])"},
222 {"tm_wday", "day of week, range [0, 6], Monday is 0"},
223 {"tm_yday", "day of year, range [1, 366]"},
224 {"tm_isdst", "1 if summer time is in effect, 0 if not, and -1 if unknown"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000225 {0}
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000226};
227
228static PyStructSequence_Desc struct_time_type_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000229 "time.struct_time",
Alexander Belopolsky69f3fd02010-06-05 15:04:51 +0000230 "The time value as returned by gmtime(), localtime(), and strptime(), and\n"
231 " accepted by asctime(), mktime() and strftime(). May be considered as a\n"
232 " sequence of 9 integers.\n\n"
233 " Note that several fields' values are not the same as those defined by\n"
234 " the C language standard for struct tm. For example, the value of the\n"
235 " field tm_year is the actual year, not year - 1900. See individual\n"
236 " fields' descriptions for details.",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000237 struct_time_type_fields,
238 9,
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000239};
Tim Peters9ad4b682002-02-13 05:14:18 +0000240
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000241static int initialized;
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000242static PyTypeObject StructTimeType;
243
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000244static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000245tmtotuple(struct tm *p)
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000246{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000247 PyObject *v = PyStructSequence_New(&StructTimeType);
248 if (v == NULL)
249 return NULL;
Tim Peters9ad4b682002-02-13 05:14:18 +0000250
Christian Heimes217cfd12007-12-02 14:31:20 +0000251#define SET(i,val) PyStructSequence_SET_ITEM(v, i, PyLong_FromLong((long) val))
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000252
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000253 SET(0, p->tm_year + 1900);
254 SET(1, p->tm_mon + 1); /* Want January == 1 */
255 SET(2, p->tm_mday);
256 SET(3, p->tm_hour);
257 SET(4, p->tm_min);
258 SET(5, p->tm_sec);
259 SET(6, (p->tm_wday + 6) % 7); /* Want Monday == 0 */
260 SET(7, p->tm_yday + 1); /* Want January, 1 == 1 */
261 SET(8, p->tm_isdst);
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000262#undef SET
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000263 if (PyErr_Occurred()) {
264 Py_XDECREF(v);
265 return NULL;
266 }
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000267
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000268 return v;
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000269}
270
Fred Drakef901abd2004-08-03 17:58:55 +0000271/* Parse arg tuple that can contain an optional float-or-None value;
272 format needs to be "|O:name".
273 Returns non-zero on success (parallels PyArg_ParseTuple).
274*/
275static int
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100276parse_time_t_args(PyObject *args, char *format, time_t *pwhen)
Fred Drakef901abd2004-08-03 17:58:55 +0000277{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000278 PyObject *ot = NULL;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100279 time_t whent;
Fred Drakef901abd2004-08-03 17:58:55 +0000280
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000281 if (!PyArg_ParseTuple(args, format, &ot))
282 return 0;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100283 if (ot == NULL || ot == Py_None) {
284 whent = time(NULL);
285 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000286 else {
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100287 double d = PyFloat_AsDouble(ot);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000288 if (PyErr_Occurred())
289 return 0;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100290 whent = _PyTime_DoubleToTimet(d);
291 if (whent == (time_t)-1 && PyErr_Occurred())
292 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000293 }
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100294 *pwhen = whent;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000295 return 1;
Fred Drakef901abd2004-08-03 17:58:55 +0000296}
297
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000298static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000299time_gmtime(PyObject *self, PyObject *args)
Guido van Rossum234f9421993-06-17 12:35:49 +0000300{
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100301 time_t when;
302 struct tm buf, *local;
303
304 if (!parse_time_t_args(args, "|O:gmtime", &when))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000305 return NULL;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100306
307 errno = 0;
308 local = gmtime(&when);
309 if (local == NULL) {
310#ifdef EINVAL
311 if (errno == 0)
312 errno = EINVAL;
313#endif
314 return PyErr_SetFromErrno(PyExc_OSError);
315 }
316 buf = *local;
317 return tmtotuple(&buf);
Guido van Rossum234f9421993-06-17 12:35:49 +0000318}
319
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000320PyDoc_STRVAR(gmtime_doc,
Christian Heimes9a371592007-12-28 14:08:13 +0000321"gmtime([seconds]) -> (tm_year, tm_mon, tm_mday, tm_hour, tm_min,\n\
Fred Drake193a3f62002-03-12 21:38:49 +0000322 tm_sec, tm_wday, tm_yday, tm_isdst)\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000323\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000324Convert seconds since the Epoch to a time tuple expressing UTC (a.k.a.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000325GMT). When 'seconds' is not passed in, convert the current time instead.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000326
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100327static int
328pylocaltime(time_t *timep, struct tm *result)
329{
330 struct tm *local;
331
332 assert (timep != NULL);
333 local = localtime(timep);
334 if (local == NULL) {
335 /* unconvertible time */
336#ifdef EINVAL
337 if (errno == 0)
338 errno = EINVAL;
339#endif
340 PyErr_SetFromErrno(PyExc_OSError);
341 return -1;
342 }
343 *result = *local;
344 return 0;
345}
346
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000347static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000348time_localtime(PyObject *self, PyObject *args)
Guido van Rossum234f9421993-06-17 12:35:49 +0000349{
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100350 time_t when;
351 struct tm buf;
352
353 if (!parse_time_t_args(args, "|O:localtime", &when))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000354 return NULL;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100355 if (pylocaltime(&when, &buf) == 1)
356 return NULL;
357 return tmtotuple(&buf);
Guido van Rossum234f9421993-06-17 12:35:49 +0000358}
359
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000360PyDoc_STRVAR(localtime_doc,
Christian Heimes9a371592007-12-28 14:08:13 +0000361"localtime([seconds]) -> (tm_year,tm_mon,tm_mday,tm_hour,tm_min,\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000362 tm_sec,tm_wday,tm_yday,tm_isdst)\n\
Martin v. Löwisb3cfc1d2001-12-02 12:27:43 +0000363\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000364Convert seconds since the Epoch to a time tuple expressing local time.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000365When 'seconds' is not passed in, convert the current time instead.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000366
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000367/* Convert 9-item tuple to tm structure. Return 1 on success, set
368 * an exception and return 0 on error.
369 */
Guido van Rossum9e90a671993-06-24 11:10:19 +0000370static int
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000371gettmarg(PyObject *args, struct tm *p)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000372{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000373 int y;
Guido van Rossumcfbaecc1998-08-25 14:51:12 +0000374
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000375 memset((void *) p, '\0', sizeof(struct tm));
Guido van Rossumb9081262007-08-25 03:14:09 +0000376
Alexander Belopolsky610e5442011-01-06 21:57:06 +0000377 if (!PyTuple_Check(args)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000378 PyErr_SetString(PyExc_TypeError,
379 "Tuple or struct_time argument required");
380 return 0;
381 }
Skip Montanaro41cfce92007-08-24 21:11:00 +0000382
Alexander Belopolsky610e5442011-01-06 21:57:06 +0000383 if (!PyArg_ParseTuple(args, "iiiiiiiii",
384 &y, &p->tm_mon, &p->tm_mday,
385 &p->tm_hour, &p->tm_min, &p->tm_sec,
386 &p->tm_wday, &p->tm_yday, &p->tm_isdst))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000387 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000388 p->tm_year = y - 1900;
389 p->tm_mon--;
390 p->tm_wday = (p->tm_wday + 1) % 7;
391 p->tm_yday--;
392 return 1;
Guido van Rossum9e90a671993-06-24 11:10:19 +0000393}
394
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000395/* Check values of the struct tm fields before it is passed to strftime() and
396 * asctime(). Return 1 if all values are valid, otherwise set an exception
397 * and returns 0.
398 */
Victor Stinneref128102010-10-07 01:00:52 +0000399static int
400checktm(struct tm* buf)
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000401{
Victor Stinneref128102010-10-07 01:00:52 +0000402 /* Checks added to make sure strftime() and asctime() does not crash Python by
403 indexing blindly into some array for a textual representation
404 by some bad index (fixes bug #897625 and #6608).
405
406 Also support values of zero from Python code for arguments in which
407 that is out of range by forcing that value to the lowest value that
408 is valid (fixed bug #1520914).
409
410 Valid ranges based on what is allowed in struct tm:
411
412 - tm_year: [0, max(int)] (1)
413 - tm_mon: [0, 11] (2)
414 - tm_mday: [1, 31]
415 - tm_hour: [0, 23]
416 - tm_min: [0, 59]
417 - tm_sec: [0, 60]
418 - tm_wday: [0, 6] (1)
419 - tm_yday: [0, 365] (2)
420 - tm_isdst: [-max(int), max(int)]
421
422 (1) gettmarg() handles bounds-checking.
423 (2) Python's acceptable range is one greater than the range in C,
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000424 thus need to check against automatic decrement by gettmarg().
425 */
426 if (buf->tm_mon == -1)
427 buf->tm_mon = 0;
428 else if (buf->tm_mon < 0 || buf->tm_mon > 11) {
429 PyErr_SetString(PyExc_ValueError, "month out of range");
430 return 0;
431 }
432 if (buf->tm_mday == 0)
433 buf->tm_mday = 1;
434 else if (buf->tm_mday < 0 || buf->tm_mday > 31) {
435 PyErr_SetString(PyExc_ValueError, "day of month out of range");
436 return 0;
437 }
438 if (buf->tm_hour < 0 || buf->tm_hour > 23) {
439 PyErr_SetString(PyExc_ValueError, "hour out of range");
440 return 0;
441 }
442 if (buf->tm_min < 0 || buf->tm_min > 59) {
443 PyErr_SetString(PyExc_ValueError, "minute out of range");
444 return 0;
445 }
446 if (buf->tm_sec < 0 || buf->tm_sec > 61) {
447 PyErr_SetString(PyExc_ValueError, "seconds out of range");
448 return 0;
449 }
450 /* tm_wday does not need checking of its upper-bound since taking
451 ``% 7`` in gettmarg() automatically restricts the range. */
452 if (buf->tm_wday < 0) {
453 PyErr_SetString(PyExc_ValueError, "day of week out of range");
454 return 0;
455 }
456 if (buf->tm_yday == -1)
457 buf->tm_yday = 0;
458 else if (buf->tm_yday < 0 || buf->tm_yday > 365) {
459 PyErr_SetString(PyExc_ValueError, "day of year out of range");
460 return 0;
461 }
462 return 1;
463}
464
Victor Stinnerc1f32ca2011-10-14 02:36:13 +0200465#ifdef MS_WINDOWS
466 /* wcsftime() doesn't format correctly time zones, see issue #10653 */
467# undef HAVE_WCSFTIME
468#endif
469
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000470#ifdef HAVE_STRFTIME
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000471#ifdef HAVE_WCSFTIME
472#define time_char wchar_t
473#define format_time wcsftime
474#define time_strlen wcslen
475#else
476#define time_char char
477#define format_time strftime
478#define time_strlen strlen
479#endif
480
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000481static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000482time_strftime(PyObject *self, PyObject *args)
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000483{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000484 PyObject *tup = NULL;
485 struct tm buf;
486 const time_char *fmt;
Victor Stinnerb2904782010-09-29 10:34:19 +0000487#ifdef HAVE_WCSFTIME
488 wchar_t *format;
489#else
490 PyObject *format;
491#endif
Victor Stinneref128102010-10-07 01:00:52 +0000492 PyObject *format_arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000493 size_t fmtlen, buflen;
Victor Stinnerb2904782010-09-29 10:34:19 +0000494 time_char *outbuf = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000495 size_t i;
Victor Stinnerb2904782010-09-29 10:34:19 +0000496 PyObject *ret = NULL;
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000497
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000498 memset((void *) &buf, '\0', sizeof(buf));
Guido van Rossum1f41f841998-04-27 19:04:26 +0000499
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000500 /* Will always expect a unicode string to be passed as format.
501 Given that there's no str type anymore in py3k this seems safe.
502 */
Victor Stinneref128102010-10-07 01:00:52 +0000503 if (!PyArg_ParseTuple(args, "U|O:strftime", &format_arg, &tup))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000504 return NULL;
Thomas Woutersfe385252001-01-19 23:16:56 +0000505
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000506 if (tup == NULL) {
507 time_t tt = time(NULL);
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100508 if (pylocaltime(&tt, &buf) == -1)
509 return NULL;
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000510 }
511 else if (!gettmarg(tup, &buf) || !checktm(&buf))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000512 return NULL;
Guido van Rossum10b164a2001-09-25 13:59:01 +0000513
Victor Stinner06ec45e2011-01-08 03:35:36 +0000514#if defined(_MSC_VER) || defined(sun)
Victor Stinner73ea29c2011-01-08 01:56:31 +0000515 if (buf.tm_year + 1900 < 1 || 9999 < buf.tm_year + 1900) {
Victor Stinner6f0e4f92011-03-21 02:14:53 +0100516 PyErr_SetString(PyExc_ValueError,
517 "strftime() requires year in [1; 9999]");
Alexander Belopolsky0dd06f42011-01-08 01:23:02 +0000518 return NULL;
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000519 }
Victor Stinner73ea29c2011-01-08 01:56:31 +0000520#endif
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000521
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000522 /* Normalize tm_isdst just in case someone foolishly implements %Z
523 based on the assumption that tm_isdst falls within the range of
524 [-1, 1] */
525 if (buf.tm_isdst < -1)
526 buf.tm_isdst = -1;
527 else if (buf.tm_isdst > 1)
528 buf.tm_isdst = 1;
Brett Cannond1080a32004-03-02 04:38:10 +0000529
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000530#ifdef HAVE_WCSFTIME
Victor Stinnerbeb4135b2010-10-07 01:02:42 +0000531 format = PyUnicode_AsWideCharString(format_arg, NULL);
Victor Stinnerb2904782010-09-29 10:34:19 +0000532 if (format == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000533 return NULL;
Victor Stinnerb2904782010-09-29 10:34:19 +0000534 fmt = format;
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000535#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000536 /* Convert the unicode string to an ascii one */
Victor Stinner1b579672011-12-17 05:47:23 +0100537 format = PyUnicode_EncodeLocale(format_arg, "surrogateescape");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000538 if (format == NULL)
539 return NULL;
540 fmt = PyBytes_AS_STRING(format);
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000541#endif
Amaury Forgeot d'Arcb5be6d42009-03-02 23:52:57 +0000542
Stefan Krah4aea7d32012-02-27 16:30:26 +0100543#if defined(MS_WINDOWS) && !defined(HAVE_WCSFTIME)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000544 /* check that the format string contains only valid directives */
Victor Stinner5a3ff792011-10-16 19:08:23 +0200545 for(outbuf = strchr(fmt, '%');
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000546 outbuf != NULL;
Victor Stinner5a3ff792011-10-16 19:08:23 +0200547 outbuf = strchr(outbuf+2, '%'))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000548 {
549 if (outbuf[1]=='#')
550 ++outbuf; /* not documented by python, */
551 if (outbuf[1]=='\0' ||
Victor Stinner5a3ff792011-10-16 19:08:23 +0200552 !strchr("aAbBcdHIjmMpSUwWxXyYzZ%", outbuf[1]))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000553 {
554 PyErr_SetString(PyExc_ValueError, "Invalid format string");
Stefan Krah4aea7d32012-02-27 16:30:26 +0100555 Py_DECREF(format);
556 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000557 }
558 }
Amaury Forgeot d'Arcb5be6d42009-03-02 23:52:57 +0000559#endif
560
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000561 fmtlen = time_strlen(fmt);
Guido van Rossumc222ec21999-02-23 00:00:10 +0000562
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000563 /* I hate these functions that presume you know how big the output
564 * will be ahead of time...
565 */
566 for (i = 1024; ; i += i) {
Victor Stinner136ea492011-12-17 22:37:18 +0100567#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100568 int err;
Victor Stinner136ea492011-12-17 22:37:18 +0100569#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000570 outbuf = (time_char *)PyMem_Malloc(i*sizeof(time_char));
571 if (outbuf == NULL) {
Victor Stinnerb2904782010-09-29 10:34:19 +0000572 PyErr_NoMemory();
573 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000574 }
575 buflen = format_time(outbuf, i, fmt, &buf);
Victor Stinner136ea492011-12-17 22:37:18 +0100576#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100577 err = errno;
Victor Stinner136ea492011-12-17 22:37:18 +0100578#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000579 if (buflen > 0 || i >= 256 * fmtlen) {
580 /* If the buffer is 256 times as long as the format,
581 it's probably not failing for lack of room!
582 More likely, the format yields an empty result,
583 e.g. an empty format, or %Z when the timezone
584 is unknown. */
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000585#ifdef HAVE_WCSFTIME
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000586 ret = PyUnicode_FromWideChar(outbuf, buflen);
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000587#else
Victor Stinner1b579672011-12-17 05:47:23 +0100588 ret = PyUnicode_DecodeLocaleAndSize(outbuf, buflen,
589 "surrogateescape");
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000590#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000591 PyMem_Free(outbuf);
Victor Stinnerb2904782010-09-29 10:34:19 +0000592 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000593 }
594 PyMem_Free(outbuf);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000595#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000596 /* VisualStudio .NET 2005 does this properly */
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100597 if (buflen == 0 && err == EINVAL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000598 PyErr_SetString(PyExc_ValueError, "Invalid format string");
Victor Stinnerb2904782010-09-29 10:34:19 +0000599 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000600 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000601#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000602 }
Victor Stinnerb2904782010-09-29 10:34:19 +0000603#ifdef HAVE_WCSFTIME
604 PyMem_Free(format);
605#else
606 Py_DECREF(format);
607#endif
608 return ret;
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000609}
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000610
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000611#undef time_char
612#undef format_time
613
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000614PyDoc_STRVAR(strftime_doc,
Thomas Woutersfe385252001-01-19 23:16:56 +0000615"strftime(format[, tuple]) -> string\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000616\n\
617Convert a time tuple to a string according to a format specification.\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000618See the library reference manual for formatting codes. When the time tuple\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000619is not present, current time as returned by localtime() is used.");
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000620#endif /* HAVE_STRFTIME */
621
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000622static PyObject *
623time_strptime(PyObject *self, PyObject *args)
624{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000625 PyObject *strptime_module = PyImport_ImportModuleNoBlock("_strptime");
626 PyObject *strptime_result;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200627 _Py_IDENTIFIER(_strptime_time);
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000628
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000629 if (!strptime_module)
630 return NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200631 strptime_result = _PyObject_CallMethodId(strptime_module,
632 &PyId__strptime_time, "O", args);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000633 Py_DECREF(strptime_module);
634 return strptime_result;
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000635}
636
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000637
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000638PyDoc_STRVAR(strptime_doc,
Brett Cannon20def8b2003-07-01 05:16:08 +0000639"strptime(string, format) -> struct_time\n\
Martin v. Löwisb3cfc1d2001-12-02 12:27:43 +0000640\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000641Parse a string to a time tuple according to a format specification.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000642See the library reference manual for formatting codes (same as strftime()).");
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000643
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000644static PyObject *
645_asctime(struct tm *timeptr)
646{
647 /* Inspired by Open Group reference implementation available at
648 * http://pubs.opengroup.org/onlinepubs/009695399/functions/asctime.html */
Victor Stinner499dfcf2011-03-21 13:26:24 +0100649 static char wday_name[7][4] = {
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000650 "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
651 };
Victor Stinner499dfcf2011-03-21 13:26:24 +0100652 static char mon_name[12][4] = {
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000653 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
654 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
655 };
Victor Stinner499dfcf2011-03-21 13:26:24 +0100656 return PyUnicode_FromFormat(
657 "%s %s%3d %.2d:%.2d:%.2d %d",
658 wday_name[timeptr->tm_wday],
659 mon_name[timeptr->tm_mon],
660 timeptr->tm_mday, timeptr->tm_hour,
661 timeptr->tm_min, timeptr->tm_sec,
662 1900 + timeptr->tm_year);
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000663}
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000664
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000665static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000666time_asctime(PyObject *self, PyObject *args)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000667{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000668 PyObject *tup = NULL;
669 struct tm buf;
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000670
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000671 if (!PyArg_UnpackTuple(args, "asctime", 0, 1, &tup))
672 return NULL;
673 if (tup == NULL) {
674 time_t tt = time(NULL);
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100675 if (pylocaltime(&tt, &buf) == -1)
676 return NULL;
677
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000678 } else if (!gettmarg(tup, &buf) || !checktm(&buf))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000679 return NULL;
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000680 return _asctime(&buf);
Guido van Rossum9e90a671993-06-24 11:10:19 +0000681}
682
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000683PyDoc_STRVAR(asctime_doc,
Thomas Woutersfe385252001-01-19 23:16:56 +0000684"asctime([tuple]) -> string\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000685\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000686Convert a time tuple to a string, e.g. 'Sat Jun 06 16:26:11 1998'.\n\
687When the time tuple is not present, current time as returned by localtime()\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000688is used.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000689
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000690static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000691time_ctime(PyObject *self, PyObject *args)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000692{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000693 time_t tt;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100694 struct tm buf;
695 if (!parse_time_t_args(args, "|O:ctime", &tt))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000696 return NULL;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100697 if (pylocaltime(&tt, &buf) == -1)
Alexander Belopolsky5da468f2011-01-04 17:15:52 +0000698 return NULL;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100699 return _asctime(&buf);
Guido van Rossum9e90a671993-06-24 11:10:19 +0000700}
701
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000702PyDoc_STRVAR(ctime_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000703"ctime(seconds) -> string\n\
704\n\
705Convert a time in seconds since the Epoch to a string in local time.\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000706This is equivalent to asctime(localtime(seconds)). When the time tuple is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000707not present, current time as returned by localtime() is used.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000708
Guido van Rossum60cd8131998-03-06 17:16:21 +0000709#ifdef HAVE_MKTIME
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000710static PyObject *
Victor Stinner4195b5c2012-02-08 23:03:19 +0100711time_mktime(PyObject *self, PyObject *tup)
Guido van Rossum234f9421993-06-17 12:35:49 +0000712{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000713 struct tm buf;
714 time_t tt;
715 if (!gettmarg(tup, &buf))
716 return NULL;
Alexander Belopolskyb7d40d12011-01-11 01:21:25 +0000717 buf.tm_wday = -1; /* sentinel; original value ignored */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000718 tt = mktime(&buf);
Alexander Belopolskyb7d40d12011-01-11 01:21:25 +0000719 /* Return value of -1 does not necessarily mean an error, but tm_wday
Ezio Melotti13925002011-03-16 11:05:33 +0200720 * cannot remain set to -1 if mktime succeeded. */
Alexander Belopolskyb7d40d12011-01-11 01:21:25 +0000721 if (tt == (time_t)(-1) && buf.tm_wday == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000722 PyErr_SetString(PyExc_OverflowError,
723 "mktime argument out of range");
724 return NULL;
725 }
Victor Stinner4195b5c2012-02-08 23:03:19 +0100726 return PyFloat_FromDouble((double)tt);
Guido van Rossum234f9421993-06-17 12:35:49 +0000727}
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000728
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000729PyDoc_STRVAR(mktime_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000730"mktime(tuple) -> floating point number\n\
731\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000732Convert a time tuple in local time to seconds since the Epoch.");
Guido van Rossum60cd8131998-03-06 17:16:21 +0000733#endif /* HAVE_MKTIME */
Guido van Rossum234f9421993-06-17 12:35:49 +0000734
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000735#ifdef HAVE_WORKING_TZSET
Martin v. Löwis1a214512008-06-11 05:26:20 +0000736static void PyInit_timezone(PyObject *module);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000737
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000738static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000739time_tzset(PyObject *self, PyObject *unused)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000740{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000741 PyObject* m;
Fred Drake9bb74322002-04-01 14:49:59 +0000742
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000743 m = PyImport_ImportModuleNoBlock("time");
744 if (m == NULL) {
745 return NULL;
746 }
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000747
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000748 tzset();
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000749
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000750 /* Reset timezone, altzone, daylight and tzname */
751 PyInit_timezone(m);
752 Py_DECREF(m);
Tim Peters1b6f7a92004-06-20 02:50:16 +0000753
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000754 Py_INCREF(Py_None);
755 return Py_None;
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000756}
757
758PyDoc_STRVAR(tzset_doc,
R. David Murray4d55bf92010-12-14 00:55:46 +0000759"tzset()\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000760\n\
761Initialize, or reinitialize, the local timezone to the value stored in\n\
762os.environ['TZ']. The TZ environment variable should be specified in\n\
Neal Norwitzdc8e1942004-07-20 22:34:37 +0000763standard Unix timezone format as documented in the tzset man page\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000764(eg. 'US/Eastern', 'Europe/Amsterdam'). Unknown timezones will silently\n\
765fall back to UTC. If the TZ environment variable is not set, the local\n\
766timezone is set to the systems best guess of wallclock time.\n\
767Changing the TZ environment variable without calling tzset *may* change\n\
768the local timezone used by methods such as localtime, but this behaviour\n\
769should not be relied on.");
770#endif /* HAVE_WORKING_TZSET */
771
Victor Stinner4195b5c2012-02-08 23:03:19 +0100772static PyObject *
773time_wallclock(PyObject *self, PyObject *unused)
Victor Stinnerb94b2662012-01-18 01:50:21 +0100774{
775#if defined(MS_WINDOWS) && !defined(__BORLANDC__)
Victor Stinner4195b5c2012-02-08 23:03:19 +0100776 return win32_clock(1);
777#elif defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_MONOTONIC)
Victor Stinnerb94b2662012-01-18 01:50:21 +0100778 static int clk_index = 0;
779 clockid_t clk_ids[] = {
780#ifdef CLOCK_MONOTONIC_RAW
781 CLOCK_MONOTONIC_RAW,
782#endif
783 CLOCK_MONOTONIC
784#ifdef CLOCK_REALTIME
785 /* On Linux, CLOCK_REALTIME uses the same clock than gettimeofday(),
786 but clock_gettime() has a nanosecond resolution. */
787 , CLOCK_REALTIME
788#endif
789 };
790 int ret;
791 struct timespec tp;
792
793 while (0 <= clk_index) {
794 clockid_t clk_id = clk_ids[clk_index];
795 ret = clock_gettime(clk_id, &tp);
796 if (ret == 0)
Victor Stinner4195b5c2012-02-08 23:03:19 +0100797 return PyFloat_FromDouble(tp.tv_sec + tp.tv_nsec * 1e-9);
Victor Stinnerb94b2662012-01-18 01:50:21 +0100798
799 clk_index++;
800 if (Py_ARRAY_LENGTH(clk_ids) <= clk_index)
801 clk_index = -1;
802 }
Victor Stinner4195b5c2012-02-08 23:03:19 +0100803 return time_time(self, NULL);
804#else
805 return time_time(self, NULL);
Victor Stinnerb94b2662012-01-18 01:50:21 +0100806#endif
807}
808
809PyDoc_STRVAR(wallclock_doc,
Victor Stinner4195b5c2012-02-08 23:03:19 +0100810"wallclock() -> float\n\
Victor Stinnerb94b2662012-01-18 01:50:21 +0100811\n\
812Return the current time in fractions of a second to the system's best\n\
813ability. Use this when the most accurate representation of wall-clock is\n\
Victor Stinner855889b2012-01-18 01:57:19 +0100814required, i.e. when \"processor time\" is inappropriate. The reference point\n\
Victor Stinnerb94b2662012-01-18 01:50:21 +0100815of the returned value is undefined so only the difference of consecutive\n\
816calls is valid.");
817
Victor Stinner8b302012012-02-07 23:29:46 +0100818#if (defined(MS_WINDOWS) && !defined(__BORLANDC__)) \
819 || (defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_MONOTONIC))
820# define HAVE_PYTIME_MONOTONIC
821#endif
822
823#ifdef HAVE_PYTIME_MONOTONIC
824static PyObject *
Victor Stinner4195b5c2012-02-08 23:03:19 +0100825time_monotonic(PyObject *self, PyObject *unused)
Victor Stinner8b302012012-02-07 23:29:46 +0100826{
Victor Stinner4195b5c2012-02-08 23:03:19 +0100827#if defined(MS_WINDOWS) && !defined(__BORLANDC__)
828 return win32_clock(0);
829#else
Victor Stinner8b302012012-02-07 23:29:46 +0100830 static int clk_index = 0;
831 clockid_t clk_ids[] = {
832#ifdef CLOCK_MONOTONIC_RAW
833 CLOCK_MONOTONIC_RAW,
834#endif
835 CLOCK_MONOTONIC
836 };
837 int ret;
838 struct timespec tp;
839
840 while (0 <= clk_index) {
841 clockid_t clk_id = clk_ids[clk_index];
842 ret = clock_gettime(clk_id, &tp);
843 if (ret == 0)
Victor Stinner4195b5c2012-02-08 23:03:19 +0100844 return PyFloat_FromDouble(tp.tv_sec + tp.tv_nsec * 1e-9);
Victor Stinner8b302012012-02-07 23:29:46 +0100845
846 clk_index++;
847 if (Py_ARRAY_LENGTH(clk_ids) <= clk_index)
848 clk_index = -1;
849 }
850 PyErr_SetFromErrno(PyExc_OSError);
851 return NULL;
852#endif
853}
854
855PyDoc_STRVAR(monotonic_doc,
856"monotonic() -> float\n\
857\n\
858Monotonic clock. The reference point of the returned value is undefined so\n\
859only the difference of consecutive calls is valid.");
860#endif
861
Martin v. Löwisd218dc12008-04-07 03:17:54 +0000862static void
Martin v. Löwis1a214512008-06-11 05:26:20 +0000863PyInit_timezone(PyObject *m) {
864 /* This code moved from PyInit_time wholesale to allow calling it from
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000865 time_tzset. In the future, some parts of it can be moved back
866 (for platforms that don't HAVE_WORKING_TZSET, when we know what they
867 are), and the extraneous calls to tzset(3) should be removed.
868 I haven't done this yet, as I don't want to change this code as
869 little as possible when introducing the time.tzset and time.tzsetwall
870 methods. This should simply be a method of doing the following once,
871 at the top of this function and removing the call to tzset() from
872 time_tzset():
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000873
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000874 #ifdef HAVE_TZSET
875 tzset()
876 #endif
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000877
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000878 And I'm lazy and hate C so nyer.
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000879 */
Guido van Rossum10b164a2001-09-25 13:59:01 +0000880#if defined(HAVE_TZNAME) && !defined(__GLIBC__) && !defined(__CYGWIN__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000881 PyObject *otz0, *otz1;
882 tzset();
Guido van Rossum26452411998-09-28 22:07:11 +0000883#ifdef PYOS_OS2
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000884 PyModule_AddIntConstant(m, "timezone", _timezone);
Guido van Rossum26452411998-09-28 22:07:11 +0000885#else /* !PYOS_OS2 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000886 PyModule_AddIntConstant(m, "timezone", timezone);
Guido van Rossum26452411998-09-28 22:07:11 +0000887#endif /* PYOS_OS2 */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000888#ifdef HAVE_ALTZONE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000889 PyModule_AddIntConstant(m, "altzone", altzone);
Guido van Rossumb6775db1994-08-01 11:34:53 +0000890#else
Guido van Rossum26452411998-09-28 22:07:11 +0000891#ifdef PYOS_OS2
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000892 PyModule_AddIntConstant(m, "altzone", _timezone-3600);
Guido van Rossum26452411998-09-28 22:07:11 +0000893#else /* !PYOS_OS2 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000894 PyModule_AddIntConstant(m, "altzone", timezone-3600);
Guido van Rossum26452411998-09-28 22:07:11 +0000895#endif /* PYOS_OS2 */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000896#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000897 PyModule_AddIntConstant(m, "daylight", daylight);
Victor Stinner1b579672011-12-17 05:47:23 +0100898 otz0 = PyUnicode_DecodeLocale(tzname[0], "surrogateescape");
899 otz1 = PyUnicode_DecodeLocale(tzname[1], "surrogateescape");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000900 PyModule_AddObject(m, "tzname", Py_BuildValue("(NN)", otz0, otz1));
Guido van Rossum10b164a2001-09-25 13:59:01 +0000901#else /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/
Martin v. Löwis60a5d722002-10-16 20:28:25 +0000902#ifdef HAVE_STRUCT_TM_TM_ZONE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000903 {
Guido van Rossum234f9421993-06-17 12:35:49 +0000904#define YEAR ((time_t)((365 * 24 + 6) * 3600))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000905 time_t t;
906 struct tm *p;
907 long janzone, julyzone;
908 char janname[10], julyname[10];
909 t = (time((time_t *)0) / YEAR) * YEAR;
910 p = localtime(&t);
911 janzone = -p->tm_gmtoff;
912 strncpy(janname, p->tm_zone ? p->tm_zone : " ", 9);
913 janname[9] = '\0';
914 t += YEAR/2;
915 p = localtime(&t);
916 julyzone = -p->tm_gmtoff;
917 strncpy(julyname, p->tm_zone ? p->tm_zone : " ", 9);
918 julyname[9] = '\0';
Guido van Rossum10b164a2001-09-25 13:59:01 +0000919
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000920 if( janzone < julyzone ) {
921 /* DST is reversed in the southern hemisphere */
922 PyModule_AddIntConstant(m, "timezone", julyzone);
923 PyModule_AddIntConstant(m, "altzone", janzone);
924 PyModule_AddIntConstant(m, "daylight",
925 janzone != julyzone);
926 PyModule_AddObject(m, "tzname",
927 Py_BuildValue("(zz)",
928 julyname, janname));
929 } else {
930 PyModule_AddIntConstant(m, "timezone", janzone);
931 PyModule_AddIntConstant(m, "altzone", julyzone);
932 PyModule_AddIntConstant(m, "daylight",
933 janzone != julyzone);
934 PyModule_AddObject(m, "tzname",
935 Py_BuildValue("(zz)",
936 janname, julyname));
937 }
938 }
Guido van Rossume6a4b7b1997-10-08 15:27:56 +0000939#else
Martin v. Löwis60a5d722002-10-16 20:28:25 +0000940#endif /* HAVE_STRUCT_TM_TM_ZONE */
Tim Peters26ae7cd2001-03-20 03:26:49 +0000941#ifdef __CYGWIN__
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000942 tzset();
943 PyModule_AddIntConstant(m, "timezone", _timezone);
944 PyModule_AddIntConstant(m, "altzone", _timezone-3600);
945 PyModule_AddIntConstant(m, "daylight", _daylight);
946 PyModule_AddObject(m, "tzname",
947 Py_BuildValue("(zz)", _tzname[0], _tzname[1]));
Tim Peters26ae7cd2001-03-20 03:26:49 +0000948#endif /* __CYGWIN__ */
Guido van Rossum10b164a2001-09-25 13:59:01 +0000949#endif /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/
Victor Stinnere0be4232011-10-25 13:06:09 +0200950
951#if defined(HAVE_CLOCK_GETTIME) || defined(HAVE_CLOCK_GETRES)
952#ifdef CLOCK_REALTIME
953 PyModule_AddIntMacro(m, CLOCK_REALTIME);
954#endif
955#ifdef CLOCK_MONOTONIC
956 PyModule_AddIntMacro(m, CLOCK_MONOTONIC);
957#endif
958#ifdef CLOCK_MONOTONIC_RAW
959 PyModule_AddIntMacro(m, CLOCK_MONOTONIC_RAW);
960#endif
961#ifdef CLOCK_PROCESS_CPUTIME_ID
962 PyModule_AddIntMacro(m, CLOCK_PROCESS_CPUTIME_ID);
963#endif
964#ifdef CLOCK_THREAD_CPUTIME_ID
965 PyModule_AddIntMacro(m, CLOCK_THREAD_CPUTIME_ID);
966#endif
967#endif /* HAVE_CLOCK_GETTIME */
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000968}
969
970
971static PyMethodDef time_methods[] = {
Victor Stinner4195b5c2012-02-08 23:03:19 +0100972 {"time", time_time, METH_NOARGS, time_doc},
973#if (defined(MS_WINDOWS) && !defined(__BORLANDC__)) || defined(HAVE_CLOCK)
974 {"clock", time_clock, METH_NOARGS, clock_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000975#endif
Victor Stinnere0be4232011-10-25 13:06:09 +0200976#ifdef HAVE_CLOCK_GETTIME
Victor Stinner4195b5c2012-02-08 23:03:19 +0100977 {"clock_gettime", time_clock_gettime, METH_VARARGS, clock_gettime_doc},
Victor Stinnere0be4232011-10-25 13:06:09 +0200978#endif
979#ifdef HAVE_CLOCK_GETRES
Victor Stinner4195b5c2012-02-08 23:03:19 +0100980 {"clock_getres", time_clock_getres, METH_VARARGS, clock_getres_doc},
Victor Stinnere0be4232011-10-25 13:06:09 +0200981#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000982 {"sleep", time_sleep, METH_VARARGS, sleep_doc},
983 {"gmtime", time_gmtime, METH_VARARGS, gmtime_doc},
984 {"localtime", time_localtime, METH_VARARGS, localtime_doc},
985 {"asctime", time_asctime, METH_VARARGS, asctime_doc},
986 {"ctime", time_ctime, METH_VARARGS, ctime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000987#ifdef HAVE_MKTIME
Victor Stinner4195b5c2012-02-08 23:03:19 +0100988 {"mktime", time_mktime, METH_O, mktime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000989#endif
Victor Stinner8b302012012-02-07 23:29:46 +0100990#ifdef HAVE_PYTIME_MONOTONIC
Victor Stinner4195b5c2012-02-08 23:03:19 +0100991 {"monotonic", time_monotonic, METH_NOARGS, monotonic_doc},
Victor Stinner8b302012012-02-07 23:29:46 +0100992#endif
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000993#ifdef HAVE_STRFTIME
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000994 {"strftime", time_strftime, METH_VARARGS, strftime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000995#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000996 {"strptime", time_strptime, METH_VARARGS, strptime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000997#ifdef HAVE_WORKING_TZSET
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000998 {"tzset", time_tzset, METH_NOARGS, tzset_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000999#endif
Victor Stinner4195b5c2012-02-08 23:03:19 +01001000 {"wallclock", time_wallclock, METH_NOARGS, wallclock_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001001 {NULL, NULL} /* sentinel */
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001002};
1003
1004
1005PyDoc_STRVAR(module_doc,
1006"This module provides various functions to manipulate time values.\n\
1007\n\
1008There are two standard representations of time. One is the number\n\
1009of seconds since the Epoch, in UTC (a.k.a. GMT). It may be an integer\n\
1010or a floating point number (to represent fractions of seconds).\n\
1011The Epoch is system-defined; on Unix, it is generally January 1st, 1970.\n\
1012The actual value can be retrieved by calling gmtime(0).\n\
1013\n\
1014The other representation is a tuple of 9 integers giving local time.\n\
1015The tuple items are:\n\
Alexander Belopolsky03163ac2011-05-02 12:20:52 -04001016 year (including century, e.g. 1998)\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001017 month (1-12)\n\
1018 day (1-31)\n\
1019 hours (0-23)\n\
1020 minutes (0-59)\n\
1021 seconds (0-59)\n\
1022 weekday (0-6, Monday is 0)\n\
1023 Julian day (day in the year, 1-366)\n\
1024 DST (Daylight Savings Time) flag (-1, 0 or 1)\n\
1025If the DST flag is 0, the time is given in the regular time zone;\n\
1026if it is 1, the time is given in the DST time zone;\n\
1027if it is -1, mktime() should guess based on the date and time.\n\
1028\n\
1029Variables:\n\
1030\n\
1031timezone -- difference in seconds between UTC and local standard time\n\
1032altzone -- difference in seconds between UTC and local DST time\n\
1033daylight -- whether local time should reflect DST\n\
1034tzname -- tuple of (standard time zone name, DST time zone name)\n\
1035\n\
1036Functions:\n\
1037\n\
1038time() -- return current time in seconds since the Epoch as a float\n\
1039clock() -- return CPU time since process start as a float\n\
1040sleep() -- delay for a number of seconds given as a float\n\
1041gmtime() -- convert seconds since Epoch to UTC tuple\n\
1042localtime() -- convert seconds since Epoch to local time tuple\n\
1043asctime() -- convert time tuple to string\n\
1044ctime() -- convert time in seconds to string\n\
1045mktime() -- convert local time tuple to seconds since Epoch\n\
1046strftime() -- convert time tuple to string according to format specification\n\
1047strptime() -- parse string to time tuple according to format specification\n\
1048tzset() -- change the local timezone");
1049
1050
Martin v. Löwis1a214512008-06-11 05:26:20 +00001051
1052static struct PyModuleDef timemodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001053 PyModuleDef_HEAD_INIT,
1054 "time",
1055 module_doc,
1056 -1,
1057 time_methods,
1058 NULL,
1059 NULL,
1060 NULL,
1061 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00001062};
1063
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001064PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00001065PyInit_time(void)
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001066{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001067 PyObject *m;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001068 m = PyModule_Create(&timemodule);
1069 if (m == NULL)
1070 return NULL;
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001071
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001072 /* Set, or reset, module variables like time.timezone */
1073 PyInit_timezone(m);
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001074
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001075 if (!initialized) {
1076 PyStructSequence_InitType(&StructTimeType,
1077 &struct_time_type_desc);
1078 }
1079 Py_INCREF(&StructTimeType);
1080 PyModule_AddObject(m, "struct_time", (PyObject*) &StructTimeType);
1081 initialized = 1;
1082 return m;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001083}
1084
Victor Stinner4195b5c2012-02-08 23:03:19 +01001085static double
1086floattime(void)
1087{
1088 _PyTime_timeval t;
1089 _PyTime_gettimeofday(&t);
1090 return (double)t.tv_sec + t.tv_usec*0.000001;
1091}
1092
1093
Guido van Rossumb6775db1994-08-01 11:34:53 +00001094/* Implement floatsleep() for various platforms.
1095 When interrupted (or when another error occurs), return -1 and
1096 set an exception; else return 0. */
1097
1098static int
Guido van Rossuma320fd31995-03-09 12:14:15 +00001099floatsleep(double secs)
Guido van Rossum426035c1991-02-19 12:27:35 +00001100{
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001101/* XXX Should test for MS_WINDOWS first! */
Skip Montanaroeb33e5a2007-08-17 12:57:41 +00001102#if defined(HAVE_SELECT) && !defined(__EMX__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001103 struct timeval t;
1104 double frac;
Victor Stinner48b1ce52011-07-01 13:50:09 +02001105 int err;
1106
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001107 frac = fmod(secs, 1.0);
1108 secs = floor(secs);
1109 t.tv_sec = (long)secs;
1110 t.tv_usec = (long)(frac*1000000.0);
1111 Py_BEGIN_ALLOW_THREADS
Victor Stinner48b1ce52011-07-01 13:50:09 +02001112 err = select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &t);
1113 Py_END_ALLOW_THREADS
1114 if (err != 0) {
Guido van Rossum09cbb011999-11-08 15:32:27 +00001115#ifdef EINTR
Victor Stinner48b1ce52011-07-01 13:50:09 +02001116 if (errno == EINTR) {
1117 if (PyErr_CheckSignals())
1118 return -1;
1119 }
1120 else
Guido van Rossum09cbb011999-11-08 15:32:27 +00001121#endif
Victor Stinner48b1ce52011-07-01 13:50:09 +02001122 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001123 PyErr_SetFromErrno(PyExc_IOError);
1124 return -1;
1125 }
1126 }
Martin v. Löwis02af9642002-01-16 11:04:06 +00001127#elif defined(__WATCOMC__) && !defined(__QNX__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001128 /* XXX Can't interrupt this sleep */
1129 Py_BEGIN_ALLOW_THREADS
1130 delay((int)(secs * 1000 + 0.5)); /* delay() uses milliseconds */
1131 Py_END_ALLOW_THREADS
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001132#elif defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001133 {
1134 double millisecs = secs * 1000.0;
1135 unsigned long ul_millis;
Tim Peters513a1cd2003-01-19 04:54:58 +00001136
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001137 if (millisecs > (double)ULONG_MAX) {
1138 PyErr_SetString(PyExc_OverflowError,
1139 "sleep length is too large");
1140 return -1;
1141 }
1142 Py_BEGIN_ALLOW_THREADS
1143 /* Allow sleep(0) to maintain win32 semantics, and as decreed
1144 * by Guido, only the main thread can be interrupted.
1145 */
1146 ul_millis = (unsigned long)millisecs;
Antoine Pitrou6dd381e2011-11-21 21:26:56 +01001147 if (ul_millis == 0 || !_PyOS_IsMainThread())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001148 Sleep(ul_millis);
1149 else {
1150 DWORD rc;
Antoine Pitrou6dd381e2011-11-21 21:26:56 +01001151 HANDLE hInterruptEvent = _PyOS_SigintEvent();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001152 ResetEvent(hInterruptEvent);
1153 rc = WaitForSingleObject(hInterruptEvent, ul_millis);
1154 if (rc == WAIT_OBJECT_0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001155 Py_BLOCK_THREADS
1156 errno = EINTR;
1157 PyErr_SetFromErrno(PyExc_IOError);
1158 return -1;
1159 }
1160 }
1161 Py_END_ALLOW_THREADS
1162 }
Martin v. Löwis02af9642002-01-16 11:04:06 +00001163#elif defined(PYOS_OS2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001164 /* This Sleep *IS* Interruptable by Exceptions */
1165 Py_BEGIN_ALLOW_THREADS
1166 if (DosSleep(secs * 1000) != NO_ERROR) {
1167 Py_BLOCK_THREADS
1168 PyErr_SetFromErrno(PyExc_IOError);
1169 return -1;
1170 }
1171 Py_END_ALLOW_THREADS
Martin v. Löwis02af9642002-01-16 11:04:06 +00001172#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001173 /* XXX Can't interrupt this sleep */
1174 Py_BEGIN_ALLOW_THREADS
1175 sleep((int)secs);
1176 Py_END_ALLOW_THREADS
Martin v. Löwis02af9642002-01-16 11:04:06 +00001177#endif
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001178
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001179 return 0;
Guido van Rossum80c9d881991-04-16 08:47:51 +00001180}