blob: d5ffdcccbae6ed6f908f1f2b3476a64b3f22a93f [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
Victor Stinnera8ec5ea2012-03-13 00:25:42 +010040#if defined(__APPLE__)
41#include <mach/mach_time.h>
42#endif
43
Guido van Rossum234f9421993-06-17 12:35:49 +000044/* Forward declarations */
Tim Petersdbd9ba62000-07-09 03:09:57 +000045static int floatsleep(double);
Victor Stinnerec895392012-04-29 02:41:27 +020046static PyObject* floattime(_Py_clock_info_t *info);
47
48#ifdef MS_WINDOWS
49static OSVERSIONINFOEX winver;
50#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000051
Barry Warsaw9a2a8a81996-12-06 23:32:14 +000052static PyObject *
Victor Stinner4195b5c2012-02-08 23:03:19 +010053time_time(PyObject *self, PyObject *unused)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000054{
Victor Stinnerec895392012-04-29 02:41:27 +020055 return floattime(NULL);
Guido van Rossumb6775db1994-08-01 11:34:53 +000056}
57
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000058PyDoc_STRVAR(time_doc,
Victor Stinner4195b5c2012-02-08 23:03:19 +010059"time() -> floating point number\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +000060\n\
61Return the current time in seconds since the Epoch.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000062Fractions of a second may be present if the system clock provides them.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +000063
Victor Stinner85fdfa82012-01-27 00:38:48 +010064#if defined(HAVE_CLOCK)
65
66#ifndef CLOCKS_PER_SEC
67#ifdef CLK_TCK
68#define CLOCKS_PER_SEC CLK_TCK
69#else
70#define CLOCKS_PER_SEC 1000000
71#endif
72#endif
73
Victor Stinner4195b5c2012-02-08 23:03:19 +010074static PyObject *
Victor Stinnerec895392012-04-29 02:41:27 +020075floatclock(_Py_clock_info_t *info)
Victor Stinner85fdfa82012-01-27 00:38:48 +010076{
Victor Stinner4195b5c2012-02-08 23:03:19 +010077 clock_t value;
78 value = clock();
79 if (value == (clock_t)-1) {
Victor Stinner85fdfa82012-01-27 00:38:48 +010080 PyErr_SetString(PyExc_RuntimeError,
81 "the processor time used is not available "
82 "or its value cannot be represented");
Victor Stinner4195b5c2012-02-08 23:03:19 +010083 return NULL;
Victor Stinner85fdfa82012-01-27 00:38:48 +010084 }
Victor Stinnerec895392012-04-29 02:41:27 +020085 if (info) {
86 info->implementation = "clock()";
87 info->resolution = 1.0 / (double)CLOCKS_PER_SEC;
Benjamin Peterson49a69e42012-05-01 09:38:34 -040088 info->monotonic = 1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +020089 info->adjustable = 0;
Victor Stinnerec895392012-04-29 02:41:27 +020090 }
Victor Stinner4195b5c2012-02-08 23:03:19 +010091 return PyFloat_FromDouble((double)value / CLOCKS_PER_SEC);
Victor Stinner85fdfa82012-01-27 00:38:48 +010092}
93#endif /* HAVE_CLOCK */
94
Thomas Wouters477c8d52006-05-27 19:21:47 +000095#if defined(MS_WINDOWS) && !defined(__BORLANDC__)
Victor Stinnerec895392012-04-29 02:41:27 +020096#define WIN32_PERF_COUNTER
Victor Stinner9122fdd2011-07-04 13:55:40 +020097/* Win32 has better clock replacement; we have our own version, due to Mark
98 Hammond and Tim Peters */
Victor Stinnerec895392012-04-29 02:41:27 +020099static int
100win_perf_counter(_Py_clock_info_t *info, PyObject **result)
Guido van Rossum3917c221997-04-02 05:35:28 +0000101{
Victor Stinner8b302012012-02-07 23:29:46 +0100102 static LONGLONG cpu_frequency = 0;
Victor Stinner4195b5c2012-02-08 23:03:19 +0100103 static LONGLONG ctrStart;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000104 LARGE_INTEGER now;
Victor Stinner4195b5c2012-02-08 23:03:19 +0100105 double diff;
Guido van Rossum3917c221997-04-02 05:35:28 +0000106
Victor Stinner8b302012012-02-07 23:29:46 +0100107 if (cpu_frequency == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000108 LARGE_INTEGER freq;
Victor Stinner8b302012012-02-07 23:29:46 +0100109 QueryPerformanceCounter(&now);
Victor Stinner4195b5c2012-02-08 23:03:19 +0100110 ctrStart = now.QuadPart;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000111 if (!QueryPerformanceFrequency(&freq) || freq.QuadPart == 0) {
112 /* Unlikely to happen - this works on all intel
113 machines at least! Revert to clock() */
Victor Stinnerec895392012-04-29 02:41:27 +0200114 *result = NULL;
115 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000116 }
Victor Stinner8b302012012-02-07 23:29:46 +0100117 cpu_frequency = freq.QuadPart;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000118 }
119 QueryPerformanceCounter(&now);
Victor Stinner4195b5c2012-02-08 23:03:19 +0100120 diff = (double)(now.QuadPart - ctrStart);
Victor Stinnerec895392012-04-29 02:41:27 +0200121 if (info) {
122 info->implementation = "QueryPerformanceCounter()";
123 info->resolution = 1.0 / (double)cpu_frequency;
Benjamin Peterson49a69e42012-05-01 09:38:34 -0400124 info->monotonic = 1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +0200125 info->adjustable = 0;
Victor Stinnerec895392012-04-29 02:41:27 +0200126 }
127 *result = PyFloat_FromDouble(diff / (double)cpu_frequency);
128 return 0;
Guido van Rossum3917c221997-04-02 05:35:28 +0000129}
Victor Stinner8b302012012-02-07 23:29:46 +0100130#endif
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000131
Victor Stinnerec895392012-04-29 02:41:27 +0200132#if defined(WIN32_PERF_COUNTER) || defined(HAVE_CLOCK)
133#define PYCLOCK
134static PyObject*
135pyclock(_Py_clock_info_t *info)
136{
137#ifdef WIN32_PERF_COUNTER
138 PyObject *res;
139 if (win_perf_counter(info, &res) == 0)
140 return res;
141#endif
142 return floatclock(info);
143}
144
Victor Stinner9122fdd2011-07-04 13:55:40 +0200145static PyObject *
Victor Stinner4195b5c2012-02-08 23:03:19 +0100146time_clock(PyObject *self, PyObject *unused)
Victor Stinner9122fdd2011-07-04 13:55:40 +0200147{
Victor Stinnerec895392012-04-29 02:41:27 +0200148 return pyclock(NULL);
Victor Stinner9122fdd2011-07-04 13:55:40 +0200149}
Victor Stinner9122fdd2011-07-04 13:55:40 +0200150
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000151PyDoc_STRVAR(clock_doc,
Victor Stinner4195b5c2012-02-08 23:03:19 +0100152"clock() -> floating point number\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000153\n\
154Return the CPU time or real time since the start of the process or since\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000155the first call to clock(). This has as much precision as the system\n\
156records.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000157#endif
158
Victor Stinnere0be4232011-10-25 13:06:09 +0200159#ifdef HAVE_CLOCK_GETTIME
160static PyObject *
Victor Stinner4195b5c2012-02-08 23:03:19 +0100161time_clock_gettime(PyObject *self, PyObject *args)
Victor Stinnere0be4232011-10-25 13:06:09 +0200162{
163 int ret;
Victor Stinnerb8d01692012-04-13 23:44:05 +0200164 int clk_id;
Victor Stinnere0be4232011-10-25 13:06:09 +0200165 struct timespec tp;
166
Victor Stinner4195b5c2012-02-08 23:03:19 +0100167 if (!PyArg_ParseTuple(args, "i:clock_gettime", &clk_id))
Victor Stinnere0be4232011-10-25 13:06:09 +0200168 return NULL;
169
170 ret = clock_gettime((clockid_t)clk_id, &tp);
Antoine Pitrou2c085602012-01-18 01:41:44 +0100171 if (ret != 0) {
Victor Stinnere0be4232011-10-25 13:06:09 +0200172 PyErr_SetFromErrno(PyExc_IOError);
Antoine Pitrou2c085602012-01-18 01:41:44 +0100173 return NULL;
174 }
Victor Stinner4195b5c2012-02-08 23:03:19 +0100175 return PyFloat_FromDouble(tp.tv_sec + tp.tv_nsec * 1e-9);
Victor Stinnere0be4232011-10-25 13:06:09 +0200176}
177
178PyDoc_STRVAR(clock_gettime_doc,
Victor Stinner4195b5c2012-02-08 23:03:19 +0100179"clock_gettime(clk_id) -> floating point number\n\
Victor Stinnere0be4232011-10-25 13:06:09 +0200180\n\
181Return the time of the specified clock clk_id.");
Victor Stinner30d79472012-04-03 00:45:07 +0200182
183static PyObject *
184time_clock_settime(PyObject *self, PyObject *args)
185{
Victor Stinnerb8d01692012-04-13 23:44:05 +0200186 int clk_id;
Victor Stinner30d79472012-04-03 00:45:07 +0200187 PyObject *obj;
188 struct timespec tp;
189 int ret;
190
191 if (!PyArg_ParseTuple(args, "iO:clock_settime", &clk_id, &obj))
192 return NULL;
193
194 if (_PyTime_ObjectToTimespec(obj, &tp.tv_sec, &tp.tv_nsec) == -1)
195 return NULL;
196
197 ret = clock_settime((clockid_t)clk_id, &tp);
198 if (ret != 0) {
199 PyErr_SetFromErrno(PyExc_IOError);
200 return NULL;
201 }
202 Py_RETURN_NONE;
203}
204
205PyDoc_STRVAR(clock_settime_doc,
206"clock_settime(clk_id, time)\n\
207\n\
208Set the time of the specified clock clk_id.");
Victor Stinnere0be4232011-10-25 13:06:09 +0200209
Victor Stinnere0be4232011-10-25 13:06:09 +0200210static PyObject *
Victor Stinner4195b5c2012-02-08 23:03:19 +0100211time_clock_getres(PyObject *self, PyObject *args)
Victor Stinnere0be4232011-10-25 13:06:09 +0200212{
213 int ret;
Victor Stinnerb8d01692012-04-13 23:44:05 +0200214 int clk_id;
Victor Stinnere0be4232011-10-25 13:06:09 +0200215 struct timespec tp;
216
Victor Stinner4195b5c2012-02-08 23:03:19 +0100217 if (!PyArg_ParseTuple(args, "i:clock_getres", &clk_id))
Victor Stinnere0be4232011-10-25 13:06:09 +0200218 return NULL;
219
220 ret = clock_getres((clockid_t)clk_id, &tp);
Antoine Pitrou2c085602012-01-18 01:41:44 +0100221 if (ret != 0) {
Victor Stinnere0be4232011-10-25 13:06:09 +0200222 PyErr_SetFromErrno(PyExc_IOError);
Antoine Pitrou2c085602012-01-18 01:41:44 +0100223 return NULL;
224 }
Victor Stinner4195b5c2012-02-08 23:03:19 +0100225
226 return PyFloat_FromDouble(tp.tv_sec + tp.tv_nsec * 1e-9);
Victor Stinnere0be4232011-10-25 13:06:09 +0200227}
228
229PyDoc_STRVAR(clock_getres_doc,
Victor Stinner4195b5c2012-02-08 23:03:19 +0100230"clock_getres(clk_id) -> floating point number\n\
Victor Stinnere0be4232011-10-25 13:06:09 +0200231\n\
232Return the resolution (precision) of the specified clock clk_id.");
Victor Stinnerb8d01692012-04-13 23:44:05 +0200233#endif /* HAVE_CLOCK_GETTIME */
Victor Stinnere0be4232011-10-25 13:06:09 +0200234
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000235static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000236time_sleep(PyObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000237{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000238 double secs;
239 if (!PyArg_ParseTuple(args, "d:sleep", &secs))
240 return NULL;
Victor Stinner7f53a502011-07-05 22:00:25 +0200241 if (secs < 0) {
242 PyErr_SetString(PyExc_ValueError,
243 "sleep length must be non-negative");
244 return NULL;
245 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000246 if (floatsleep(secs) != 0)
247 return NULL;
248 Py_INCREF(Py_None);
249 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000250}
251
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000252PyDoc_STRVAR(sleep_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000253"sleep(seconds)\n\
254\n\
255Delay execution for a given number of seconds. The argument may be\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000256a floating point number for subsecond precision.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000257
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000258static PyStructSequence_Field struct_time_type_fields[] = {
Alexander Belopolsky69f3fd02010-06-05 15:04:51 +0000259 {"tm_year", "year, for example, 1993"},
260 {"tm_mon", "month of year, range [1, 12]"},
261 {"tm_mday", "day of month, range [1, 31]"},
262 {"tm_hour", "hours, range [0, 23]"},
263 {"tm_min", "minutes, range [0, 59]"},
264 {"tm_sec", "seconds, range [0, 61])"},
265 {"tm_wday", "day of week, range [0, 6], Monday is 0"},
266 {"tm_yday", "day of year, range [1, 366]"},
267 {"tm_isdst", "1 if summer time is in effect, 0 if not, and -1 if unknown"},
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400268#ifdef HAVE_STRUCT_TM_TM_ZONE
269 {"tm_zone", "abbreviation of timezone name"},
270 {"tm_gmtoff", "offset from UTC in seconds"},
271#endif /* HAVE_STRUCT_TM_TM_ZONE */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000272 {0}
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000273};
274
275static PyStructSequence_Desc struct_time_type_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000276 "time.struct_time",
Alexander Belopolsky69f3fd02010-06-05 15:04:51 +0000277 "The time value as returned by gmtime(), localtime(), and strptime(), and\n"
278 " accepted by asctime(), mktime() and strftime(). May be considered as a\n"
279 " sequence of 9 integers.\n\n"
280 " Note that several fields' values are not the same as those defined by\n"
281 " the C language standard for struct tm. For example, the value of the\n"
282 " field tm_year is the actual year, not year - 1900. See individual\n"
283 " fields' descriptions for details.",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000284 struct_time_type_fields,
285 9,
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000286};
Tim Peters9ad4b682002-02-13 05:14:18 +0000287
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000288static int initialized;
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000289static PyTypeObject StructTimeType;
290
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400291
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000292static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000293tmtotuple(struct tm *p)
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000294{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000295 PyObject *v = PyStructSequence_New(&StructTimeType);
296 if (v == NULL)
297 return NULL;
Tim Peters9ad4b682002-02-13 05:14:18 +0000298
Christian Heimes217cfd12007-12-02 14:31:20 +0000299#define SET(i,val) PyStructSequence_SET_ITEM(v, i, PyLong_FromLong((long) val))
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000300
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000301 SET(0, p->tm_year + 1900);
302 SET(1, p->tm_mon + 1); /* Want January == 1 */
303 SET(2, p->tm_mday);
304 SET(3, p->tm_hour);
305 SET(4, p->tm_min);
306 SET(5, p->tm_sec);
307 SET(6, (p->tm_wday + 6) % 7); /* Want Monday == 0 */
308 SET(7, p->tm_yday + 1); /* Want January, 1 == 1 */
309 SET(8, p->tm_isdst);
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400310#ifdef HAVE_STRUCT_TM_TM_ZONE
311 PyStructSequence_SET_ITEM(v, 9,
312 PyUnicode_DecodeLocale(p->tm_zone, "surrogateescape"));
313 SET(10, p->tm_gmtoff);
314#endif /* HAVE_STRUCT_TM_TM_ZONE */
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000315#undef SET
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000316 if (PyErr_Occurred()) {
317 Py_XDECREF(v);
318 return NULL;
319 }
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000320
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000321 return v;
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000322}
323
Fred Drakef901abd2004-08-03 17:58:55 +0000324/* Parse arg tuple that can contain an optional float-or-None value;
325 format needs to be "|O:name".
326 Returns non-zero on success (parallels PyArg_ParseTuple).
327*/
328static int
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100329parse_time_t_args(PyObject *args, char *format, time_t *pwhen)
Fred Drakef901abd2004-08-03 17:58:55 +0000330{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000331 PyObject *ot = NULL;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100332 time_t whent;
Fred Drakef901abd2004-08-03 17:58:55 +0000333
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000334 if (!PyArg_ParseTuple(args, format, &ot))
335 return 0;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100336 if (ot == NULL || ot == Py_None) {
337 whent = time(NULL);
338 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000339 else {
Victor Stinner5d272cc2012-03-13 13:35:55 +0100340 if (_PyTime_ObjectToTime_t(ot, &whent) == -1)
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100341 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000342 }
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100343 *pwhen = whent;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000344 return 1;
Fred Drakef901abd2004-08-03 17:58:55 +0000345}
346
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000347static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000348time_gmtime(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, *local;
352
353 if (!parse_time_t_args(args, "|O:gmtime", &when))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000354 return NULL;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100355
356 errno = 0;
357 local = gmtime(&when);
358 if (local == NULL) {
359#ifdef EINVAL
360 if (errno == 0)
361 errno = EINVAL;
362#endif
363 return PyErr_SetFromErrno(PyExc_OSError);
364 }
365 buf = *local;
366 return tmtotuple(&buf);
Guido van Rossum234f9421993-06-17 12:35:49 +0000367}
368
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000369PyDoc_STRVAR(gmtime_doc,
Christian Heimes9a371592007-12-28 14:08:13 +0000370"gmtime([seconds]) -> (tm_year, tm_mon, tm_mday, tm_hour, tm_min,\n\
Fred Drake193a3f62002-03-12 21:38:49 +0000371 tm_sec, tm_wday, tm_yday, tm_isdst)\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000372\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000373Convert seconds since the Epoch to a time tuple expressing UTC (a.k.a.\n\
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400374GMT). When 'seconds' is not passed in, convert the current time instead.\n\
375\n\
376If the platform supports the tm_gmtoff and tm_zone, they are available as\n\
377attributes only.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000378
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100379static int
380pylocaltime(time_t *timep, struct tm *result)
381{
382 struct tm *local;
383
384 assert (timep != NULL);
385 local = localtime(timep);
386 if (local == NULL) {
387 /* unconvertible time */
388#ifdef EINVAL
389 if (errno == 0)
390 errno = EINVAL;
391#endif
392 PyErr_SetFromErrno(PyExc_OSError);
393 return -1;
394 }
395 *result = *local;
396 return 0;
397}
398
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000399static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000400time_localtime(PyObject *self, PyObject *args)
Guido van Rossum234f9421993-06-17 12:35:49 +0000401{
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100402 time_t when;
403 struct tm buf;
404
405 if (!parse_time_t_args(args, "|O:localtime", &when))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000406 return NULL;
Alexander Belopolskyd9738242012-06-12 16:14:17 -0400407 if (pylocaltime(&when, &buf) == -1)
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100408 return NULL;
409 return tmtotuple(&buf);
Guido van Rossum234f9421993-06-17 12:35:49 +0000410}
411
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000412PyDoc_STRVAR(localtime_doc,
Christian Heimes9a371592007-12-28 14:08:13 +0000413"localtime([seconds]) -> (tm_year,tm_mon,tm_mday,tm_hour,tm_min,\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000414 tm_sec,tm_wday,tm_yday,tm_isdst)\n\
Martin v. Löwisb3cfc1d2001-12-02 12:27:43 +0000415\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000416Convert seconds since the Epoch to a time tuple expressing local time.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000417When 'seconds' is not passed in, convert the current time instead.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000418
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000419/* Convert 9-item tuple to tm structure. Return 1 on success, set
420 * an exception and return 0 on error.
421 */
Guido van Rossum9e90a671993-06-24 11:10:19 +0000422static int
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000423gettmarg(PyObject *args, struct tm *p)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000424{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000425 int y;
Guido van Rossumcfbaecc1998-08-25 14:51:12 +0000426
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000427 memset((void *) p, '\0', sizeof(struct tm));
Guido van Rossumb9081262007-08-25 03:14:09 +0000428
Alexander Belopolsky610e5442011-01-06 21:57:06 +0000429 if (!PyTuple_Check(args)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000430 PyErr_SetString(PyExc_TypeError,
431 "Tuple or struct_time argument required");
432 return 0;
433 }
Skip Montanaro41cfce92007-08-24 21:11:00 +0000434
Alexander Belopolsky610e5442011-01-06 21:57:06 +0000435 if (!PyArg_ParseTuple(args, "iiiiiiiii",
436 &y, &p->tm_mon, &p->tm_mday,
437 &p->tm_hour, &p->tm_min, &p->tm_sec,
438 &p->tm_wday, &p->tm_yday, &p->tm_isdst))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000439 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000440 p->tm_year = y - 1900;
441 p->tm_mon--;
442 p->tm_wday = (p->tm_wday + 1) % 7;
443 p->tm_yday--;
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400444#ifdef HAVE_STRUCT_TM_TM_ZONE
445 if (Py_TYPE(args) == &StructTimeType) {
446 PyObject *item;
447 item = PyTuple_GET_ITEM(args, 9);
448 p->tm_zone = item == Py_None ? NULL : _PyUnicode_AsString(item);
449 item = PyTuple_GET_ITEM(args, 10);
450 p->tm_gmtoff = item == Py_None ? 0 : PyLong_AsLong(item);
451 if (PyErr_Occurred())
452 return 0;
453 }
454#endif /* HAVE_STRUCT_TM_TM_ZONE */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000455 return 1;
Guido van Rossum9e90a671993-06-24 11:10:19 +0000456}
457
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000458/* Check values of the struct tm fields before it is passed to strftime() and
459 * asctime(). Return 1 if all values are valid, otherwise set an exception
460 * and returns 0.
461 */
Victor Stinneref128102010-10-07 01:00:52 +0000462static int
463checktm(struct tm* buf)
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000464{
Victor Stinneref128102010-10-07 01:00:52 +0000465 /* Checks added to make sure strftime() and asctime() does not crash Python by
466 indexing blindly into some array for a textual representation
467 by some bad index (fixes bug #897625 and #6608).
468
469 Also support values of zero from Python code for arguments in which
470 that is out of range by forcing that value to the lowest value that
471 is valid (fixed bug #1520914).
472
473 Valid ranges based on what is allowed in struct tm:
474
475 - tm_year: [0, max(int)] (1)
476 - tm_mon: [0, 11] (2)
477 - tm_mday: [1, 31]
478 - tm_hour: [0, 23]
479 - tm_min: [0, 59]
480 - tm_sec: [0, 60]
481 - tm_wday: [0, 6] (1)
482 - tm_yday: [0, 365] (2)
483 - tm_isdst: [-max(int), max(int)]
484
485 (1) gettmarg() handles bounds-checking.
486 (2) Python's acceptable range is one greater than the range in C,
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000487 thus need to check against automatic decrement by gettmarg().
488 */
489 if (buf->tm_mon == -1)
490 buf->tm_mon = 0;
491 else if (buf->tm_mon < 0 || buf->tm_mon > 11) {
492 PyErr_SetString(PyExc_ValueError, "month out of range");
493 return 0;
494 }
495 if (buf->tm_mday == 0)
496 buf->tm_mday = 1;
497 else if (buf->tm_mday < 0 || buf->tm_mday > 31) {
498 PyErr_SetString(PyExc_ValueError, "day of month out of range");
499 return 0;
500 }
501 if (buf->tm_hour < 0 || buf->tm_hour > 23) {
502 PyErr_SetString(PyExc_ValueError, "hour out of range");
503 return 0;
504 }
505 if (buf->tm_min < 0 || buf->tm_min > 59) {
506 PyErr_SetString(PyExc_ValueError, "minute out of range");
507 return 0;
508 }
509 if (buf->tm_sec < 0 || buf->tm_sec > 61) {
510 PyErr_SetString(PyExc_ValueError, "seconds out of range");
511 return 0;
512 }
513 /* tm_wday does not need checking of its upper-bound since taking
514 ``% 7`` in gettmarg() automatically restricts the range. */
515 if (buf->tm_wday < 0) {
516 PyErr_SetString(PyExc_ValueError, "day of week out of range");
517 return 0;
518 }
519 if (buf->tm_yday == -1)
520 buf->tm_yday = 0;
521 else if (buf->tm_yday < 0 || buf->tm_yday > 365) {
522 PyErr_SetString(PyExc_ValueError, "day of year out of range");
523 return 0;
524 }
525 return 1;
526}
527
Victor Stinnerc1f32ca2011-10-14 02:36:13 +0200528#ifdef MS_WINDOWS
529 /* wcsftime() doesn't format correctly time zones, see issue #10653 */
530# undef HAVE_WCSFTIME
531#endif
Alexander Belopolskycf774542012-10-02 18:39:16 -0400532#define STRFTIME_FORMAT_CODES \
533"Commonly used format codes:\n\
534\n\
535%Y Year with century as a decimal number.\n\
536%m Month as a decimal number [01,12].\n\
537%d Day of the month as a decimal number [01,31].\n\
538%H Hour (24-hour clock) as a decimal number [00,23].\n\
539%M Minute as a decimal number [00,59].\n\
540%S Second as a decimal number [00,61].\n\
541%z Time zone offset from UTC.\n\
542%a Locale's abbreviated weekday name.\n\
543%A Locale's full weekday name.\n\
544%b Locale's abbreviated month name.\n\
545%B Locale's full month name.\n\
546%c Locale's appropriate date and time representation.\n\
547%I Hour (12-hour clock) as a decimal number [01,12].\n\
548%p Locale's equivalent of either AM or PM.\n\
549\n\
550Other codes may be available on your platform. See documentation for\n\
551the C library strftime function.\n"
Victor Stinnerc1f32ca2011-10-14 02:36:13 +0200552
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000553#ifdef HAVE_STRFTIME
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000554#ifdef HAVE_WCSFTIME
555#define time_char wchar_t
556#define format_time wcsftime
557#define time_strlen wcslen
558#else
559#define time_char char
560#define format_time strftime
561#define time_strlen strlen
562#endif
563
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000564static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000565time_strftime(PyObject *self, PyObject *args)
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000566{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000567 PyObject *tup = NULL;
568 struct tm buf;
569 const time_char *fmt;
Victor Stinnerb2904782010-09-29 10:34:19 +0000570#ifdef HAVE_WCSFTIME
571 wchar_t *format;
572#else
573 PyObject *format;
574#endif
Victor Stinneref128102010-10-07 01:00:52 +0000575 PyObject *format_arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000576 size_t fmtlen, buflen;
Victor Stinnerb2904782010-09-29 10:34:19 +0000577 time_char *outbuf = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000578 size_t i;
Victor Stinnerb2904782010-09-29 10:34:19 +0000579 PyObject *ret = NULL;
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000580
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000581 memset((void *) &buf, '\0', sizeof(buf));
Guido van Rossum1f41f841998-04-27 19:04:26 +0000582
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000583 /* Will always expect a unicode string to be passed as format.
584 Given that there's no str type anymore in py3k this seems safe.
585 */
Victor Stinneref128102010-10-07 01:00:52 +0000586 if (!PyArg_ParseTuple(args, "U|O:strftime", &format_arg, &tup))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000587 return NULL;
Thomas Woutersfe385252001-01-19 23:16:56 +0000588
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000589 if (tup == NULL) {
590 time_t tt = time(NULL);
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100591 if (pylocaltime(&tt, &buf) == -1)
592 return NULL;
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000593 }
594 else if (!gettmarg(tup, &buf) || !checktm(&buf))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000595 return NULL;
Guido van Rossum10b164a2001-09-25 13:59:01 +0000596
Victor Stinner06ec45e2011-01-08 03:35:36 +0000597#if defined(_MSC_VER) || defined(sun)
Victor Stinner73ea29c2011-01-08 01:56:31 +0000598 if (buf.tm_year + 1900 < 1 || 9999 < buf.tm_year + 1900) {
Victor Stinner6f0e4f92011-03-21 02:14:53 +0100599 PyErr_SetString(PyExc_ValueError,
600 "strftime() requires year in [1; 9999]");
Alexander Belopolsky0dd06f42011-01-08 01:23:02 +0000601 return NULL;
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000602 }
Victor Stinner73ea29c2011-01-08 01:56:31 +0000603#endif
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000604
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000605 /* Normalize tm_isdst just in case someone foolishly implements %Z
606 based on the assumption that tm_isdst falls within the range of
607 [-1, 1] */
608 if (buf.tm_isdst < -1)
609 buf.tm_isdst = -1;
610 else if (buf.tm_isdst > 1)
611 buf.tm_isdst = 1;
Brett Cannond1080a32004-03-02 04:38:10 +0000612
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000613#ifdef HAVE_WCSFTIME
Victor Stinnerbeb4135b2010-10-07 01:02:42 +0000614 format = PyUnicode_AsWideCharString(format_arg, NULL);
Victor Stinnerb2904782010-09-29 10:34:19 +0000615 if (format == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000616 return NULL;
Victor Stinnerb2904782010-09-29 10:34:19 +0000617 fmt = format;
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000618#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000619 /* Convert the unicode string to an ascii one */
Victor Stinner1b579672011-12-17 05:47:23 +0100620 format = PyUnicode_EncodeLocale(format_arg, "surrogateescape");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000621 if (format == NULL)
622 return NULL;
623 fmt = PyBytes_AS_STRING(format);
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000624#endif
Amaury Forgeot d'Arcb5be6d42009-03-02 23:52:57 +0000625
Stefan Krah4aea7d32012-02-27 16:30:26 +0100626#if defined(MS_WINDOWS) && !defined(HAVE_WCSFTIME)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000627 /* check that the format string contains only valid directives */
Victor Stinner5a3ff792011-10-16 19:08:23 +0200628 for(outbuf = strchr(fmt, '%');
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000629 outbuf != NULL;
Victor Stinner5a3ff792011-10-16 19:08:23 +0200630 outbuf = strchr(outbuf+2, '%'))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000631 {
632 if (outbuf[1]=='#')
633 ++outbuf; /* not documented by python, */
634 if (outbuf[1]=='\0' ||
Victor Stinner5a3ff792011-10-16 19:08:23 +0200635 !strchr("aAbBcdHIjmMpSUwWxXyYzZ%", outbuf[1]))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000636 {
637 PyErr_SetString(PyExc_ValueError, "Invalid format string");
Stefan Krah4aea7d32012-02-27 16:30:26 +0100638 Py_DECREF(format);
639 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000640 }
641 }
Amaury Forgeot d'Arcb5be6d42009-03-02 23:52:57 +0000642#endif
643
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000644 fmtlen = time_strlen(fmt);
Guido van Rossumc222ec21999-02-23 00:00:10 +0000645
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000646 /* I hate these functions that presume you know how big the output
647 * will be ahead of time...
648 */
649 for (i = 1024; ; i += i) {
Victor Stinner136ea492011-12-17 22:37:18 +0100650#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100651 int err;
Victor Stinner136ea492011-12-17 22:37:18 +0100652#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000653 outbuf = (time_char *)PyMem_Malloc(i*sizeof(time_char));
654 if (outbuf == NULL) {
Victor Stinnerb2904782010-09-29 10:34:19 +0000655 PyErr_NoMemory();
656 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000657 }
658 buflen = format_time(outbuf, i, fmt, &buf);
Victor Stinner136ea492011-12-17 22:37:18 +0100659#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100660 err = errno;
Victor Stinner136ea492011-12-17 22:37:18 +0100661#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000662 if (buflen > 0 || i >= 256 * fmtlen) {
663 /* If the buffer is 256 times as long as the format,
664 it's probably not failing for lack of room!
665 More likely, the format yields an empty result,
666 e.g. an empty format, or %Z when the timezone
667 is unknown. */
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000668#ifdef HAVE_WCSFTIME
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000669 ret = PyUnicode_FromWideChar(outbuf, buflen);
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000670#else
Victor Stinner1b579672011-12-17 05:47:23 +0100671 ret = PyUnicode_DecodeLocaleAndSize(outbuf, buflen,
672 "surrogateescape");
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000673#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000674 PyMem_Free(outbuf);
Victor Stinnerb2904782010-09-29 10:34:19 +0000675 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000676 }
677 PyMem_Free(outbuf);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000678#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000679 /* VisualStudio .NET 2005 does this properly */
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100680 if (buflen == 0 && err == EINVAL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000681 PyErr_SetString(PyExc_ValueError, "Invalid format string");
Victor Stinnerb2904782010-09-29 10:34:19 +0000682 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000683 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000684#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000685 }
Victor Stinnerb2904782010-09-29 10:34:19 +0000686#ifdef HAVE_WCSFTIME
687 PyMem_Free(format);
688#else
689 Py_DECREF(format);
690#endif
691 return ret;
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000692}
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000693
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000694#undef time_char
695#undef format_time
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000696PyDoc_STRVAR(strftime_doc,
Thomas Woutersfe385252001-01-19 23:16:56 +0000697"strftime(format[, tuple]) -> string\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000698\n\
699Convert a time tuple to a string according to a format specification.\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000700See the library reference manual for formatting codes. When the time tuple\n\
Alexander Belopolskycf774542012-10-02 18:39:16 -0400701is not present, current time as returned by localtime() is used.\n\
702\n" STRFTIME_FORMAT_CODES);
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000703#endif /* HAVE_STRFTIME */
704
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000705static PyObject *
706time_strptime(PyObject *self, PyObject *args)
707{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000708 PyObject *strptime_module = PyImport_ImportModuleNoBlock("_strptime");
709 PyObject *strptime_result;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200710 _Py_IDENTIFIER(_strptime_time);
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000711
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000712 if (!strptime_module)
713 return NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200714 strptime_result = _PyObject_CallMethodId(strptime_module,
715 &PyId__strptime_time, "O", args);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000716 Py_DECREF(strptime_module);
717 return strptime_result;
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000718}
719
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000720
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000721PyDoc_STRVAR(strptime_doc,
Brett Cannon20def8b2003-07-01 05:16:08 +0000722"strptime(string, format) -> struct_time\n\
Martin v. Löwisb3cfc1d2001-12-02 12:27:43 +0000723\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000724Parse a string to a time tuple according to a format specification.\n\
Alexander Belopolskycf774542012-10-02 18:39:16 -0400725See the library reference manual for formatting codes (same as\n\
726strftime()).\n\
727\n" STRFTIME_FORMAT_CODES);
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000728
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000729static PyObject *
730_asctime(struct tm *timeptr)
731{
732 /* Inspired by Open Group reference implementation available at
733 * http://pubs.opengroup.org/onlinepubs/009695399/functions/asctime.html */
Victor Stinner499dfcf2011-03-21 13:26:24 +0100734 static char wday_name[7][4] = {
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000735 "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
736 };
Victor Stinner499dfcf2011-03-21 13:26:24 +0100737 static char mon_name[12][4] = {
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000738 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
739 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
740 };
Victor Stinner499dfcf2011-03-21 13:26:24 +0100741 return PyUnicode_FromFormat(
742 "%s %s%3d %.2d:%.2d:%.2d %d",
743 wday_name[timeptr->tm_wday],
744 mon_name[timeptr->tm_mon],
745 timeptr->tm_mday, timeptr->tm_hour,
746 timeptr->tm_min, timeptr->tm_sec,
747 1900 + timeptr->tm_year);
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000748}
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000749
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000750static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000751time_asctime(PyObject *self, PyObject *args)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000752{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000753 PyObject *tup = NULL;
754 struct tm buf;
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000755
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000756 if (!PyArg_UnpackTuple(args, "asctime", 0, 1, &tup))
757 return NULL;
758 if (tup == NULL) {
759 time_t tt = time(NULL);
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100760 if (pylocaltime(&tt, &buf) == -1)
761 return NULL;
762
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000763 } else if (!gettmarg(tup, &buf) || !checktm(&buf))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000764 return NULL;
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000765 return _asctime(&buf);
Guido van Rossum9e90a671993-06-24 11:10:19 +0000766}
767
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000768PyDoc_STRVAR(asctime_doc,
Thomas Woutersfe385252001-01-19 23:16:56 +0000769"asctime([tuple]) -> string\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000770\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000771Convert a time tuple to a string, e.g. 'Sat Jun 06 16:26:11 1998'.\n\
772When the time tuple is not present, current time as returned by localtime()\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000773is used.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000774
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000775static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000776time_ctime(PyObject *self, PyObject *args)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000777{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000778 time_t tt;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100779 struct tm buf;
780 if (!parse_time_t_args(args, "|O:ctime", &tt))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000781 return NULL;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100782 if (pylocaltime(&tt, &buf) == -1)
Alexander Belopolsky5da468f2011-01-04 17:15:52 +0000783 return NULL;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100784 return _asctime(&buf);
Guido van Rossum9e90a671993-06-24 11:10:19 +0000785}
786
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000787PyDoc_STRVAR(ctime_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000788"ctime(seconds) -> string\n\
789\n\
790Convert a time in seconds since the Epoch to a string in local time.\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000791This is equivalent to asctime(localtime(seconds)). When the time tuple is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000792not present, current time as returned by localtime() is used.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000793
Guido van Rossum60cd8131998-03-06 17:16:21 +0000794#ifdef HAVE_MKTIME
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000795static PyObject *
Victor Stinner4195b5c2012-02-08 23:03:19 +0100796time_mktime(PyObject *self, PyObject *tup)
Guido van Rossum234f9421993-06-17 12:35:49 +0000797{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000798 struct tm buf;
799 time_t tt;
800 if (!gettmarg(tup, &buf))
801 return NULL;
Alexander Belopolskyb7d40d12011-01-11 01:21:25 +0000802 buf.tm_wday = -1; /* sentinel; original value ignored */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000803 tt = mktime(&buf);
Alexander Belopolskyb7d40d12011-01-11 01:21:25 +0000804 /* Return value of -1 does not necessarily mean an error, but tm_wday
Ezio Melotti13925002011-03-16 11:05:33 +0200805 * cannot remain set to -1 if mktime succeeded. */
Alexander Belopolskyb7d40d12011-01-11 01:21:25 +0000806 if (tt == (time_t)(-1) && buf.tm_wday == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000807 PyErr_SetString(PyExc_OverflowError,
808 "mktime argument out of range");
809 return NULL;
810 }
Victor Stinner4195b5c2012-02-08 23:03:19 +0100811 return PyFloat_FromDouble((double)tt);
Guido van Rossum234f9421993-06-17 12:35:49 +0000812}
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000813
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000814PyDoc_STRVAR(mktime_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000815"mktime(tuple) -> floating point number\n\
816\n\
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400817Convert a time tuple in local time to seconds since the Epoch.\n\
818Note that mktime(gmtime(0)) will not generally return zero for most\n\
819time zones; instead the returned value will either be equal to that\n\
820of the timezone or altzone attributes on the time module.");
Guido van Rossum60cd8131998-03-06 17:16:21 +0000821#endif /* HAVE_MKTIME */
Guido van Rossum234f9421993-06-17 12:35:49 +0000822
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000823#ifdef HAVE_WORKING_TZSET
Martin v. Löwis1a214512008-06-11 05:26:20 +0000824static void PyInit_timezone(PyObject *module);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000825
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000826static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000827time_tzset(PyObject *self, PyObject *unused)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000828{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000829 PyObject* m;
Fred Drake9bb74322002-04-01 14:49:59 +0000830
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000831 m = PyImport_ImportModuleNoBlock("time");
832 if (m == NULL) {
833 return NULL;
834 }
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000835
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000836 tzset();
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000837
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000838 /* Reset timezone, altzone, daylight and tzname */
839 PyInit_timezone(m);
840 Py_DECREF(m);
Tim Peters1b6f7a92004-06-20 02:50:16 +0000841
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000842 Py_INCREF(Py_None);
843 return Py_None;
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000844}
845
846PyDoc_STRVAR(tzset_doc,
R. David Murray4d55bf92010-12-14 00:55:46 +0000847"tzset()\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000848\n\
849Initialize, or reinitialize, the local timezone to the value stored in\n\
850os.environ['TZ']. The TZ environment variable should be specified in\n\
Neal Norwitzdc8e1942004-07-20 22:34:37 +0000851standard Unix timezone format as documented in the tzset man page\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000852(eg. 'US/Eastern', 'Europe/Amsterdam'). Unknown timezones will silently\n\
853fall back to UTC. If the TZ environment variable is not set, the local\n\
854timezone is set to the systems best guess of wallclock time.\n\
855Changing the TZ environment variable without calling tzset *may* change\n\
856the local timezone used by methods such as localtime, but this behaviour\n\
857should not be relied on.");
858#endif /* HAVE_WORKING_TZSET */
859
Victor Stinnerec895392012-04-29 02:41:27 +0200860#if defined(MS_WINDOWS) || defined(__APPLE__) \
861 || (defined(HAVE_CLOCK_GETTIME) \
862 && (defined(CLOCK_HIGHRES) || defined(CLOCK_MONOTONIC)))
863#define PYMONOTONIC
864#endif
865
866#ifdef PYMONOTONIC
Victor Stinner071eca32012-03-15 01:17:09 +0100867static PyObject*
Victor Stinnerec895392012-04-29 02:41:27 +0200868pymonotonic(_Py_clock_info_t *info)
Victor Stinnerb94b2662012-01-18 01:50:21 +0100869{
Victor Stinnerec895392012-04-29 02:41:27 +0200870#if defined(MS_WINDOWS)
871 static ULONGLONG (*GetTickCount64) (void) = NULL;
872 static ULONGLONG (CALLBACK *Py_GetTickCount64)(void);
873 static int has_getickcount64 = -1;
874 double result;
875
876 if (has_getickcount64 == -1) {
877 /* GetTickCount64() was added to Windows Vista */
878 if (winver.dwMajorVersion >= 6) {
879 HINSTANCE hKernel32;
880 hKernel32 = GetModuleHandleW(L"KERNEL32");
881 *(FARPROC*)&Py_GetTickCount64 = GetProcAddress(hKernel32,
882 "GetTickCount64");
883 has_getickcount64 = (Py_GetTickCount64 != NULL);
884 }
885 else
886 has_getickcount64 = 0;
887 }
888
889 if (has_getickcount64) {
890 ULONGLONG ticks;
891 ticks = Py_GetTickCount64();
892 result = (double)ticks * 1e-3;
893 }
894 else {
895 static DWORD last_ticks = 0;
896 static DWORD n_overflow = 0;
897 DWORD ticks;
898
899 ticks = GetTickCount();
900 if (ticks < last_ticks)
901 n_overflow++;
902 last_ticks = ticks;
903
904 result = ldexp(n_overflow, 32);
905 result += ticks;
906 result *= 1e-3;
907 }
908
909 if (info) {
910 DWORD timeAdjustment, timeIncrement;
911 BOOL isTimeAdjustmentDisabled, ok;
912 if (has_getickcount64)
913 info->implementation = "GetTickCount64()";
914 else
915 info->implementation = "GetTickCount()";
Benjamin Peterson49a69e42012-05-01 09:38:34 -0400916 info->monotonic = 1;
Victor Stinnerec895392012-04-29 02:41:27 +0200917 ok = GetSystemTimeAdjustment(&timeAdjustment, &timeIncrement,
918 &isTimeAdjustmentDisabled);
919 if (!ok) {
920 PyErr_SetFromWindowsErr(0);
921 return NULL;
922 }
923 info->resolution = timeIncrement * 1e-7;
Victor Stinner2b89fdf2012-06-12 22:46:37 +0200924 info->adjustable = 0;
Victor Stinnerec895392012-04-29 02:41:27 +0200925 }
926 return PyFloat_FromDouble(result);
927
Victor Stinnera8ec5ea2012-03-13 00:25:42 +0100928#elif defined(__APPLE__)
Victor Stinner74eb6c02012-03-28 02:50:46 +0200929 static mach_timebase_info_data_t timebase;
930 uint64_t time;
Victor Stinnera8ec5ea2012-03-13 00:25:42 +0100931 double secs;
932
Victor Stinner74eb6c02012-03-28 02:50:46 +0200933 if (timebase.denom == 0) {
934 /* According to the Technical Q&A QA1398, mach_timebase_info() cannot
935 fail: https://developer.apple.com/library/mac/#qa/qa1398/ */
936 (void)mach_timebase_info(&timebase);
937 }
Victor Stinnera8ec5ea2012-03-13 00:25:42 +0100938
Victor Stinner74eb6c02012-03-28 02:50:46 +0200939 time = mach_absolute_time();
Victor Stinnera8ec5ea2012-03-13 00:25:42 +0100940 secs = (double)time * timebase.numer / timebase.denom * 1e-9;
Victor Stinnerec895392012-04-29 02:41:27 +0200941 if (info) {
942 info->implementation = "mach_absolute_time()";
943 info->resolution = (double)timebase.numer / timebase.denom * 1e-9;
Benjamin Peterson49a69e42012-05-01 09:38:34 -0400944 info->monotonic = 1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +0200945 info->adjustable = 0;
Victor Stinnerec895392012-04-29 02:41:27 +0200946 }
Victor Stinnera8ec5ea2012-03-13 00:25:42 +0100947 return PyFloat_FromDouble(secs);
Victor Stinnerec895392012-04-29 02:41:27 +0200948
949#elif defined(HAVE_CLOCK_GETTIME) && (defined(CLOCK_HIGHRES) || defined(CLOCK_MONOTONIC))
Victor Stinner8b302012012-02-07 23:29:46 +0100950 struct timespec tp;
Victor Stinnerec895392012-04-29 02:41:27 +0200951#ifdef CLOCK_HIGHRES
952 const clockid_t clk_id = CLOCK_HIGHRES;
953 const char *function = "clock_gettime(CLOCK_HIGHRES)";
954#else
955 const clockid_t clk_id = CLOCK_MONOTONIC;
956 const char *function = "clock_gettime(CLOCK_MONOTONIC)";
957#endif
Victor Stinner8b302012012-02-07 23:29:46 +0100958
Victor Stinnerec895392012-04-29 02:41:27 +0200959 if (clock_gettime(clk_id, &tp) != 0) {
Victor Stinner071eca32012-03-15 01:17:09 +0100960 PyErr_SetFromErrno(PyExc_OSError);
961 return NULL;
962 }
Victor Stinnerec895392012-04-29 02:41:27 +0200963
964 if (info) {
965 struct timespec res;
Benjamin Peterson49a69e42012-05-01 09:38:34 -0400966 info->monotonic = 1;
Victor Stinnerec895392012-04-29 02:41:27 +0200967 info->implementation = function;
Victor Stinner2b89fdf2012-06-12 22:46:37 +0200968 info->adjustable = 0;
Victor Stinnerec895392012-04-29 02:41:27 +0200969 if (clock_getres(clk_id, &res) == 0)
970 info->resolution = res.tv_sec + res.tv_nsec * 1e-9;
971 else
972 info->resolution = 1e-9;
Victor Stinner071eca32012-03-15 01:17:09 +0100973 }
Victor Stinnerec895392012-04-29 02:41:27 +0200974 return PyFloat_FromDouble(tp.tv_sec + tp.tv_nsec * 1e-9);
Victor Stinner8b302012012-02-07 23:29:46 +0100975#endif
976}
977
Victor Stinner071eca32012-03-15 01:17:09 +0100978static PyObject *
Victor Stinnerec895392012-04-29 02:41:27 +0200979time_monotonic(PyObject *self, PyObject *unused)
Victor Stinner071eca32012-03-15 01:17:09 +0100980{
Victor Stinnerec895392012-04-29 02:41:27 +0200981 return pymonotonic(NULL);
Victor Stinner071eca32012-03-15 01:17:09 +0100982}
983
Victor Stinnerec895392012-04-29 02:41:27 +0200984PyDoc_STRVAR(monotonic_doc,
985"monotonic() -> float\n\
Victor Stinner8b302012012-02-07 23:29:46 +0100986\n\
Victor Stinnerec895392012-04-29 02:41:27 +0200987Monotonic clock, cannot go backward.");
988#endif /* PYMONOTONIC */
Victor Stinnerec919cc2012-03-15 00:58:32 +0100989
Victor Stinnerec895392012-04-29 02:41:27 +0200990static PyObject*
991perf_counter(_Py_clock_info_t *info)
992{
993#if defined(WIN32_PERF_COUNTER) || defined(PYMONOTONIC)
994 PyObject *res;
995#endif
996#if defined(WIN32_PERF_COUNTER)
997 static int use_perf_counter = 1;
998#endif
999#ifdef PYMONOTONIC
1000 static int use_monotonic = 1;
1001#endif
1002
1003#ifdef WIN32_PERF_COUNTER
1004 if (use_perf_counter) {
1005 if (win_perf_counter(info, &res) == 0)
1006 return res;
1007 use_perf_counter = 0;
1008 }
1009#endif
1010
1011#ifdef PYMONOTONIC
1012 if (use_monotonic) {
1013 res = pymonotonic(info);
1014 if (res != NULL)
1015 return res;
1016 use_monotonic = 0;
1017 PyErr_Clear();
1018 }
1019#endif
1020
1021 return floattime(info);
1022}
1023
1024static PyObject *
1025time_perf_counter(PyObject *self, PyObject *unused)
1026{
1027 return perf_counter(NULL);
1028}
1029
1030PyDoc_STRVAR(perf_counter_doc,
1031"perf_counter() -> float\n\
1032\n\
1033Performance counter for benchmarking.");
1034
1035static PyObject*
1036py_process_time(_Py_clock_info_t *info)
1037{
1038#if defined(MS_WINDOWS)
1039 HANDLE process;
1040 FILETIME creation_time, exit_time, kernel_time, user_time;
1041 ULARGE_INTEGER large;
1042 double total;
1043 BOOL ok;
1044
1045 process = GetCurrentProcess();
1046 ok = GetProcessTimes(process, &creation_time, &exit_time, &kernel_time, &user_time);
1047 if (!ok)
1048 return PyErr_SetFromWindowsErr(0);
1049
1050 large.u.LowPart = kernel_time.dwLowDateTime;
1051 large.u.HighPart = kernel_time.dwHighDateTime;
1052 total = (double)large.QuadPart;
1053 large.u.LowPart = user_time.dwLowDateTime;
1054 large.u.HighPart = user_time.dwHighDateTime;
1055 total += (double)large.QuadPart;
1056 if (info) {
1057 info->implementation = "GetProcessTimes()";
1058 info->resolution = 1e-7;
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001059 info->monotonic = 1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001060 info->adjustable = 0;
Victor Stinnerec895392012-04-29 02:41:27 +02001061 }
1062 return PyFloat_FromDouble(total * 1e-7);
1063#else
1064
1065#if defined(HAVE_SYS_RESOURCE_H)
1066 struct rusage ru;
1067#endif
1068#ifdef HAVE_TIMES
1069 struct tms t;
1070 static long ticks_per_second = -1;
1071#endif
1072
1073#if defined(HAVE_CLOCK_GETTIME) \
1074 && (defined(CLOCK_PROCESS_CPUTIME_ID) || defined(CLOCK_PROF))
1075 struct timespec tp;
1076#ifdef CLOCK_PROF
1077 const clockid_t clk_id = CLOCK_PROF;
1078 const char *function = "clock_gettime(CLOCK_PROF)";
1079#else
1080 const clockid_t clk_id = CLOCK_PROCESS_CPUTIME_ID;
1081 const char *function = "clock_gettime(CLOCK_PROCESS_CPUTIME_ID)";
1082#endif
1083
1084 if (clock_gettime(clk_id, &tp) == 0) {
1085 if (info) {
1086 struct timespec res;
1087 info->implementation = function;
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001088 info->monotonic = 1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001089 info->adjustable = 0;
Victor Stinnerec895392012-04-29 02:41:27 +02001090 if (clock_getres(clk_id, &res) == 0)
1091 info->resolution = res.tv_sec + res.tv_nsec * 1e-9;
1092 else
1093 info->resolution = 1e-9;
1094 }
1095 return PyFloat_FromDouble(tp.tv_sec + tp.tv_nsec * 1e-9);
1096 }
1097#endif
1098
1099#if defined(HAVE_SYS_RESOURCE_H)
1100 if (getrusage(RUSAGE_SELF, &ru) == 0) {
1101 double total;
1102 total = ru.ru_utime.tv_sec + ru.ru_utime.tv_usec * 1e-6;
1103 total += ru.ru_stime.tv_sec + ru.ru_stime.tv_usec * 1e-6;
1104 if (info) {
1105 info->implementation = "getrusage(RUSAGE_SELF)";
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001106 info->monotonic = 1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001107 info->adjustable = 0;
Victor Stinnerec895392012-04-29 02:41:27 +02001108 info->resolution = 1e-6;
1109 }
1110 return PyFloat_FromDouble(total);
1111 }
1112#endif
1113
1114#ifdef HAVE_TIMES
1115 if (times(&t) != (clock_t)-1) {
1116 double total;
1117
1118 if (ticks_per_second == -1) {
1119#if defined(HAVE_SYSCONF) && defined(_SC_CLK_TCK)
1120 ticks_per_second = sysconf(_SC_CLK_TCK);
1121 if (ticks_per_second < 1)
1122 ticks_per_second = -1;
1123#elif defined(HZ)
1124 ticks_per_second = HZ;
1125#else
1126 ticks_per_second = 60; /* magic fallback value; may be bogus */
1127#endif
1128 }
1129
1130 if (ticks_per_second != -1) {
1131 total = (double)t.tms_utime / ticks_per_second;
1132 total += (double)t.tms_stime / ticks_per_second;
1133 if (info) {
1134 info->implementation = "times()";
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001135 info->monotonic = 1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001136 info->adjustable = 0;
Victor Stinnerec895392012-04-29 02:41:27 +02001137 info->resolution = 1.0 / ticks_per_second;
1138 }
1139 return PyFloat_FromDouble(total);
1140 }
1141 }
1142#endif
1143
1144 return floatclock(info);
1145#endif
1146}
1147
1148static PyObject *
1149time_process_time(PyObject *self, PyObject *unused)
1150{
1151 return py_process_time(NULL);
1152}
1153
1154PyDoc_STRVAR(process_time_doc,
1155"process_time() -> float\n\
1156\n\
1157Process time for profiling: sum of the kernel and user-space CPU time.");
1158
1159
Victor Stinnerec895392012-04-29 02:41:27 +02001160static PyObject *
1161time_get_clock_info(PyObject *self, PyObject *args)
1162{
1163 char *name;
Victor Stinnerec895392012-04-29 02:41:27 +02001164 _Py_clock_info_t info;
Victor Stinnerbda4b882012-06-12 22:11:44 +02001165 PyObject *obj = NULL, *dict, *ns;
Victor Stinnerec895392012-04-29 02:41:27 +02001166
1167 if (!PyArg_ParseTuple(args, "s:get_clock_info", &name))
1168 return NULL;
1169
1170#ifdef Py_DEBUG
1171 info.implementation = NULL;
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001172 info.monotonic = -1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001173 info.adjustable = -1;
Victor Stinnerec895392012-04-29 02:41:27 +02001174 info.resolution = -1.0;
1175#else
1176 info.implementation = "";
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001177 info.monotonic = 0;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001178 info.adjustable = 0;
Victor Stinnerec895392012-04-29 02:41:27 +02001179 info.resolution = 1.0;
1180#endif
1181
1182 if (strcmp(name, "time") == 0)
1183 obj = floattime(&info);
1184#ifdef PYCLOCK
1185 else if (strcmp(name, "clock") == 0)
1186 obj = pyclock(&info);
1187#endif
1188#ifdef PYMONOTONIC
1189 else if (strcmp(name, "monotonic") == 0)
1190 obj = pymonotonic(&info);
1191#endif
1192 else if (strcmp(name, "perf_counter") == 0)
1193 obj = perf_counter(&info);
1194 else if (strcmp(name, "process_time") == 0)
1195 obj = py_process_time(&info);
1196 else {
1197 PyErr_SetString(PyExc_ValueError, "unknown clock");
1198 return NULL;
1199 }
1200 if (obj == NULL)
1201 return NULL;
1202 Py_DECREF(obj);
1203
Victor Stinnerbda4b882012-06-12 22:11:44 +02001204 dict = PyDict_New();
1205 if (dict == NULL)
Victor Stinnerec895392012-04-29 02:41:27 +02001206 return NULL;
1207
1208 assert(info.implementation != NULL);
1209 obj = PyUnicode_FromString(info.implementation);
1210 if (obj == NULL)
1211 goto error;
Victor Stinnerbda4b882012-06-12 22:11:44 +02001212 if (PyDict_SetItemString(dict, "implementation", obj) == -1)
1213 goto error;
1214 Py_CLEAR(obj);
Victor Stinnerec895392012-04-29 02:41:27 +02001215
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001216 assert(info.monotonic != -1);
1217 obj = PyBool_FromLong(info.monotonic);
Victor Stinnerec895392012-04-29 02:41:27 +02001218 if (obj == NULL)
1219 goto error;
Victor Stinnerbda4b882012-06-12 22:11:44 +02001220 if (PyDict_SetItemString(dict, "monotonic", obj) == -1)
1221 goto error;
1222 Py_CLEAR(obj);
Victor Stinnerec895392012-04-29 02:41:27 +02001223
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001224 assert(info.adjustable != -1);
1225 obj = PyBool_FromLong(info.adjustable);
Victor Stinnerec895392012-04-29 02:41:27 +02001226 if (obj == NULL)
1227 goto error;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001228 if (PyDict_SetItemString(dict, "adjustable", obj) == -1)
Victor Stinnerbda4b882012-06-12 22:11:44 +02001229 goto error;
1230 Py_CLEAR(obj);
Victor Stinnerec895392012-04-29 02:41:27 +02001231
1232 assert(info.resolution > 0.0);
1233 assert(info.resolution <= 1.0);
1234 obj = PyFloat_FromDouble(info.resolution);
1235 if (obj == NULL)
1236 goto error;
Victor Stinnerbda4b882012-06-12 22:11:44 +02001237 if (PyDict_SetItemString(dict, "resolution", obj) == -1)
1238 goto error;
1239 Py_CLEAR(obj);
Victor Stinnerec895392012-04-29 02:41:27 +02001240
Victor Stinnerbda4b882012-06-12 22:11:44 +02001241 ns = _PyNamespace_New(dict);
1242 Py_DECREF(dict);
1243 return ns;
Victor Stinnerec895392012-04-29 02:41:27 +02001244
1245error:
Victor Stinnerbda4b882012-06-12 22:11:44 +02001246 Py_DECREF(dict);
1247 Py_XDECREF(obj);
Victor Stinnerec895392012-04-29 02:41:27 +02001248 return NULL;
1249}
1250
1251PyDoc_STRVAR(get_clock_info_doc,
1252"get_clock_info(name: str) -> dict\n\
1253\n\
1254Get information of the specified clock.");
Victor Stinner8b302012012-02-07 23:29:46 +01001255
Martin v. Löwisd218dc12008-04-07 03:17:54 +00001256static void
Martin v. Löwis1a214512008-06-11 05:26:20 +00001257PyInit_timezone(PyObject *m) {
1258 /* This code moved from PyInit_time wholesale to allow calling it from
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001259 time_tzset. In the future, some parts of it can be moved back
1260 (for platforms that don't HAVE_WORKING_TZSET, when we know what they
1261 are), and the extraneous calls to tzset(3) should be removed.
1262 I haven't done this yet, as I don't want to change this code as
1263 little as possible when introducing the time.tzset and time.tzsetwall
1264 methods. This should simply be a method of doing the following once,
1265 at the top of this function and removing the call to tzset() from
1266 time_tzset():
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001267
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001268 #ifdef HAVE_TZSET
1269 tzset()
1270 #endif
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001271
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001272 And I'm lazy and hate C so nyer.
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001273 */
Guido van Rossum10b164a2001-09-25 13:59:01 +00001274#if defined(HAVE_TZNAME) && !defined(__GLIBC__) && !defined(__CYGWIN__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001275 PyObject *otz0, *otz1;
1276 tzset();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001277 PyModule_AddIntConstant(m, "timezone", timezone);
Guido van Rossumb6775db1994-08-01 11:34:53 +00001278#ifdef HAVE_ALTZONE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001279 PyModule_AddIntConstant(m, "altzone", altzone);
Guido van Rossumb6775db1994-08-01 11:34:53 +00001280#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001281 PyModule_AddIntConstant(m, "altzone", timezone-3600);
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);
Martin v. Löwisb26a9b12013-01-25 14:25:48 +01001577 rc = WaitForSingleObjectEx(hInterruptEvent, ul_millis, FALSE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001578 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#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001588 /* XXX Can't interrupt this sleep */
1589 Py_BEGIN_ALLOW_THREADS
1590 sleep((int)secs);
1591 Py_END_ALLOW_THREADS
Martin v. Löwis02af9642002-01-16 11:04:06 +00001592#endif
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001593
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001594 return 0;
Guido van Rossum80c9d881991-04-16 08:47:51 +00001595}