blob: 03476d97dcead1439fbb956a3a518bf0437b5b4d [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"
Guido van Rossum3f5da241990-12-20 15:06:42 +00004
Guido van Rossum87ce7bb1998-06-09 16:30:31 +00005#include <ctype.h>
6
Victor Stinnerec895392012-04-29 02:41:27 +02007#ifdef HAVE_SYS_TIMES_H
8#include <sys/times.h>
9#endif
10
Thomas Wouters0e3f5912006-08-11 14:57:12 +000011#ifdef HAVE_SYS_TYPES_H
Guido van Rossumb6775db1994-08-01 11:34:53 +000012#include <sys/types.h>
Victor Stinnerec895392012-04-29 02:41:27 +020013#endif
14
15#if defined(HAVE_SYS_RESOURCE_H)
16#include <sys/resource.h>
17#endif
Guido van Rossum6d946f91992-08-14 13:49:30 +000018
Guido van Rossumb6775db1994-08-01 11:34:53 +000019#ifdef QUICKWIN
20#include <io.h>
21#endif
22
Guido van Rossum7bf22de1997-12-02 20:34:19 +000023#if defined(__WATCOMC__) && !defined(__QNX__)
Guido van Rossumbceeac81996-05-23 22:53:47 +000024#include <i86.h>
25#else
Guido van Rossumcac6c721996-09-06 13:34:02 +000026#ifdef MS_WINDOWS
Mark Hammond975e3922002-07-16 01:29:19 +000027#define WIN32_LEAN_AND_MEAN
Guido van Rossum258ccd42001-03-02 06:53:29 +000028#include <windows.h>
Mark Hammond975e3922002-07-16 01:29:19 +000029#include "pythread.h"
30
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000031#if defined(__BORLANDC__)
Guido van Rossumb2fb3641996-09-07 00:47:35 +000032/* These overrides not needed for Win32 */
Guido van Rossumb6775db1994-08-01 11:34:53 +000033#define timezone _timezone
Guido van Rossumcc081121995-03-14 15:05:41 +000034#define tzname _tzname
35#define daylight _daylight
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000036#endif /* __BORLANDC__ */
Guido van Rossumcac6c721996-09-06 13:34:02 +000037#endif /* MS_WINDOWS */
Guido van Rossum7bf22de1997-12-02 20:34:19 +000038#endif /* !__WATCOMC__ || __QNX__ */
Guido van Rossum234f9421993-06-17 12:35:49 +000039
Andrew MacIntyre7bf68332002-03-03 02:59:16 +000040#if defined(PYOS_OS2)
41#define INCL_DOS
42#define INCL_ERRORS
43#include <os2.h>
44#endif
45
Guido van Rossum8e9ebfd1997-11-22 21:53:48 +000046#if defined(PYCC_VACPP)
Guido van Rossum26452411998-09-28 22:07:11 +000047#include <sys/time.h>
Guido van Rossum8e9ebfd1997-11-22 21:53:48 +000048#endif
49
Victor Stinnera8ec5ea2012-03-13 00:25:42 +010050#if defined(__APPLE__)
51#include <mach/mach_time.h>
52#endif
53
Guido van Rossum234f9421993-06-17 12:35:49 +000054/* Forward declarations */
Tim Petersdbd9ba62000-07-09 03:09:57 +000055static int floatsleep(double);
Victor Stinnerec895392012-04-29 02:41:27 +020056static PyObject* floattime(_Py_clock_info_t *info);
57
58#ifdef MS_WINDOWS
59static OSVERSIONINFOEX winver;
60#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000061
Barry Warsaw9a2a8a81996-12-06 23:32:14 +000062static PyObject *
Victor Stinner4195b5c2012-02-08 23:03:19 +010063time_time(PyObject *self, PyObject *unused)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000064{
Victor Stinnerec895392012-04-29 02:41:27 +020065 return floattime(NULL);
Guido van Rossumb6775db1994-08-01 11:34:53 +000066}
67
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000068PyDoc_STRVAR(time_doc,
Victor Stinner4195b5c2012-02-08 23:03:19 +010069"time() -> floating point number\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +000070\n\
71Return the current time in seconds since the Epoch.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000072Fractions of a second may be present if the system clock provides them.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +000073
Victor Stinner85fdfa82012-01-27 00:38:48 +010074#if defined(HAVE_CLOCK)
75
76#ifndef CLOCKS_PER_SEC
77#ifdef CLK_TCK
78#define CLOCKS_PER_SEC CLK_TCK
79#else
80#define CLOCKS_PER_SEC 1000000
81#endif
82#endif
83
Victor Stinner4195b5c2012-02-08 23:03:19 +010084static PyObject *
Victor Stinnerec895392012-04-29 02:41:27 +020085floatclock(_Py_clock_info_t *info)
Victor Stinner85fdfa82012-01-27 00:38:48 +010086{
Victor Stinner4195b5c2012-02-08 23:03:19 +010087 clock_t value;
88 value = clock();
89 if (value == (clock_t)-1) {
Victor Stinner85fdfa82012-01-27 00:38:48 +010090 PyErr_SetString(PyExc_RuntimeError,
91 "the processor time used is not available "
92 "or its value cannot be represented");
Victor Stinner4195b5c2012-02-08 23:03:19 +010093 return NULL;
Victor Stinner85fdfa82012-01-27 00:38:48 +010094 }
Victor Stinnerec895392012-04-29 02:41:27 +020095 if (info) {
96 info->implementation = "clock()";
97 info->resolution = 1.0 / (double)CLOCKS_PER_SEC;
Benjamin Peterson49a69e42012-05-01 09:38:34 -040098 info->monotonic = 1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +020099 info->adjustable = 0;
Victor Stinnerec895392012-04-29 02:41:27 +0200100 }
Victor Stinner4195b5c2012-02-08 23:03:19 +0100101 return PyFloat_FromDouble((double)value / CLOCKS_PER_SEC);
Victor Stinner85fdfa82012-01-27 00:38:48 +0100102}
103#endif /* HAVE_CLOCK */
104
Thomas Wouters477c8d52006-05-27 19:21:47 +0000105#if defined(MS_WINDOWS) && !defined(__BORLANDC__)
Victor Stinnerec895392012-04-29 02:41:27 +0200106#define WIN32_PERF_COUNTER
Victor Stinner9122fdd2011-07-04 13:55:40 +0200107/* Win32 has better clock replacement; we have our own version, due to Mark
108 Hammond and Tim Peters */
Victor Stinnerec895392012-04-29 02:41:27 +0200109static int
110win_perf_counter(_Py_clock_info_t *info, PyObject **result)
Guido van Rossum3917c221997-04-02 05:35:28 +0000111{
Victor Stinner8b302012012-02-07 23:29:46 +0100112 static LONGLONG cpu_frequency = 0;
Victor Stinner4195b5c2012-02-08 23:03:19 +0100113 static LONGLONG ctrStart;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000114 LARGE_INTEGER now;
Victor Stinner4195b5c2012-02-08 23:03:19 +0100115 double diff;
Guido van Rossum3917c221997-04-02 05:35:28 +0000116
Victor Stinner8b302012012-02-07 23:29:46 +0100117 if (cpu_frequency == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000118 LARGE_INTEGER freq;
Victor Stinner8b302012012-02-07 23:29:46 +0100119 QueryPerformanceCounter(&now);
Victor Stinner4195b5c2012-02-08 23:03:19 +0100120 ctrStart = now.QuadPart;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000121 if (!QueryPerformanceFrequency(&freq) || freq.QuadPart == 0) {
122 /* Unlikely to happen - this works on all intel
123 machines at least! Revert to clock() */
Victor Stinnerec895392012-04-29 02:41:27 +0200124 *result = NULL;
125 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000126 }
Victor Stinner8b302012012-02-07 23:29:46 +0100127 cpu_frequency = freq.QuadPart;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000128 }
129 QueryPerformanceCounter(&now);
Victor Stinner4195b5c2012-02-08 23:03:19 +0100130 diff = (double)(now.QuadPart - ctrStart);
Victor Stinnerec895392012-04-29 02:41:27 +0200131 if (info) {
132 info->implementation = "QueryPerformanceCounter()";
133 info->resolution = 1.0 / (double)cpu_frequency;
Benjamin Peterson49a69e42012-05-01 09:38:34 -0400134 info->monotonic = 1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +0200135 info->adjustable = 0;
Victor Stinnerec895392012-04-29 02:41:27 +0200136 }
137 *result = PyFloat_FromDouble(diff / (double)cpu_frequency);
138 return 0;
Guido van Rossum3917c221997-04-02 05:35:28 +0000139}
Victor Stinner8b302012012-02-07 23:29:46 +0100140#endif
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000141
Victor Stinnerec895392012-04-29 02:41:27 +0200142#if defined(WIN32_PERF_COUNTER) || defined(HAVE_CLOCK)
143#define PYCLOCK
144static PyObject*
145pyclock(_Py_clock_info_t *info)
146{
147#ifdef WIN32_PERF_COUNTER
148 PyObject *res;
149 if (win_perf_counter(info, &res) == 0)
150 return res;
151#endif
152 return floatclock(info);
153}
154
Victor Stinner9122fdd2011-07-04 13:55:40 +0200155static PyObject *
Victor Stinner4195b5c2012-02-08 23:03:19 +0100156time_clock(PyObject *self, PyObject *unused)
Victor Stinner9122fdd2011-07-04 13:55:40 +0200157{
Victor Stinnerec895392012-04-29 02:41:27 +0200158 return pyclock(NULL);
Victor Stinner9122fdd2011-07-04 13:55:40 +0200159}
Victor Stinner9122fdd2011-07-04 13:55:40 +0200160
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000161PyDoc_STRVAR(clock_doc,
Victor Stinner4195b5c2012-02-08 23:03:19 +0100162"clock() -> floating point number\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000163\n\
164Return the CPU time or real time since the start of the process or since\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000165the first call to clock(). This has as much precision as the system\n\
166records.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000167#endif
168
Victor Stinnere0be4232011-10-25 13:06:09 +0200169#ifdef HAVE_CLOCK_GETTIME
170static PyObject *
Victor Stinner4195b5c2012-02-08 23:03:19 +0100171time_clock_gettime(PyObject *self, PyObject *args)
Victor Stinnere0be4232011-10-25 13:06:09 +0200172{
173 int ret;
Victor Stinnerb8d01692012-04-13 23:44:05 +0200174 int clk_id;
Victor Stinnere0be4232011-10-25 13:06:09 +0200175 struct timespec tp;
176
Victor Stinner4195b5c2012-02-08 23:03:19 +0100177 if (!PyArg_ParseTuple(args, "i:clock_gettime", &clk_id))
Victor Stinnere0be4232011-10-25 13:06:09 +0200178 return NULL;
179
180 ret = clock_gettime((clockid_t)clk_id, &tp);
Antoine Pitrou2c085602012-01-18 01:41:44 +0100181 if (ret != 0) {
Victor Stinnere0be4232011-10-25 13:06:09 +0200182 PyErr_SetFromErrno(PyExc_IOError);
Antoine Pitrou2c085602012-01-18 01:41:44 +0100183 return NULL;
184 }
Victor Stinner4195b5c2012-02-08 23:03:19 +0100185 return PyFloat_FromDouble(tp.tv_sec + tp.tv_nsec * 1e-9);
Victor Stinnere0be4232011-10-25 13:06:09 +0200186}
187
188PyDoc_STRVAR(clock_gettime_doc,
Victor Stinner4195b5c2012-02-08 23:03:19 +0100189"clock_gettime(clk_id) -> floating point number\n\
Victor Stinnere0be4232011-10-25 13:06:09 +0200190\n\
191Return the time of the specified clock clk_id.");
Victor Stinner30d79472012-04-03 00:45:07 +0200192
193static PyObject *
194time_clock_settime(PyObject *self, PyObject *args)
195{
Victor Stinnerb8d01692012-04-13 23:44:05 +0200196 int clk_id;
Victor Stinner30d79472012-04-03 00:45:07 +0200197 PyObject *obj;
Antoine Pitroucf8a1e52013-04-17 22:06:44 +0200198 time_t tv_sec;
199 long tv_nsec;
Victor Stinner30d79472012-04-03 00:45:07 +0200200 struct timespec tp;
201 int ret;
202
203 if (!PyArg_ParseTuple(args, "iO:clock_settime", &clk_id, &obj))
204 return NULL;
205
Antoine Pitroucf8a1e52013-04-17 22:06:44 +0200206 if (_PyTime_ObjectToTimespec(obj, &tv_sec, &tv_nsec) == -1)
Victor Stinner30d79472012-04-03 00:45:07 +0200207 return NULL;
Antoine Pitroucf8a1e52013-04-17 22:06:44 +0200208 tp.tv_sec = tv_sec;
209 tp.tv_nsec = tv_nsec;
Victor Stinner30d79472012-04-03 00:45:07 +0200210
211 ret = clock_settime((clockid_t)clk_id, &tp);
212 if (ret != 0) {
213 PyErr_SetFromErrno(PyExc_IOError);
214 return NULL;
215 }
216 Py_RETURN_NONE;
217}
218
219PyDoc_STRVAR(clock_settime_doc,
220"clock_settime(clk_id, time)\n\
221\n\
222Set the time of the specified clock clk_id.");
Victor Stinnere0be4232011-10-25 13:06:09 +0200223
Victor Stinnere0be4232011-10-25 13:06:09 +0200224static PyObject *
Victor Stinner4195b5c2012-02-08 23:03:19 +0100225time_clock_getres(PyObject *self, PyObject *args)
Victor Stinnere0be4232011-10-25 13:06:09 +0200226{
227 int ret;
Victor Stinnerb8d01692012-04-13 23:44:05 +0200228 int clk_id;
Victor Stinnere0be4232011-10-25 13:06:09 +0200229 struct timespec tp;
230
Victor Stinner4195b5c2012-02-08 23:03:19 +0100231 if (!PyArg_ParseTuple(args, "i:clock_getres", &clk_id))
Victor Stinnere0be4232011-10-25 13:06:09 +0200232 return NULL;
233
234 ret = clock_getres((clockid_t)clk_id, &tp);
Antoine Pitrou2c085602012-01-18 01:41:44 +0100235 if (ret != 0) {
Victor Stinnere0be4232011-10-25 13:06:09 +0200236 PyErr_SetFromErrno(PyExc_IOError);
Antoine Pitrou2c085602012-01-18 01:41:44 +0100237 return NULL;
238 }
Victor Stinner4195b5c2012-02-08 23:03:19 +0100239
240 return PyFloat_FromDouble(tp.tv_sec + tp.tv_nsec * 1e-9);
Victor Stinnere0be4232011-10-25 13:06:09 +0200241}
242
243PyDoc_STRVAR(clock_getres_doc,
Victor Stinner4195b5c2012-02-08 23:03:19 +0100244"clock_getres(clk_id) -> floating point number\n\
Victor Stinnere0be4232011-10-25 13:06:09 +0200245\n\
246Return the resolution (precision) of the specified clock clk_id.");
Victor Stinnerb8d01692012-04-13 23:44:05 +0200247#endif /* HAVE_CLOCK_GETTIME */
Victor Stinnere0be4232011-10-25 13:06:09 +0200248
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000249static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000250time_sleep(PyObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000251{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000252 double secs;
253 if (!PyArg_ParseTuple(args, "d:sleep", &secs))
254 return NULL;
Victor Stinner7f53a502011-07-05 22:00:25 +0200255 if (secs < 0) {
256 PyErr_SetString(PyExc_ValueError,
257 "sleep length must be non-negative");
258 return NULL;
259 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000260 if (floatsleep(secs) != 0)
261 return NULL;
262 Py_INCREF(Py_None);
263 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000264}
265
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000266PyDoc_STRVAR(sleep_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000267"sleep(seconds)\n\
268\n\
269Delay execution for a given number of seconds. The argument may be\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000270a floating point number for subsecond precision.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000271
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000272static PyStructSequence_Field struct_time_type_fields[] = {
Alexander Belopolsky69f3fd02010-06-05 15:04:51 +0000273 {"tm_year", "year, for example, 1993"},
274 {"tm_mon", "month of year, range [1, 12]"},
275 {"tm_mday", "day of month, range [1, 31]"},
276 {"tm_hour", "hours, range [0, 23]"},
277 {"tm_min", "minutes, range [0, 59]"},
278 {"tm_sec", "seconds, range [0, 61])"},
279 {"tm_wday", "day of week, range [0, 6], Monday is 0"},
280 {"tm_yday", "day of year, range [1, 366]"},
281 {"tm_isdst", "1 if summer time is in effect, 0 if not, and -1 if unknown"},
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400282#ifdef HAVE_STRUCT_TM_TM_ZONE
283 {"tm_zone", "abbreviation of timezone name"},
284 {"tm_gmtoff", "offset from UTC in seconds"},
285#endif /* HAVE_STRUCT_TM_TM_ZONE */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000286 {0}
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000287};
288
289static PyStructSequence_Desc struct_time_type_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000290 "time.struct_time",
Alexander Belopolsky69f3fd02010-06-05 15:04:51 +0000291 "The time value as returned by gmtime(), localtime(), and strptime(), and\n"
292 " accepted by asctime(), mktime() and strftime(). May be considered as a\n"
293 " sequence of 9 integers.\n\n"
294 " Note that several fields' values are not the same as those defined by\n"
295 " the C language standard for struct tm. For example, the value of the\n"
296 " field tm_year is the actual year, not year - 1900. See individual\n"
297 " fields' descriptions for details.",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000298 struct_time_type_fields,
299 9,
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000300};
Tim Peters9ad4b682002-02-13 05:14:18 +0000301
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000302static int initialized;
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000303static PyTypeObject StructTimeType;
304
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400305
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000306static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000307tmtotuple(struct tm *p)
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000308{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000309 PyObject *v = PyStructSequence_New(&StructTimeType);
310 if (v == NULL)
311 return NULL;
Tim Peters9ad4b682002-02-13 05:14:18 +0000312
Christian Heimes217cfd12007-12-02 14:31:20 +0000313#define SET(i,val) PyStructSequence_SET_ITEM(v, i, PyLong_FromLong((long) val))
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000314
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000315 SET(0, p->tm_year + 1900);
316 SET(1, p->tm_mon + 1); /* Want January == 1 */
317 SET(2, p->tm_mday);
318 SET(3, p->tm_hour);
319 SET(4, p->tm_min);
320 SET(5, p->tm_sec);
321 SET(6, (p->tm_wday + 6) % 7); /* Want Monday == 0 */
322 SET(7, p->tm_yday + 1); /* Want January, 1 == 1 */
323 SET(8, p->tm_isdst);
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400324#ifdef HAVE_STRUCT_TM_TM_ZONE
325 PyStructSequence_SET_ITEM(v, 9,
326 PyUnicode_DecodeLocale(p->tm_zone, "surrogateescape"));
327 SET(10, p->tm_gmtoff);
328#endif /* HAVE_STRUCT_TM_TM_ZONE */
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000329#undef SET
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000330 if (PyErr_Occurred()) {
331 Py_XDECREF(v);
332 return NULL;
333 }
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000334
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000335 return v;
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000336}
337
Fred Drakef901abd2004-08-03 17:58:55 +0000338/* Parse arg tuple that can contain an optional float-or-None value;
339 format needs to be "|O:name".
340 Returns non-zero on success (parallels PyArg_ParseTuple).
341*/
342static int
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100343parse_time_t_args(PyObject *args, char *format, time_t *pwhen)
Fred Drakef901abd2004-08-03 17:58:55 +0000344{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000345 PyObject *ot = NULL;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100346 time_t whent;
Fred Drakef901abd2004-08-03 17:58:55 +0000347
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000348 if (!PyArg_ParseTuple(args, format, &ot))
349 return 0;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100350 if (ot == NULL || ot == Py_None) {
351 whent = time(NULL);
352 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000353 else {
Victor Stinner5d272cc2012-03-13 13:35:55 +0100354 if (_PyTime_ObjectToTime_t(ot, &whent) == -1)
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100355 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000356 }
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100357 *pwhen = whent;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000358 return 1;
Fred Drakef901abd2004-08-03 17:58:55 +0000359}
360
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000361static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000362time_gmtime(PyObject *self, PyObject *args)
Guido van Rossum234f9421993-06-17 12:35:49 +0000363{
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100364 time_t when;
365 struct tm buf, *local;
366
367 if (!parse_time_t_args(args, "|O:gmtime", &when))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000368 return NULL;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100369
370 errno = 0;
371 local = gmtime(&when);
372 if (local == NULL) {
373#ifdef EINVAL
374 if (errno == 0)
375 errno = EINVAL;
376#endif
377 return PyErr_SetFromErrno(PyExc_OSError);
378 }
379 buf = *local;
380 return tmtotuple(&buf);
Guido van Rossum234f9421993-06-17 12:35:49 +0000381}
382
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000383PyDoc_STRVAR(gmtime_doc,
Christian Heimes9a371592007-12-28 14:08:13 +0000384"gmtime([seconds]) -> (tm_year, tm_mon, tm_mday, tm_hour, tm_min,\n\
Fred Drake193a3f62002-03-12 21:38:49 +0000385 tm_sec, tm_wday, tm_yday, tm_isdst)\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000386\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000387Convert seconds since the Epoch to a time tuple expressing UTC (a.k.a.\n\
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400388GMT). When 'seconds' is not passed in, convert the current time instead.\n\
389\n\
390If the platform supports the tm_gmtoff and tm_zone, they are available as\n\
391attributes only.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000392
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100393static int
394pylocaltime(time_t *timep, struct tm *result)
395{
396 struct tm *local;
397
398 assert (timep != NULL);
399 local = localtime(timep);
400 if (local == NULL) {
401 /* unconvertible time */
402#ifdef EINVAL
403 if (errno == 0)
404 errno = EINVAL;
405#endif
406 PyErr_SetFromErrno(PyExc_OSError);
407 return -1;
408 }
409 *result = *local;
410 return 0;
411}
412
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000413static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000414time_localtime(PyObject *self, PyObject *args)
Guido van Rossum234f9421993-06-17 12:35:49 +0000415{
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100416 time_t when;
417 struct tm buf;
418
419 if (!parse_time_t_args(args, "|O:localtime", &when))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000420 return NULL;
Alexander Belopolskyd9738242012-06-12 16:14:17 -0400421 if (pylocaltime(&when, &buf) == -1)
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100422 return NULL;
423 return tmtotuple(&buf);
Guido van Rossum234f9421993-06-17 12:35:49 +0000424}
425
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000426PyDoc_STRVAR(localtime_doc,
Christian Heimes9a371592007-12-28 14:08:13 +0000427"localtime([seconds]) -> (tm_year,tm_mon,tm_mday,tm_hour,tm_min,\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000428 tm_sec,tm_wday,tm_yday,tm_isdst)\n\
Martin v. Löwisb3cfc1d2001-12-02 12:27:43 +0000429\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000430Convert seconds since the Epoch to a time tuple expressing local time.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000431When 'seconds' is not passed in, convert the current time instead.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000432
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000433/* Convert 9-item tuple to tm structure. Return 1 on success, set
434 * an exception and return 0 on error.
435 */
Guido van Rossum9e90a671993-06-24 11:10:19 +0000436static int
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000437gettmarg(PyObject *args, struct tm *p)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000438{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000439 int y;
Guido van Rossumcfbaecc1998-08-25 14:51:12 +0000440
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000441 memset((void *) p, '\0', sizeof(struct tm));
Guido van Rossumb9081262007-08-25 03:14:09 +0000442
Alexander Belopolsky610e5442011-01-06 21:57:06 +0000443 if (!PyTuple_Check(args)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000444 PyErr_SetString(PyExc_TypeError,
445 "Tuple or struct_time argument required");
446 return 0;
447 }
Skip Montanaro41cfce92007-08-24 21:11:00 +0000448
Alexander Belopolsky610e5442011-01-06 21:57:06 +0000449 if (!PyArg_ParseTuple(args, "iiiiiiiii",
450 &y, &p->tm_mon, &p->tm_mday,
451 &p->tm_hour, &p->tm_min, &p->tm_sec,
452 &p->tm_wday, &p->tm_yday, &p->tm_isdst))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000453 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000454 p->tm_year = y - 1900;
455 p->tm_mon--;
456 p->tm_wday = (p->tm_wday + 1) % 7;
457 p->tm_yday--;
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400458#ifdef HAVE_STRUCT_TM_TM_ZONE
459 if (Py_TYPE(args) == &StructTimeType) {
460 PyObject *item;
461 item = PyTuple_GET_ITEM(args, 9);
462 p->tm_zone = item == Py_None ? NULL : _PyUnicode_AsString(item);
463 item = PyTuple_GET_ITEM(args, 10);
464 p->tm_gmtoff = item == Py_None ? 0 : PyLong_AsLong(item);
465 if (PyErr_Occurred())
466 return 0;
467 }
468#endif /* HAVE_STRUCT_TM_TM_ZONE */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000469 return 1;
Guido van Rossum9e90a671993-06-24 11:10:19 +0000470}
471
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000472/* Check values of the struct tm fields before it is passed to strftime() and
473 * asctime(). Return 1 if all values are valid, otherwise set an exception
474 * and returns 0.
475 */
Victor Stinneref128102010-10-07 01:00:52 +0000476static int
477checktm(struct tm* buf)
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000478{
Victor Stinneref128102010-10-07 01:00:52 +0000479 /* Checks added to make sure strftime() and asctime() does not crash Python by
480 indexing blindly into some array for a textual representation
481 by some bad index (fixes bug #897625 and #6608).
482
483 Also support values of zero from Python code for arguments in which
484 that is out of range by forcing that value to the lowest value that
485 is valid (fixed bug #1520914).
486
487 Valid ranges based on what is allowed in struct tm:
488
489 - tm_year: [0, max(int)] (1)
490 - tm_mon: [0, 11] (2)
491 - tm_mday: [1, 31]
492 - tm_hour: [0, 23]
493 - tm_min: [0, 59]
494 - tm_sec: [0, 60]
495 - tm_wday: [0, 6] (1)
496 - tm_yday: [0, 365] (2)
497 - tm_isdst: [-max(int), max(int)]
498
499 (1) gettmarg() handles bounds-checking.
500 (2) Python's acceptable range is one greater than the range in C,
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000501 thus need to check against automatic decrement by gettmarg().
502 */
503 if (buf->tm_mon == -1)
504 buf->tm_mon = 0;
505 else if (buf->tm_mon < 0 || buf->tm_mon > 11) {
506 PyErr_SetString(PyExc_ValueError, "month out of range");
507 return 0;
508 }
509 if (buf->tm_mday == 0)
510 buf->tm_mday = 1;
511 else if (buf->tm_mday < 0 || buf->tm_mday > 31) {
512 PyErr_SetString(PyExc_ValueError, "day of month out of range");
513 return 0;
514 }
515 if (buf->tm_hour < 0 || buf->tm_hour > 23) {
516 PyErr_SetString(PyExc_ValueError, "hour out of range");
517 return 0;
518 }
519 if (buf->tm_min < 0 || buf->tm_min > 59) {
520 PyErr_SetString(PyExc_ValueError, "minute out of range");
521 return 0;
522 }
523 if (buf->tm_sec < 0 || buf->tm_sec > 61) {
524 PyErr_SetString(PyExc_ValueError, "seconds out of range");
525 return 0;
526 }
527 /* tm_wday does not need checking of its upper-bound since taking
528 ``% 7`` in gettmarg() automatically restricts the range. */
529 if (buf->tm_wday < 0) {
530 PyErr_SetString(PyExc_ValueError, "day of week out of range");
531 return 0;
532 }
533 if (buf->tm_yday == -1)
534 buf->tm_yday = 0;
535 else if (buf->tm_yday < 0 || buf->tm_yday > 365) {
536 PyErr_SetString(PyExc_ValueError, "day of year out of range");
537 return 0;
538 }
539 return 1;
540}
541
Victor Stinnerc1f32ca2011-10-14 02:36:13 +0200542#ifdef MS_WINDOWS
543 /* wcsftime() doesn't format correctly time zones, see issue #10653 */
544# undef HAVE_WCSFTIME
545#endif
546
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000547#ifdef HAVE_STRFTIME
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000548#ifdef HAVE_WCSFTIME
549#define time_char wchar_t
550#define format_time wcsftime
551#define time_strlen wcslen
552#else
553#define time_char char
554#define format_time strftime
555#define time_strlen strlen
556#endif
557
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000558static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000559time_strftime(PyObject *self, PyObject *args)
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000560{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000561 PyObject *tup = NULL;
562 struct tm buf;
563 const time_char *fmt;
Victor Stinnerb2904782010-09-29 10:34:19 +0000564#ifdef HAVE_WCSFTIME
565 wchar_t *format;
566#else
567 PyObject *format;
568#endif
Victor Stinneref128102010-10-07 01:00:52 +0000569 PyObject *format_arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000570 size_t fmtlen, buflen;
Victor Stinnerb2904782010-09-29 10:34:19 +0000571 time_char *outbuf = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000572 size_t i;
Victor Stinnerb2904782010-09-29 10:34:19 +0000573 PyObject *ret = NULL;
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000574
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000575 memset((void *) &buf, '\0', sizeof(buf));
Guido van Rossum1f41f841998-04-27 19:04:26 +0000576
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000577 /* Will always expect a unicode string to be passed as format.
578 Given that there's no str type anymore in py3k this seems safe.
579 */
Victor Stinneref128102010-10-07 01:00:52 +0000580 if (!PyArg_ParseTuple(args, "U|O:strftime", &format_arg, &tup))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000581 return NULL;
Thomas Woutersfe385252001-01-19 23:16:56 +0000582
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000583 if (tup == NULL) {
584 time_t tt = time(NULL);
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100585 if (pylocaltime(&tt, &buf) == -1)
586 return NULL;
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000587 }
588 else if (!gettmarg(tup, &buf) || !checktm(&buf))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000589 return NULL;
Guido van Rossum10b164a2001-09-25 13:59:01 +0000590
Victor Stinner36b82d82013-06-25 02:33:53 +0200591#if defined(_MSC_VER) || defined(sun) || defined(_AIX)
Victor Stinner73ea29c2011-01-08 01:56:31 +0000592 if (buf.tm_year + 1900 < 1 || 9999 < buf.tm_year + 1900) {
Victor Stinner6f0e4f92011-03-21 02:14:53 +0100593 PyErr_SetString(PyExc_ValueError,
594 "strftime() requires year in [1; 9999]");
Alexander Belopolsky0dd06f42011-01-08 01:23:02 +0000595 return NULL;
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000596 }
Victor Stinner73ea29c2011-01-08 01:56:31 +0000597#endif
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000598
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000599 /* Normalize tm_isdst just in case someone foolishly implements %Z
600 based on the assumption that tm_isdst falls within the range of
601 [-1, 1] */
602 if (buf.tm_isdst < -1)
603 buf.tm_isdst = -1;
604 else if (buf.tm_isdst > 1)
605 buf.tm_isdst = 1;
Brett Cannond1080a32004-03-02 04:38:10 +0000606
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000607#ifdef HAVE_WCSFTIME
Victor Stinnerbeb4135b2010-10-07 01:02:42 +0000608 format = PyUnicode_AsWideCharString(format_arg, NULL);
Victor Stinnerb2904782010-09-29 10:34:19 +0000609 if (format == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000610 return NULL;
Victor Stinnerb2904782010-09-29 10:34:19 +0000611 fmt = format;
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000612#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000613 /* Convert the unicode string to an ascii one */
Victor Stinner1b579672011-12-17 05:47:23 +0100614 format = PyUnicode_EncodeLocale(format_arg, "surrogateescape");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000615 if (format == NULL)
616 return NULL;
617 fmt = PyBytes_AS_STRING(format);
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000618#endif
Amaury Forgeot d'Arcb5be6d42009-03-02 23:52:57 +0000619
Stefan Krah4aea7d32012-02-27 16:30:26 +0100620#if defined(MS_WINDOWS) && !defined(HAVE_WCSFTIME)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000621 /* check that the format string contains only valid directives */
Victor Stinner5a3ff792011-10-16 19:08:23 +0200622 for(outbuf = strchr(fmt, '%');
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000623 outbuf != NULL;
Victor Stinner5a3ff792011-10-16 19:08:23 +0200624 outbuf = strchr(outbuf+2, '%'))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000625 {
626 if (outbuf[1]=='#')
627 ++outbuf; /* not documented by python, */
628 if (outbuf[1]=='\0' ||
Victor Stinner5a3ff792011-10-16 19:08:23 +0200629 !strchr("aAbBcdHIjmMpSUwWxXyYzZ%", outbuf[1]))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000630 {
631 PyErr_SetString(PyExc_ValueError, "Invalid format string");
Stefan Krah4aea7d32012-02-27 16:30:26 +0100632 Py_DECREF(format);
633 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000634 }
635 }
Amaury Forgeot d'Arcb5be6d42009-03-02 23:52:57 +0000636#endif
637
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000638 fmtlen = time_strlen(fmt);
Guido van Rossumc222ec21999-02-23 00:00:10 +0000639
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000640 /* I hate these functions that presume you know how big the output
641 * will be ahead of time...
642 */
643 for (i = 1024; ; i += i) {
Victor Stinner136ea492011-12-17 22:37:18 +0100644#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100645 int err;
Victor Stinner136ea492011-12-17 22:37:18 +0100646#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000647 outbuf = (time_char *)PyMem_Malloc(i*sizeof(time_char));
648 if (outbuf == NULL) {
Victor Stinnerb2904782010-09-29 10:34:19 +0000649 PyErr_NoMemory();
650 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000651 }
652 buflen = format_time(outbuf, i, fmt, &buf);
Victor Stinner136ea492011-12-17 22:37:18 +0100653#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100654 err = errno;
Victor Stinner136ea492011-12-17 22:37:18 +0100655#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000656 if (buflen > 0 || i >= 256 * fmtlen) {
657 /* If the buffer is 256 times as long as the format,
658 it's probably not failing for lack of room!
659 More likely, the format yields an empty result,
660 e.g. an empty format, or %Z when the timezone
661 is unknown. */
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000662#ifdef HAVE_WCSFTIME
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000663 ret = PyUnicode_FromWideChar(outbuf, buflen);
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000664#else
Victor Stinner1b579672011-12-17 05:47:23 +0100665 ret = PyUnicode_DecodeLocaleAndSize(outbuf, buflen,
666 "surrogateescape");
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000667#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000668 PyMem_Free(outbuf);
Victor Stinnerb2904782010-09-29 10:34:19 +0000669 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000670 }
671 PyMem_Free(outbuf);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000672#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000673 /* VisualStudio .NET 2005 does this properly */
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100674 if (buflen == 0 && err == EINVAL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000675 PyErr_SetString(PyExc_ValueError, "Invalid format string");
Victor Stinnerb2904782010-09-29 10:34:19 +0000676 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000677 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000678#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000679 }
Victor Stinnerb2904782010-09-29 10:34:19 +0000680#ifdef HAVE_WCSFTIME
681 PyMem_Free(format);
682#else
683 Py_DECREF(format);
684#endif
685 return ret;
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000686}
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000687
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000688#undef time_char
689#undef format_time
690
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000691PyDoc_STRVAR(strftime_doc,
Thomas Woutersfe385252001-01-19 23:16:56 +0000692"strftime(format[, tuple]) -> string\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000693\n\
694Convert a time tuple to a string according to a format specification.\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000695See the library reference manual for formatting codes. When the time tuple\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000696is not present, current time as returned by localtime() is used.");
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000697#endif /* HAVE_STRFTIME */
698
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000699static PyObject *
700time_strptime(PyObject *self, PyObject *args)
701{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000702 PyObject *strptime_module = PyImport_ImportModuleNoBlock("_strptime");
703 PyObject *strptime_result;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200704 _Py_IDENTIFIER(_strptime_time);
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000705
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000706 if (!strptime_module)
707 return NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200708 strptime_result = _PyObject_CallMethodId(strptime_module,
709 &PyId__strptime_time, "O", args);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000710 Py_DECREF(strptime_module);
711 return strptime_result;
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000712}
713
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000714
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000715PyDoc_STRVAR(strptime_doc,
Brett Cannon20def8b2003-07-01 05:16:08 +0000716"strptime(string, format) -> struct_time\n\
Martin v. Löwisb3cfc1d2001-12-02 12:27:43 +0000717\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000718Parse a string to a time tuple according to a format specification.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000719See the library reference manual for formatting codes (same as strftime()).");
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000720
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000721static PyObject *
722_asctime(struct tm *timeptr)
723{
724 /* Inspired by Open Group reference implementation available at
725 * http://pubs.opengroup.org/onlinepubs/009695399/functions/asctime.html */
Victor Stinner499dfcf2011-03-21 13:26:24 +0100726 static char wday_name[7][4] = {
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000727 "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
728 };
Victor Stinner499dfcf2011-03-21 13:26:24 +0100729 static char mon_name[12][4] = {
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000730 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
731 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
732 };
Victor Stinner499dfcf2011-03-21 13:26:24 +0100733 return PyUnicode_FromFormat(
734 "%s %s%3d %.2d:%.2d:%.2d %d",
735 wday_name[timeptr->tm_wday],
736 mon_name[timeptr->tm_mon],
737 timeptr->tm_mday, timeptr->tm_hour,
738 timeptr->tm_min, timeptr->tm_sec,
739 1900 + timeptr->tm_year);
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000740}
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000741
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000742static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000743time_asctime(PyObject *self, PyObject *args)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000744{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000745 PyObject *tup = NULL;
746 struct tm buf;
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000747
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000748 if (!PyArg_UnpackTuple(args, "asctime", 0, 1, &tup))
749 return NULL;
750 if (tup == NULL) {
751 time_t tt = time(NULL);
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100752 if (pylocaltime(&tt, &buf) == -1)
753 return NULL;
754
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000755 } else if (!gettmarg(tup, &buf) || !checktm(&buf))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000756 return NULL;
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000757 return _asctime(&buf);
Guido van Rossum9e90a671993-06-24 11:10:19 +0000758}
759
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000760PyDoc_STRVAR(asctime_doc,
Thomas Woutersfe385252001-01-19 23:16:56 +0000761"asctime([tuple]) -> string\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000762\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000763Convert a time tuple to a string, e.g. 'Sat Jun 06 16:26:11 1998'.\n\
764When the time tuple is not present, current time as returned by localtime()\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000765is used.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000766
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000767static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000768time_ctime(PyObject *self, PyObject *args)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000769{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000770 time_t tt;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100771 struct tm buf;
772 if (!parse_time_t_args(args, "|O:ctime", &tt))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000773 return NULL;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100774 if (pylocaltime(&tt, &buf) == -1)
Alexander Belopolsky5da468f2011-01-04 17:15:52 +0000775 return NULL;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100776 return _asctime(&buf);
Guido van Rossum9e90a671993-06-24 11:10:19 +0000777}
778
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000779PyDoc_STRVAR(ctime_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000780"ctime(seconds) -> string\n\
781\n\
782Convert a time in seconds since the Epoch to a string in local time.\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000783This is equivalent to asctime(localtime(seconds)). When the time tuple is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000784not present, current time as returned by localtime() is used.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000785
Guido van Rossum60cd8131998-03-06 17:16:21 +0000786#ifdef HAVE_MKTIME
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000787static PyObject *
Victor Stinner4195b5c2012-02-08 23:03:19 +0100788time_mktime(PyObject *self, PyObject *tup)
Guido van Rossum234f9421993-06-17 12:35:49 +0000789{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000790 struct tm buf;
791 time_t tt;
792 if (!gettmarg(tup, &buf))
793 return NULL;
Alexander Belopolskyb7d40d12011-01-11 01:21:25 +0000794 buf.tm_wday = -1; /* sentinel; original value ignored */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000795 tt = mktime(&buf);
Alexander Belopolskyb7d40d12011-01-11 01:21:25 +0000796 /* Return value of -1 does not necessarily mean an error, but tm_wday
Ezio Melotti13925002011-03-16 11:05:33 +0200797 * cannot remain set to -1 if mktime succeeded. */
Alexander Belopolskyb7d40d12011-01-11 01:21:25 +0000798 if (tt == (time_t)(-1) && buf.tm_wday == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000799 PyErr_SetString(PyExc_OverflowError,
800 "mktime argument out of range");
801 return NULL;
802 }
Victor Stinner4195b5c2012-02-08 23:03:19 +0100803 return PyFloat_FromDouble((double)tt);
Guido van Rossum234f9421993-06-17 12:35:49 +0000804}
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000805
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000806PyDoc_STRVAR(mktime_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000807"mktime(tuple) -> floating point number\n\
808\n\
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400809Convert a time tuple in local time to seconds since the Epoch.\n\
810Note that mktime(gmtime(0)) will not generally return zero for most\n\
811time zones; instead the returned value will either be equal to that\n\
812of the timezone or altzone attributes on the time module.");
Guido van Rossum60cd8131998-03-06 17:16:21 +0000813#endif /* HAVE_MKTIME */
Guido van Rossum234f9421993-06-17 12:35:49 +0000814
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000815#ifdef HAVE_WORKING_TZSET
Martin v. Löwis1a214512008-06-11 05:26:20 +0000816static void PyInit_timezone(PyObject *module);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000817
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000818static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000819time_tzset(PyObject *self, PyObject *unused)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000820{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000821 PyObject* m;
Fred Drake9bb74322002-04-01 14:49:59 +0000822
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000823 m = PyImport_ImportModuleNoBlock("time");
824 if (m == NULL) {
825 return NULL;
826 }
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000827
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000828 tzset();
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000829
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000830 /* Reset timezone, altzone, daylight and tzname */
831 PyInit_timezone(m);
832 Py_DECREF(m);
Tim Peters1b6f7a92004-06-20 02:50:16 +0000833
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000834 Py_INCREF(Py_None);
835 return Py_None;
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000836}
837
838PyDoc_STRVAR(tzset_doc,
R. David Murray4d55bf92010-12-14 00:55:46 +0000839"tzset()\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000840\n\
841Initialize, or reinitialize, the local timezone to the value stored in\n\
842os.environ['TZ']. The TZ environment variable should be specified in\n\
Neal Norwitzdc8e1942004-07-20 22:34:37 +0000843standard Unix timezone format as documented in the tzset man page\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000844(eg. 'US/Eastern', 'Europe/Amsterdam'). Unknown timezones will silently\n\
845fall back to UTC. If the TZ environment variable is not set, the local\n\
846timezone is set to the systems best guess of wallclock time.\n\
847Changing the TZ environment variable without calling tzset *may* change\n\
848the local timezone used by methods such as localtime, but this behaviour\n\
849should not be relied on.");
850#endif /* HAVE_WORKING_TZSET */
851
Victor Stinnerec895392012-04-29 02:41:27 +0200852#if defined(MS_WINDOWS) || defined(__APPLE__) \
853 || (defined(HAVE_CLOCK_GETTIME) \
854 && (defined(CLOCK_HIGHRES) || defined(CLOCK_MONOTONIC)))
855#define PYMONOTONIC
856#endif
857
858#ifdef PYMONOTONIC
Victor Stinner071eca32012-03-15 01:17:09 +0100859static PyObject*
Victor Stinnerec895392012-04-29 02:41:27 +0200860pymonotonic(_Py_clock_info_t *info)
Victor Stinnerb94b2662012-01-18 01:50:21 +0100861{
Victor Stinnerec895392012-04-29 02:41:27 +0200862#if defined(MS_WINDOWS)
863 static ULONGLONG (*GetTickCount64) (void) = NULL;
864 static ULONGLONG (CALLBACK *Py_GetTickCount64)(void);
865 static int has_getickcount64 = -1;
866 double result;
867
868 if (has_getickcount64 == -1) {
869 /* GetTickCount64() was added to Windows Vista */
870 if (winver.dwMajorVersion >= 6) {
871 HINSTANCE hKernel32;
872 hKernel32 = GetModuleHandleW(L"KERNEL32");
873 *(FARPROC*)&Py_GetTickCount64 = GetProcAddress(hKernel32,
874 "GetTickCount64");
875 has_getickcount64 = (Py_GetTickCount64 != NULL);
876 }
877 else
878 has_getickcount64 = 0;
879 }
880
881 if (has_getickcount64) {
882 ULONGLONG ticks;
883 ticks = Py_GetTickCount64();
884 result = (double)ticks * 1e-3;
885 }
886 else {
887 static DWORD last_ticks = 0;
888 static DWORD n_overflow = 0;
889 DWORD ticks;
890
891 ticks = GetTickCount();
892 if (ticks < last_ticks)
893 n_overflow++;
894 last_ticks = ticks;
895
896 result = ldexp(n_overflow, 32);
897 result += ticks;
898 result *= 1e-3;
899 }
900
901 if (info) {
902 DWORD timeAdjustment, timeIncrement;
903 BOOL isTimeAdjustmentDisabled, ok;
904 if (has_getickcount64)
905 info->implementation = "GetTickCount64()";
906 else
907 info->implementation = "GetTickCount()";
Benjamin Peterson49a69e42012-05-01 09:38:34 -0400908 info->monotonic = 1;
Victor Stinnerec895392012-04-29 02:41:27 +0200909 ok = GetSystemTimeAdjustment(&timeAdjustment, &timeIncrement,
910 &isTimeAdjustmentDisabled);
911 if (!ok) {
912 PyErr_SetFromWindowsErr(0);
913 return NULL;
914 }
915 info->resolution = timeIncrement * 1e-7;
Victor Stinner2b89fdf2012-06-12 22:46:37 +0200916 info->adjustable = 0;
Victor Stinnerec895392012-04-29 02:41:27 +0200917 }
918 return PyFloat_FromDouble(result);
919
Victor Stinnera8ec5ea2012-03-13 00:25:42 +0100920#elif defined(__APPLE__)
Victor Stinner74eb6c02012-03-28 02:50:46 +0200921 static mach_timebase_info_data_t timebase;
922 uint64_t time;
Victor Stinnera8ec5ea2012-03-13 00:25:42 +0100923 double secs;
924
Victor Stinner74eb6c02012-03-28 02:50:46 +0200925 if (timebase.denom == 0) {
926 /* According to the Technical Q&A QA1398, mach_timebase_info() cannot
927 fail: https://developer.apple.com/library/mac/#qa/qa1398/ */
928 (void)mach_timebase_info(&timebase);
929 }
Victor Stinnera8ec5ea2012-03-13 00:25:42 +0100930
Victor Stinner74eb6c02012-03-28 02:50:46 +0200931 time = mach_absolute_time();
Victor Stinnera8ec5ea2012-03-13 00:25:42 +0100932 secs = (double)time * timebase.numer / timebase.denom * 1e-9;
Victor Stinnerec895392012-04-29 02:41:27 +0200933 if (info) {
934 info->implementation = "mach_absolute_time()";
935 info->resolution = (double)timebase.numer / timebase.denom * 1e-9;
Benjamin Peterson49a69e42012-05-01 09:38:34 -0400936 info->monotonic = 1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +0200937 info->adjustable = 0;
Victor Stinnerec895392012-04-29 02:41:27 +0200938 }
Victor Stinnera8ec5ea2012-03-13 00:25:42 +0100939 return PyFloat_FromDouble(secs);
Victor Stinnerec895392012-04-29 02:41:27 +0200940
941#elif defined(HAVE_CLOCK_GETTIME) && (defined(CLOCK_HIGHRES) || defined(CLOCK_MONOTONIC))
Victor Stinner8b302012012-02-07 23:29:46 +0100942 struct timespec tp;
Victor Stinnerec895392012-04-29 02:41:27 +0200943#ifdef CLOCK_HIGHRES
944 const clockid_t clk_id = CLOCK_HIGHRES;
945 const char *function = "clock_gettime(CLOCK_HIGHRES)";
946#else
947 const clockid_t clk_id = CLOCK_MONOTONIC;
948 const char *function = "clock_gettime(CLOCK_MONOTONIC)";
949#endif
Victor Stinner8b302012012-02-07 23:29:46 +0100950
Victor Stinnerec895392012-04-29 02:41:27 +0200951 if (clock_gettime(clk_id, &tp) != 0) {
Victor Stinner071eca32012-03-15 01:17:09 +0100952 PyErr_SetFromErrno(PyExc_OSError);
953 return NULL;
954 }
Victor Stinnerec895392012-04-29 02:41:27 +0200955
956 if (info) {
957 struct timespec res;
Benjamin Peterson49a69e42012-05-01 09:38:34 -0400958 info->monotonic = 1;
Victor Stinnerec895392012-04-29 02:41:27 +0200959 info->implementation = function;
Victor Stinner2b89fdf2012-06-12 22:46:37 +0200960 info->adjustable = 0;
Victor Stinnerec895392012-04-29 02:41:27 +0200961 if (clock_getres(clk_id, &res) == 0)
962 info->resolution = res.tv_sec + res.tv_nsec * 1e-9;
963 else
964 info->resolution = 1e-9;
Victor Stinner071eca32012-03-15 01:17:09 +0100965 }
Victor Stinnerec895392012-04-29 02:41:27 +0200966 return PyFloat_FromDouble(tp.tv_sec + tp.tv_nsec * 1e-9);
Victor Stinner8b302012012-02-07 23:29:46 +0100967#endif
968}
969
Victor Stinner071eca32012-03-15 01:17:09 +0100970static PyObject *
Victor Stinnerec895392012-04-29 02:41:27 +0200971time_monotonic(PyObject *self, PyObject *unused)
Victor Stinner071eca32012-03-15 01:17:09 +0100972{
Victor Stinnerec895392012-04-29 02:41:27 +0200973 return pymonotonic(NULL);
Victor Stinner071eca32012-03-15 01:17:09 +0100974}
975
Victor Stinnerec895392012-04-29 02:41:27 +0200976PyDoc_STRVAR(monotonic_doc,
977"monotonic() -> float\n\
Victor Stinner8b302012012-02-07 23:29:46 +0100978\n\
Victor Stinnerec895392012-04-29 02:41:27 +0200979Monotonic clock, cannot go backward.");
980#endif /* PYMONOTONIC */
Victor Stinnerec919cc2012-03-15 00:58:32 +0100981
Victor Stinnerec895392012-04-29 02:41:27 +0200982static PyObject*
983perf_counter(_Py_clock_info_t *info)
984{
985#if defined(WIN32_PERF_COUNTER) || defined(PYMONOTONIC)
986 PyObject *res;
987#endif
988#if defined(WIN32_PERF_COUNTER)
989 static int use_perf_counter = 1;
990#endif
991#ifdef PYMONOTONIC
992 static int use_monotonic = 1;
993#endif
994
995#ifdef WIN32_PERF_COUNTER
996 if (use_perf_counter) {
997 if (win_perf_counter(info, &res) == 0)
998 return res;
999 use_perf_counter = 0;
1000 }
1001#endif
1002
1003#ifdef PYMONOTONIC
1004 if (use_monotonic) {
1005 res = pymonotonic(info);
1006 if (res != NULL)
1007 return res;
1008 use_monotonic = 0;
1009 PyErr_Clear();
1010 }
1011#endif
1012
1013 return floattime(info);
1014}
1015
1016static PyObject *
1017time_perf_counter(PyObject *self, PyObject *unused)
1018{
1019 return perf_counter(NULL);
1020}
1021
1022PyDoc_STRVAR(perf_counter_doc,
1023"perf_counter() -> float\n\
1024\n\
1025Performance counter for benchmarking.");
1026
1027static PyObject*
1028py_process_time(_Py_clock_info_t *info)
1029{
1030#if defined(MS_WINDOWS)
1031 HANDLE process;
1032 FILETIME creation_time, exit_time, kernel_time, user_time;
1033 ULARGE_INTEGER large;
1034 double total;
1035 BOOL ok;
1036
1037 process = GetCurrentProcess();
1038 ok = GetProcessTimes(process, &creation_time, &exit_time, &kernel_time, &user_time);
1039 if (!ok)
1040 return PyErr_SetFromWindowsErr(0);
1041
1042 large.u.LowPart = kernel_time.dwLowDateTime;
1043 large.u.HighPart = kernel_time.dwHighDateTime;
1044 total = (double)large.QuadPart;
1045 large.u.LowPart = user_time.dwLowDateTime;
1046 large.u.HighPart = user_time.dwHighDateTime;
1047 total += (double)large.QuadPart;
1048 if (info) {
1049 info->implementation = "GetProcessTimes()";
1050 info->resolution = 1e-7;
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001051 info->monotonic = 1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001052 info->adjustable = 0;
Victor Stinnerec895392012-04-29 02:41:27 +02001053 }
1054 return PyFloat_FromDouble(total * 1e-7);
1055#else
1056
1057#if defined(HAVE_SYS_RESOURCE_H)
1058 struct rusage ru;
1059#endif
1060#ifdef HAVE_TIMES
1061 struct tms t;
1062 static long ticks_per_second = -1;
1063#endif
1064
1065#if defined(HAVE_CLOCK_GETTIME) \
1066 && (defined(CLOCK_PROCESS_CPUTIME_ID) || defined(CLOCK_PROF))
1067 struct timespec tp;
1068#ifdef CLOCK_PROF
1069 const clockid_t clk_id = CLOCK_PROF;
1070 const char *function = "clock_gettime(CLOCK_PROF)";
1071#else
1072 const clockid_t clk_id = CLOCK_PROCESS_CPUTIME_ID;
1073 const char *function = "clock_gettime(CLOCK_PROCESS_CPUTIME_ID)";
1074#endif
1075
1076 if (clock_gettime(clk_id, &tp) == 0) {
1077 if (info) {
1078 struct timespec res;
1079 info->implementation = function;
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001080 info->monotonic = 1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001081 info->adjustable = 0;
Victor Stinnerec895392012-04-29 02:41:27 +02001082 if (clock_getres(clk_id, &res) == 0)
1083 info->resolution = res.tv_sec + res.tv_nsec * 1e-9;
1084 else
1085 info->resolution = 1e-9;
1086 }
1087 return PyFloat_FromDouble(tp.tv_sec + tp.tv_nsec * 1e-9);
1088 }
1089#endif
1090
1091#if defined(HAVE_SYS_RESOURCE_H)
1092 if (getrusage(RUSAGE_SELF, &ru) == 0) {
1093 double total;
1094 total = ru.ru_utime.tv_sec + ru.ru_utime.tv_usec * 1e-6;
1095 total += ru.ru_stime.tv_sec + ru.ru_stime.tv_usec * 1e-6;
1096 if (info) {
1097 info->implementation = "getrusage(RUSAGE_SELF)";
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001098 info->monotonic = 1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001099 info->adjustable = 0;
Victor Stinnerec895392012-04-29 02:41:27 +02001100 info->resolution = 1e-6;
1101 }
1102 return PyFloat_FromDouble(total);
1103 }
1104#endif
1105
1106#ifdef HAVE_TIMES
1107 if (times(&t) != (clock_t)-1) {
1108 double total;
1109
1110 if (ticks_per_second == -1) {
1111#if defined(HAVE_SYSCONF) && defined(_SC_CLK_TCK)
1112 ticks_per_second = sysconf(_SC_CLK_TCK);
1113 if (ticks_per_second < 1)
1114 ticks_per_second = -1;
1115#elif defined(HZ)
1116 ticks_per_second = HZ;
1117#else
1118 ticks_per_second = 60; /* magic fallback value; may be bogus */
1119#endif
1120 }
1121
1122 if (ticks_per_second != -1) {
1123 total = (double)t.tms_utime / ticks_per_second;
1124 total += (double)t.tms_stime / ticks_per_second;
1125 if (info) {
1126 info->implementation = "times()";
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001127 info->monotonic = 1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001128 info->adjustable = 0;
Victor Stinnerec895392012-04-29 02:41:27 +02001129 info->resolution = 1.0 / ticks_per_second;
1130 }
1131 return PyFloat_FromDouble(total);
1132 }
1133 }
1134#endif
1135
1136 return floatclock(info);
1137#endif
1138}
1139
1140static PyObject *
1141time_process_time(PyObject *self, PyObject *unused)
1142{
1143 return py_process_time(NULL);
1144}
1145
1146PyDoc_STRVAR(process_time_doc,
1147"process_time() -> float\n\
1148\n\
1149Process time for profiling: sum of the kernel and user-space CPU time.");
1150
1151
Victor Stinnerec895392012-04-29 02:41:27 +02001152static PyObject *
1153time_get_clock_info(PyObject *self, PyObject *args)
1154{
1155 char *name;
Victor Stinnerec895392012-04-29 02:41:27 +02001156 _Py_clock_info_t info;
Victor Stinnerbda4b882012-06-12 22:11:44 +02001157 PyObject *obj = NULL, *dict, *ns;
Victor Stinnerec895392012-04-29 02:41:27 +02001158
1159 if (!PyArg_ParseTuple(args, "s:get_clock_info", &name))
1160 return NULL;
1161
1162#ifdef Py_DEBUG
1163 info.implementation = NULL;
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001164 info.monotonic = -1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001165 info.adjustable = -1;
Victor Stinnerec895392012-04-29 02:41:27 +02001166 info.resolution = -1.0;
1167#else
1168 info.implementation = "";
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001169 info.monotonic = 0;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001170 info.adjustable = 0;
Victor Stinnerec895392012-04-29 02:41:27 +02001171 info.resolution = 1.0;
1172#endif
1173
1174 if (strcmp(name, "time") == 0)
1175 obj = floattime(&info);
1176#ifdef PYCLOCK
1177 else if (strcmp(name, "clock") == 0)
1178 obj = pyclock(&info);
1179#endif
1180#ifdef PYMONOTONIC
1181 else if (strcmp(name, "monotonic") == 0)
1182 obj = pymonotonic(&info);
1183#endif
1184 else if (strcmp(name, "perf_counter") == 0)
1185 obj = perf_counter(&info);
1186 else if (strcmp(name, "process_time") == 0)
1187 obj = py_process_time(&info);
1188 else {
1189 PyErr_SetString(PyExc_ValueError, "unknown clock");
1190 return NULL;
1191 }
1192 if (obj == NULL)
1193 return NULL;
1194 Py_DECREF(obj);
1195
Victor Stinnerbda4b882012-06-12 22:11:44 +02001196 dict = PyDict_New();
1197 if (dict == NULL)
Victor Stinnerec895392012-04-29 02:41:27 +02001198 return NULL;
1199
1200 assert(info.implementation != NULL);
1201 obj = PyUnicode_FromString(info.implementation);
1202 if (obj == NULL)
1203 goto error;
Victor Stinnerbda4b882012-06-12 22:11:44 +02001204 if (PyDict_SetItemString(dict, "implementation", obj) == -1)
1205 goto error;
1206 Py_CLEAR(obj);
Victor Stinnerec895392012-04-29 02:41:27 +02001207
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001208 assert(info.monotonic != -1);
1209 obj = PyBool_FromLong(info.monotonic);
Victor Stinnerec895392012-04-29 02:41:27 +02001210 if (obj == NULL)
1211 goto error;
Victor Stinnerbda4b882012-06-12 22:11:44 +02001212 if (PyDict_SetItemString(dict, "monotonic", obj) == -1)
1213 goto error;
1214 Py_CLEAR(obj);
Victor Stinnerec895392012-04-29 02:41:27 +02001215
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001216 assert(info.adjustable != -1);
1217 obj = PyBool_FromLong(info.adjustable);
Victor Stinnerec895392012-04-29 02:41:27 +02001218 if (obj == NULL)
1219 goto error;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001220 if (PyDict_SetItemString(dict, "adjustable", obj) == -1)
Victor Stinnerbda4b882012-06-12 22:11:44 +02001221 goto error;
1222 Py_CLEAR(obj);
Victor Stinnerec895392012-04-29 02:41:27 +02001223
1224 assert(info.resolution > 0.0);
1225 assert(info.resolution <= 1.0);
1226 obj = PyFloat_FromDouble(info.resolution);
1227 if (obj == NULL)
1228 goto error;
Victor Stinnerbda4b882012-06-12 22:11:44 +02001229 if (PyDict_SetItemString(dict, "resolution", obj) == -1)
1230 goto error;
1231 Py_CLEAR(obj);
Victor Stinnerec895392012-04-29 02:41:27 +02001232
Victor Stinnerbda4b882012-06-12 22:11:44 +02001233 ns = _PyNamespace_New(dict);
1234 Py_DECREF(dict);
1235 return ns;
Victor Stinnerec895392012-04-29 02:41:27 +02001236
1237error:
Victor Stinnerbda4b882012-06-12 22:11:44 +02001238 Py_DECREF(dict);
1239 Py_XDECREF(obj);
Victor Stinnerec895392012-04-29 02:41:27 +02001240 return NULL;
1241}
1242
1243PyDoc_STRVAR(get_clock_info_doc,
1244"get_clock_info(name: str) -> dict\n\
1245\n\
1246Get information of the specified clock.");
Victor Stinner8b302012012-02-07 23:29:46 +01001247
Martin v. Löwisd218dc12008-04-07 03:17:54 +00001248static void
Martin v. Löwis1a214512008-06-11 05:26:20 +00001249PyInit_timezone(PyObject *m) {
1250 /* This code moved from PyInit_time wholesale to allow calling it from
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001251 time_tzset. In the future, some parts of it can be moved back
1252 (for platforms that don't HAVE_WORKING_TZSET, when we know what they
1253 are), and the extraneous calls to tzset(3) should be removed.
1254 I haven't done this yet, as I don't want to change this code as
1255 little as possible when introducing the time.tzset and time.tzsetwall
1256 methods. This should simply be a method of doing the following once,
1257 at the top of this function and removing the call to tzset() from
1258 time_tzset():
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001259
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001260 #ifdef HAVE_TZSET
1261 tzset()
1262 #endif
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001263
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001264 And I'm lazy and hate C so nyer.
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001265 */
Guido van Rossum10b164a2001-09-25 13:59:01 +00001266#if defined(HAVE_TZNAME) && !defined(__GLIBC__) && !defined(__CYGWIN__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001267 PyObject *otz0, *otz1;
1268 tzset();
Guido van Rossum26452411998-09-28 22:07:11 +00001269#ifdef PYOS_OS2
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001270 PyModule_AddIntConstant(m, "timezone", _timezone);
Guido van Rossum26452411998-09-28 22:07:11 +00001271#else /* !PYOS_OS2 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001272 PyModule_AddIntConstant(m, "timezone", timezone);
Guido van Rossum26452411998-09-28 22:07:11 +00001273#endif /* PYOS_OS2 */
Guido van Rossumb6775db1994-08-01 11:34:53 +00001274#ifdef HAVE_ALTZONE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001275 PyModule_AddIntConstant(m, "altzone", altzone);
Guido van Rossumb6775db1994-08-01 11:34:53 +00001276#else
Guido van Rossum26452411998-09-28 22:07:11 +00001277#ifdef PYOS_OS2
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001278 PyModule_AddIntConstant(m, "altzone", _timezone-3600);
Guido van Rossum26452411998-09-28 22:07:11 +00001279#else /* !PYOS_OS2 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001280 PyModule_AddIntConstant(m, "altzone", timezone-3600);
Guido van Rossum26452411998-09-28 22:07:11 +00001281#endif /* PYOS_OS2 */
Guido van Rossumb6775db1994-08-01 11:34:53 +00001282#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001283 PyModule_AddIntConstant(m, "daylight", daylight);
Victor Stinner1b579672011-12-17 05:47:23 +01001284 otz0 = PyUnicode_DecodeLocale(tzname[0], "surrogateescape");
1285 otz1 = PyUnicode_DecodeLocale(tzname[1], "surrogateescape");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001286 PyModule_AddObject(m, "tzname", Py_BuildValue("(NN)", otz0, otz1));
Guido van Rossum10b164a2001-09-25 13:59:01 +00001287#else /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/
Martin v. Löwis60a5d722002-10-16 20:28:25 +00001288#ifdef HAVE_STRUCT_TM_TM_ZONE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001289 {
Guido van Rossum234f9421993-06-17 12:35:49 +00001290#define YEAR ((time_t)((365 * 24 + 6) * 3600))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001291 time_t t;
1292 struct tm *p;
1293 long janzone, julyzone;
1294 char janname[10], julyname[10];
1295 t = (time((time_t *)0) / YEAR) * YEAR;
1296 p = localtime(&t);
1297 janzone = -p->tm_gmtoff;
1298 strncpy(janname, p->tm_zone ? p->tm_zone : " ", 9);
1299 janname[9] = '\0';
1300 t += YEAR/2;
1301 p = localtime(&t);
1302 julyzone = -p->tm_gmtoff;
1303 strncpy(julyname, p->tm_zone ? p->tm_zone : " ", 9);
1304 julyname[9] = '\0';
Guido van Rossum10b164a2001-09-25 13:59:01 +00001305
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001306 if( janzone < julyzone ) {
1307 /* DST is reversed in the southern hemisphere */
1308 PyModule_AddIntConstant(m, "timezone", julyzone);
1309 PyModule_AddIntConstant(m, "altzone", janzone);
1310 PyModule_AddIntConstant(m, "daylight",
1311 janzone != julyzone);
1312 PyModule_AddObject(m, "tzname",
1313 Py_BuildValue("(zz)",
1314 julyname, janname));
1315 } else {
1316 PyModule_AddIntConstant(m, "timezone", janzone);
1317 PyModule_AddIntConstant(m, "altzone", julyzone);
1318 PyModule_AddIntConstant(m, "daylight",
1319 janzone != julyzone);
1320 PyModule_AddObject(m, "tzname",
1321 Py_BuildValue("(zz)",
1322 janname, julyname));
1323 }
1324 }
Guido van Rossume6a4b7b1997-10-08 15:27:56 +00001325#else
Martin v. Löwis60a5d722002-10-16 20:28:25 +00001326#endif /* HAVE_STRUCT_TM_TM_ZONE */
Tim Peters26ae7cd2001-03-20 03:26:49 +00001327#ifdef __CYGWIN__
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001328 tzset();
1329 PyModule_AddIntConstant(m, "timezone", _timezone);
1330 PyModule_AddIntConstant(m, "altzone", _timezone-3600);
1331 PyModule_AddIntConstant(m, "daylight", _daylight);
1332 PyModule_AddObject(m, "tzname",
1333 Py_BuildValue("(zz)", _tzname[0], _tzname[1]));
Tim Peters26ae7cd2001-03-20 03:26:49 +00001334#endif /* __CYGWIN__ */
Guido van Rossum10b164a2001-09-25 13:59:01 +00001335#endif /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/
Victor Stinnere0be4232011-10-25 13:06:09 +02001336
Victor Stinnerec895392012-04-29 02:41:27 +02001337#if defined(HAVE_CLOCK_GETTIME)
Victor Stinnere0be4232011-10-25 13:06:09 +02001338 PyModule_AddIntMacro(m, CLOCK_REALTIME);
Victor Stinnere0be4232011-10-25 13:06:09 +02001339#ifdef CLOCK_MONOTONIC
1340 PyModule_AddIntMacro(m, CLOCK_MONOTONIC);
1341#endif
1342#ifdef CLOCK_MONOTONIC_RAW
1343 PyModule_AddIntMacro(m, CLOCK_MONOTONIC_RAW);
1344#endif
Victor Stinner1470f352012-04-03 00:31:17 +02001345#ifdef CLOCK_HIGHRES
1346 PyModule_AddIntMacro(m, CLOCK_HIGHRES);
1347#endif
Victor Stinnere0be4232011-10-25 13:06:09 +02001348#ifdef CLOCK_PROCESS_CPUTIME_ID
1349 PyModule_AddIntMacro(m, CLOCK_PROCESS_CPUTIME_ID);
1350#endif
1351#ifdef CLOCK_THREAD_CPUTIME_ID
1352 PyModule_AddIntMacro(m, CLOCK_THREAD_CPUTIME_ID);
1353#endif
1354#endif /* HAVE_CLOCK_GETTIME */
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001355}
1356
1357
1358static PyMethodDef time_methods[] = {
Victor Stinner4195b5c2012-02-08 23:03:19 +01001359 {"time", time_time, METH_NOARGS, time_doc},
Victor Stinnerec895392012-04-29 02:41:27 +02001360#ifdef PYCLOCK
Victor Stinner4195b5c2012-02-08 23:03:19 +01001361 {"clock", time_clock, METH_NOARGS, clock_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001362#endif
Victor Stinnere0be4232011-10-25 13:06:09 +02001363#ifdef HAVE_CLOCK_GETTIME
Victor Stinner4195b5c2012-02-08 23:03:19 +01001364 {"clock_gettime", time_clock_gettime, METH_VARARGS, clock_gettime_doc},
Victor Stinner30d79472012-04-03 00:45:07 +02001365 {"clock_settime", time_clock_settime, METH_VARARGS, clock_settime_doc},
Victor Stinner4195b5c2012-02-08 23:03:19 +01001366 {"clock_getres", time_clock_getres, METH_VARARGS, clock_getres_doc},
Victor Stinnere0be4232011-10-25 13:06:09 +02001367#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001368 {"sleep", time_sleep, METH_VARARGS, sleep_doc},
1369 {"gmtime", time_gmtime, METH_VARARGS, gmtime_doc},
1370 {"localtime", time_localtime, METH_VARARGS, localtime_doc},
1371 {"asctime", time_asctime, METH_VARARGS, asctime_doc},
1372 {"ctime", time_ctime, METH_VARARGS, ctime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001373#ifdef HAVE_MKTIME
Victor Stinner4195b5c2012-02-08 23:03:19 +01001374 {"mktime", time_mktime, METH_O, mktime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001375#endif
1376#ifdef HAVE_STRFTIME
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001377 {"strftime", time_strftime, METH_VARARGS, strftime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001378#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001379 {"strptime", time_strptime, METH_VARARGS, strptime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001380#ifdef HAVE_WORKING_TZSET
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001381 {"tzset", time_tzset, METH_NOARGS, tzset_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001382#endif
Victor Stinnerec895392012-04-29 02:41:27 +02001383#ifdef PYMONOTONIC
1384 {"monotonic", time_monotonic, METH_NOARGS, monotonic_doc},
1385#endif
1386 {"process_time", time_process_time, METH_NOARGS, process_time_doc},
1387 {"perf_counter", time_perf_counter, METH_NOARGS, perf_counter_doc},
1388 {"get_clock_info", time_get_clock_info, METH_VARARGS, get_clock_info_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001389 {NULL, NULL} /* sentinel */
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001390};
1391
1392
1393PyDoc_STRVAR(module_doc,
1394"This module provides various functions to manipulate time values.\n\
1395\n\
1396There are two standard representations of time. One is the number\n\
1397of seconds since the Epoch, in UTC (a.k.a. GMT). It may be an integer\n\
1398or a floating point number (to represent fractions of seconds).\n\
1399The Epoch is system-defined; on Unix, it is generally January 1st, 1970.\n\
1400The actual value can be retrieved by calling gmtime(0).\n\
1401\n\
1402The other representation is a tuple of 9 integers giving local time.\n\
1403The tuple items are:\n\
Alexander Belopolsky03163ac2011-05-02 12:20:52 -04001404 year (including century, e.g. 1998)\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001405 month (1-12)\n\
1406 day (1-31)\n\
1407 hours (0-23)\n\
1408 minutes (0-59)\n\
1409 seconds (0-59)\n\
1410 weekday (0-6, Monday is 0)\n\
1411 Julian day (day in the year, 1-366)\n\
1412 DST (Daylight Savings Time) flag (-1, 0 or 1)\n\
1413If the DST flag is 0, the time is given in the regular time zone;\n\
1414if it is 1, the time is given in the DST time zone;\n\
1415if it is -1, mktime() should guess based on the date and time.\n\
1416\n\
1417Variables:\n\
1418\n\
1419timezone -- difference in seconds between UTC and local standard time\n\
1420altzone -- difference in seconds between UTC and local DST time\n\
1421daylight -- whether local time should reflect DST\n\
1422tzname -- tuple of (standard time zone name, DST time zone name)\n\
1423\n\
1424Functions:\n\
1425\n\
1426time() -- return current time in seconds since the Epoch as a float\n\
1427clock() -- return CPU time since process start as a float\n\
1428sleep() -- delay for a number of seconds given as a float\n\
1429gmtime() -- convert seconds since Epoch to UTC tuple\n\
1430localtime() -- convert seconds since Epoch to local time tuple\n\
1431asctime() -- convert time tuple to string\n\
1432ctime() -- convert time in seconds to string\n\
1433mktime() -- convert local time tuple to seconds since Epoch\n\
1434strftime() -- convert time tuple to string according to format specification\n\
1435strptime() -- parse string to time tuple according to format specification\n\
1436tzset() -- change the local timezone");
1437
1438
Martin v. Löwis1a214512008-06-11 05:26:20 +00001439
1440static struct PyModuleDef timemodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001441 PyModuleDef_HEAD_INIT,
1442 "time",
1443 module_doc,
1444 -1,
1445 time_methods,
1446 NULL,
1447 NULL,
1448 NULL,
1449 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00001450};
1451
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001452PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00001453PyInit_time(void)
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001454{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001455 PyObject *m;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001456 m = PyModule_Create(&timemodule);
1457 if (m == NULL)
1458 return NULL;
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001459
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001460 /* Set, or reset, module variables like time.timezone */
1461 PyInit_timezone(m);
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001462
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001463 if (!initialized) {
1464 PyStructSequence_InitType(&StructTimeType,
1465 &struct_time_type_desc);
Victor Stinnerec895392012-04-29 02:41:27 +02001466
Victor Stinnerec895392012-04-29 02:41:27 +02001467#ifdef MS_WINDOWS
1468 winver.dwOSVersionInfoSize = sizeof(winver);
1469 if (!GetVersionEx((OSVERSIONINFO*)&winver)) {
1470 Py_DECREF(m);
1471 PyErr_SetFromWindowsErr(0);
1472 return NULL;
1473 }
1474#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001475 }
1476 Py_INCREF(&StructTimeType);
Alexander Belopolskyc142bba2012-06-13 22:15:26 -04001477#ifdef HAVE_STRUCT_TM_TM_ZONE
1478 PyModule_AddIntConstant(m, "_STRUCT_TM_ITEMS", 11);
1479#else
1480 PyModule_AddIntConstant(m, "_STRUCT_TM_ITEMS", 9);
1481#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001482 PyModule_AddObject(m, "struct_time", (PyObject*) &StructTimeType);
1483 initialized = 1;
1484 return m;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001485}
1486
Victor Stinner071eca32012-03-15 01:17:09 +01001487static PyObject*
Victor Stinnerec895392012-04-29 02:41:27 +02001488floattime(_Py_clock_info_t *info)
Victor Stinner4195b5c2012-02-08 23:03:19 +01001489{
1490 _PyTime_timeval t;
Victor Stinnerad95c2d2012-03-28 02:54:15 +02001491#ifdef HAVE_CLOCK_GETTIME
1492 struct timespec tp;
1493 int ret;
1494
1495 /* _PyTime_gettimeofday() does not use clock_gettime()
1496 because it would require to link Python to the rt (real-time)
1497 library, at least on Linux */
1498 ret = clock_gettime(CLOCK_REALTIME, &tp);
Victor Stinnerec895392012-04-29 02:41:27 +02001499 if (ret == 0) {
1500 if (info) {
1501 struct timespec res;
1502 info->implementation = "clock_gettime(CLOCK_REALTIME)";
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001503 info->monotonic = 0;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001504 info->adjustable = 1;
Victor Stinnerec895392012-04-29 02:41:27 +02001505 if (clock_getres(CLOCK_REALTIME, &res) == 0)
1506 info->resolution = res.tv_sec + res.tv_nsec * 1e-9;
1507 else
1508 info->resolution = 1e-9;
1509 }
Victor Stinnerad95c2d2012-03-28 02:54:15 +02001510 return PyFloat_FromDouble(tp.tv_sec + tp.tv_nsec * 1e-9);
Victor Stinnerec895392012-04-29 02:41:27 +02001511 }
Victor Stinnerad95c2d2012-03-28 02:54:15 +02001512#endif
Victor Stinnerec895392012-04-29 02:41:27 +02001513 _PyTime_gettimeofday_info(&t, info);
Victor Stinner70b2e1e2012-03-26 22:08:02 +02001514 return PyFloat_FromDouble((double)t.tv_sec + t.tv_usec * 1e-6);
Victor Stinner4195b5c2012-02-08 23:03:19 +01001515}
1516
1517
Guido van Rossumb6775db1994-08-01 11:34:53 +00001518/* Implement floatsleep() for various platforms.
1519 When interrupted (or when another error occurs), return -1 and
1520 set an exception; else return 0. */
1521
1522static int
Guido van Rossuma320fd31995-03-09 12:14:15 +00001523floatsleep(double secs)
Guido van Rossum426035c1991-02-19 12:27:35 +00001524{
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001525/* XXX Should test for MS_WINDOWS first! */
Skip Montanaroeb33e5a2007-08-17 12:57:41 +00001526#if defined(HAVE_SELECT) && !defined(__EMX__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001527 struct timeval t;
1528 double frac;
Victor Stinner48b1ce52011-07-01 13:50:09 +02001529 int err;
1530
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001531 frac = fmod(secs, 1.0);
1532 secs = floor(secs);
1533 t.tv_sec = (long)secs;
1534 t.tv_usec = (long)(frac*1000000.0);
1535 Py_BEGIN_ALLOW_THREADS
Victor Stinner48b1ce52011-07-01 13:50:09 +02001536 err = select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &t);
1537 Py_END_ALLOW_THREADS
1538 if (err != 0) {
Guido van Rossum09cbb011999-11-08 15:32:27 +00001539#ifdef EINTR
Victor Stinner48b1ce52011-07-01 13:50:09 +02001540 if (errno == EINTR) {
1541 if (PyErr_CheckSignals())
1542 return -1;
1543 }
1544 else
Guido van Rossum09cbb011999-11-08 15:32:27 +00001545#endif
Victor Stinner48b1ce52011-07-01 13:50:09 +02001546 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001547 PyErr_SetFromErrno(PyExc_IOError);
1548 return -1;
1549 }
1550 }
Martin v. Löwis02af9642002-01-16 11:04:06 +00001551#elif defined(__WATCOMC__) && !defined(__QNX__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001552 /* XXX Can't interrupt this sleep */
1553 Py_BEGIN_ALLOW_THREADS
1554 delay((int)(secs * 1000 + 0.5)); /* delay() uses milliseconds */
1555 Py_END_ALLOW_THREADS
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001556#elif defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001557 {
1558 double millisecs = secs * 1000.0;
1559 unsigned long ul_millis;
Tim Peters513a1cd2003-01-19 04:54:58 +00001560
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001561 if (millisecs > (double)ULONG_MAX) {
1562 PyErr_SetString(PyExc_OverflowError,
1563 "sleep length is too large");
1564 return -1;
1565 }
1566 Py_BEGIN_ALLOW_THREADS
1567 /* Allow sleep(0) to maintain win32 semantics, and as decreed
1568 * by Guido, only the main thread can be interrupted.
1569 */
1570 ul_millis = (unsigned long)millisecs;
Antoine Pitrou6dd381e2011-11-21 21:26:56 +01001571 if (ul_millis == 0 || !_PyOS_IsMainThread())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001572 Sleep(ul_millis);
1573 else {
1574 DWORD rc;
Antoine Pitrou6dd381e2011-11-21 21:26:56 +01001575 HANDLE hInterruptEvent = _PyOS_SigintEvent();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001576 ResetEvent(hInterruptEvent);
1577 rc = WaitForSingleObject(hInterruptEvent, ul_millis);
1578 if (rc == WAIT_OBJECT_0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001579 Py_BLOCK_THREADS
1580 errno = EINTR;
1581 PyErr_SetFromErrno(PyExc_IOError);
1582 return -1;
1583 }
1584 }
1585 Py_END_ALLOW_THREADS
1586 }
Martin v. Löwis02af9642002-01-16 11:04:06 +00001587#elif defined(PYOS_OS2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001588 /* This Sleep *IS* Interruptable by Exceptions */
1589 Py_BEGIN_ALLOW_THREADS
1590 if (DosSleep(secs * 1000) != NO_ERROR) {
1591 Py_BLOCK_THREADS
1592 PyErr_SetFromErrno(PyExc_IOError);
1593 return -1;
1594 }
1595 Py_END_ALLOW_THREADS
Martin v. Löwis02af9642002-01-16 11:04:06 +00001596#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001597 /* XXX Can't interrupt this sleep */
1598 Py_BEGIN_ALLOW_THREADS
1599 sleep((int)secs);
1600 Py_END_ALLOW_THREADS
Martin v. Löwis02af9642002-01-16 11:04:06 +00001601#endif
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001602
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001603 return 0;
Guido van Rossum80c9d881991-04-16 08:47:51 +00001604}