blob: 34e057d9d74fd08c673cb77f68f084981a5a1ae0 [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
pdoxe14679c2017-10-05 00:01:56 -070023#if defined(HAVE_PTHREAD_H)
24# include <pthread.h>
25#endif
26
Guido van Rossum7bf22de1997-12-02 20:34:19 +000027#if defined(__WATCOMC__) && !defined(__QNX__)
Guido van Rossumbceeac81996-05-23 22:53:47 +000028#include <i86.h>
29#else
Guido van Rossumcac6c721996-09-06 13:34:02 +000030#ifdef MS_WINDOWS
Mark Hammond975e3922002-07-16 01:29:19 +000031#define WIN32_LEAN_AND_MEAN
Guido van Rossum258ccd42001-03-02 06:53:29 +000032#include <windows.h>
Mark Hammond975e3922002-07-16 01:29:19 +000033#include "pythread.h"
Guido van Rossumcac6c721996-09-06 13:34:02 +000034#endif /* MS_WINDOWS */
Guido van Rossum7bf22de1997-12-02 20:34:19 +000035#endif /* !__WATCOMC__ || __QNX__ */
Guido van Rossum234f9421993-06-17 12:35:49 +000036
37/* Forward declarations */
Victor Stinnercb29f012015-03-27 13:31:18 +010038static int pysleep(_PyTime_t);
Victor Stinnerec895392012-04-29 02:41:27 +020039static PyObject* floattime(_Py_clock_info_t *info);
40
Barry Warsaw9a2a8a81996-12-06 23:32:14 +000041static PyObject *
Victor Stinner4195b5c2012-02-08 23:03:19 +010042time_time(PyObject *self, PyObject *unused)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000043{
Victor Stinnerec895392012-04-29 02:41:27 +020044 return floattime(NULL);
Guido van Rossumb6775db1994-08-01 11:34:53 +000045}
46
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000047PyDoc_STRVAR(time_doc,
Victor Stinner4195b5c2012-02-08 23:03:19 +010048"time() -> floating point number\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +000049\n\
50Return the current time in seconds since the Epoch.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000051Fractions of a second may be present if the system clock provides them.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +000052
Victor Stinner85fdfa82012-01-27 00:38:48 +010053#if defined(HAVE_CLOCK)
54
55#ifndef CLOCKS_PER_SEC
56#ifdef CLK_TCK
57#define CLOCKS_PER_SEC CLK_TCK
58#else
59#define CLOCKS_PER_SEC 1000000
60#endif
61#endif
62
Victor Stinner4195b5c2012-02-08 23:03:19 +010063static PyObject *
Victor Stinnerec895392012-04-29 02:41:27 +020064floatclock(_Py_clock_info_t *info)
Victor Stinner85fdfa82012-01-27 00:38:48 +010065{
Victor Stinner4195b5c2012-02-08 23:03:19 +010066 clock_t value;
67 value = clock();
68 if (value == (clock_t)-1) {
Victor Stinner85fdfa82012-01-27 00:38:48 +010069 PyErr_SetString(PyExc_RuntimeError,
70 "the processor time used is not available "
71 "or its value cannot be represented");
Victor Stinner4195b5c2012-02-08 23:03:19 +010072 return NULL;
Victor Stinner85fdfa82012-01-27 00:38:48 +010073 }
Victor Stinnerec895392012-04-29 02:41:27 +020074 if (info) {
75 info->implementation = "clock()";
76 info->resolution = 1.0 / (double)CLOCKS_PER_SEC;
Benjamin Peterson49a69e42012-05-01 09:38:34 -040077 info->monotonic = 1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +020078 info->adjustable = 0;
Victor Stinnerec895392012-04-29 02:41:27 +020079 }
Victor Stinner4195b5c2012-02-08 23:03:19 +010080 return PyFloat_FromDouble((double)value / CLOCKS_PER_SEC);
Victor Stinner85fdfa82012-01-27 00:38:48 +010081}
82#endif /* HAVE_CLOCK */
83
Victor Stinnerf427a142014-10-22 12:33:23 +020084#ifdef MS_WINDOWS
Victor Stinnerec895392012-04-29 02:41:27 +020085#define WIN32_PERF_COUNTER
Victor Stinner9122fdd2011-07-04 13:55:40 +020086/* Win32 has better clock replacement; we have our own version, due to Mark
87 Hammond and Tim Peters */
Victor Stinner54884492014-08-29 16:51:33 +020088static PyObject*
89win_perf_counter(_Py_clock_info_t *info)
Guido van Rossum3917c221997-04-02 05:35:28 +000090{
Victor Stinner8b302012012-02-07 23:29:46 +010091 static LONGLONG cpu_frequency = 0;
Victor Stinner4195b5c2012-02-08 23:03:19 +010092 static LONGLONG ctrStart;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000093 LARGE_INTEGER now;
Victor Stinner4195b5c2012-02-08 23:03:19 +010094 double diff;
Guido van Rossum3917c221997-04-02 05:35:28 +000095
Victor Stinner8b302012012-02-07 23:29:46 +010096 if (cpu_frequency == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000097 LARGE_INTEGER freq;
Victor Stinner8b302012012-02-07 23:29:46 +010098 QueryPerformanceCounter(&now);
Victor Stinner4195b5c2012-02-08 23:03:19 +010099 ctrStart = now.QuadPart;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000100 if (!QueryPerformanceFrequency(&freq) || freq.QuadPart == 0) {
Victor Stinner54884492014-08-29 16:51:33 +0200101 PyErr_SetFromWindowsErr(0);
102 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000103 }
Victor Stinner8b302012012-02-07 23:29:46 +0100104 cpu_frequency = freq.QuadPart;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000105 }
106 QueryPerformanceCounter(&now);
Victor Stinner4195b5c2012-02-08 23:03:19 +0100107 diff = (double)(now.QuadPart - ctrStart);
Victor Stinnerec895392012-04-29 02:41:27 +0200108 if (info) {
109 info->implementation = "QueryPerformanceCounter()";
110 info->resolution = 1.0 / (double)cpu_frequency;
Benjamin Peterson49a69e42012-05-01 09:38:34 -0400111 info->monotonic = 1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +0200112 info->adjustable = 0;
Victor Stinnerec895392012-04-29 02:41:27 +0200113 }
Victor Stinner54884492014-08-29 16:51:33 +0200114 return PyFloat_FromDouble(diff / (double)cpu_frequency);
Guido van Rossum3917c221997-04-02 05:35:28 +0000115}
Victor Stinnerf427a142014-10-22 12:33:23 +0200116#endif /* MS_WINDOWS */
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000117
Victor Stinnerec895392012-04-29 02:41:27 +0200118#if defined(WIN32_PERF_COUNTER) || defined(HAVE_CLOCK)
119#define PYCLOCK
120static PyObject*
121pyclock(_Py_clock_info_t *info)
122{
123#ifdef WIN32_PERF_COUNTER
Victor Stinner54884492014-08-29 16:51:33 +0200124 return win_perf_counter(info);
125#else
Victor Stinnerec895392012-04-29 02:41:27 +0200126 return floatclock(info);
Victor Stinner54884492014-08-29 16:51:33 +0200127#endif
Victor Stinnerec895392012-04-29 02:41:27 +0200128}
129
Victor Stinner9122fdd2011-07-04 13:55:40 +0200130static PyObject *
Victor Stinner4195b5c2012-02-08 23:03:19 +0100131time_clock(PyObject *self, PyObject *unused)
Victor Stinner9122fdd2011-07-04 13:55:40 +0200132{
Victor Stinnerec895392012-04-29 02:41:27 +0200133 return pyclock(NULL);
Victor Stinner9122fdd2011-07-04 13:55:40 +0200134}
Victor Stinner9122fdd2011-07-04 13:55:40 +0200135
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000136PyDoc_STRVAR(clock_doc,
Victor Stinner4195b5c2012-02-08 23:03:19 +0100137"clock() -> floating point number\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000138\n\
139Return the CPU time or real time since the start of the process or since\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000140the first call to clock(). This has as much precision as the system\n\
141records.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000142#endif
143
Victor Stinnere0be4232011-10-25 13:06:09 +0200144#ifdef HAVE_CLOCK_GETTIME
145static PyObject *
Victor Stinner4195b5c2012-02-08 23:03:19 +0100146time_clock_gettime(PyObject *self, PyObject *args)
Victor Stinnere0be4232011-10-25 13:06:09 +0200147{
148 int ret;
Victor Stinnerb8d01692012-04-13 23:44:05 +0200149 int clk_id;
Victor Stinnere0be4232011-10-25 13:06:09 +0200150 struct timespec tp;
151
Victor Stinner4195b5c2012-02-08 23:03:19 +0100152 if (!PyArg_ParseTuple(args, "i:clock_gettime", &clk_id))
Victor Stinnere0be4232011-10-25 13:06:09 +0200153 return NULL;
154
155 ret = clock_gettime((clockid_t)clk_id, &tp);
Antoine Pitrou2c085602012-01-18 01:41:44 +0100156 if (ret != 0) {
Victor Stinnera734af32014-07-31 13:07:17 +0200157 PyErr_SetFromErrno(PyExc_OSError);
Antoine Pitrou2c085602012-01-18 01:41:44 +0100158 return NULL;
159 }
Victor Stinner4195b5c2012-02-08 23:03:19 +0100160 return PyFloat_FromDouble(tp.tv_sec + tp.tv_nsec * 1e-9);
Victor Stinnere0be4232011-10-25 13:06:09 +0200161}
162
163PyDoc_STRVAR(clock_gettime_doc,
Victor Stinner4195b5c2012-02-08 23:03:19 +0100164"clock_gettime(clk_id) -> floating point number\n\
Victor Stinnere0be4232011-10-25 13:06:09 +0200165\n\
166Return the time of the specified clock clk_id.");
Benjamin Peterson37098cd2016-09-13 22:55:09 -0700167#endif /* HAVE_CLOCK_GETTIME */
Victor Stinner30d79472012-04-03 00:45:07 +0200168
Benjamin Peterson37098cd2016-09-13 22:55:09 -0700169#ifdef HAVE_CLOCK_SETTIME
Victor Stinner30d79472012-04-03 00:45:07 +0200170static PyObject *
171time_clock_settime(PyObject *self, PyObject *args)
172{
Victor Stinnerb8d01692012-04-13 23:44:05 +0200173 int clk_id;
Victor Stinner30d79472012-04-03 00:45:07 +0200174 PyObject *obj;
Victor Stinnerb3b45442015-03-28 04:09:41 +0100175 _PyTime_t t;
Victor Stinner30d79472012-04-03 00:45:07 +0200176 struct timespec tp;
177 int ret;
178
179 if (!PyArg_ParseTuple(args, "iO:clock_settime", &clk_id, &obj))
180 return NULL;
181
Victor Stinner02937aa2015-03-28 05:02:39 +0100182 if (_PyTime_FromSecondsObject(&t, obj, _PyTime_ROUND_FLOOR) < 0)
Victor Stinner30d79472012-04-03 00:45:07 +0200183 return NULL;
Victor Stinnerb3b45442015-03-28 04:09:41 +0100184
185 if (_PyTime_AsTimespec(t, &tp) == -1)
186 return NULL;
Victor Stinner30d79472012-04-03 00:45:07 +0200187
188 ret = clock_settime((clockid_t)clk_id, &tp);
189 if (ret != 0) {
Victor Stinnera734af32014-07-31 13:07:17 +0200190 PyErr_SetFromErrno(PyExc_OSError);
Victor Stinner30d79472012-04-03 00:45:07 +0200191 return NULL;
192 }
193 Py_RETURN_NONE;
194}
195
196PyDoc_STRVAR(clock_settime_doc,
197"clock_settime(clk_id, time)\n\
198\n\
199Set the time of the specified clock clk_id.");
Benjamin Peterson37098cd2016-09-13 22:55:09 -0700200#endif /* HAVE_CLOCK_SETTIME */
Victor Stinnere0be4232011-10-25 13:06:09 +0200201
Benjamin Peterson37098cd2016-09-13 22:55:09 -0700202#ifdef HAVE_CLOCK_GETRES
Victor Stinnere0be4232011-10-25 13:06:09 +0200203static PyObject *
Victor Stinner4195b5c2012-02-08 23:03:19 +0100204time_clock_getres(PyObject *self, PyObject *args)
Victor Stinnere0be4232011-10-25 13:06:09 +0200205{
206 int ret;
Victor Stinnerb8d01692012-04-13 23:44:05 +0200207 int clk_id;
Victor Stinnere0be4232011-10-25 13:06:09 +0200208 struct timespec tp;
209
Victor Stinner4195b5c2012-02-08 23:03:19 +0100210 if (!PyArg_ParseTuple(args, "i:clock_getres", &clk_id))
Victor Stinnere0be4232011-10-25 13:06:09 +0200211 return NULL;
212
213 ret = clock_getres((clockid_t)clk_id, &tp);
Antoine Pitrou2c085602012-01-18 01:41:44 +0100214 if (ret != 0) {
Victor Stinnera734af32014-07-31 13:07:17 +0200215 PyErr_SetFromErrno(PyExc_OSError);
Antoine Pitrou2c085602012-01-18 01:41:44 +0100216 return NULL;
217 }
Victor Stinner4195b5c2012-02-08 23:03:19 +0100218
219 return PyFloat_FromDouble(tp.tv_sec + tp.tv_nsec * 1e-9);
Victor Stinnere0be4232011-10-25 13:06:09 +0200220}
221
222PyDoc_STRVAR(clock_getres_doc,
Victor Stinner4195b5c2012-02-08 23:03:19 +0100223"clock_getres(clk_id) -> floating point number\n\
Victor Stinnere0be4232011-10-25 13:06:09 +0200224\n\
225Return the resolution (precision) of the specified clock clk_id.");
Benjamin Peterson37098cd2016-09-13 22:55:09 -0700226#endif /* HAVE_CLOCK_GETRES */
Victor Stinnere0be4232011-10-25 13:06:09 +0200227
pdoxe14679c2017-10-05 00:01:56 -0700228#ifdef HAVE_PTHREAD_GETCPUCLOCKID
229static PyObject *
230time_pthread_getcpuclockid(PyObject *self, PyObject *args)
231{
232 unsigned long thread_id;
233 int err;
234 clockid_t clk_id;
235 if (!PyArg_ParseTuple(args, "k:pthread_getcpuclockid", &thread_id)) {
236 return NULL;
237 }
238 err = pthread_getcpuclockid((pthread_t)thread_id, &clk_id);
239 if (err) {
240 errno = err;
241 PyErr_SetFromErrno(PyExc_OSError);
242 return NULL;
243 }
244 return PyLong_FromLong(clk_id);
245}
246
247PyDoc_STRVAR(pthread_getcpuclockid_doc,
248"pthread_getcpuclockid(thread_id) -> int\n\
249\n\
250Return the clk_id of a thread's CPU time clock.");
251#endif /* HAVE_PTHREAD_GETCPUCLOCKID */
252
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000253static PyObject *
Victor Stinnercb29f012015-03-27 13:31:18 +0100254time_sleep(PyObject *self, PyObject *obj)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000255{
Victor Stinnercb29f012015-03-27 13:31:18 +0100256 _PyTime_t secs;
Victor Stinner869e1772015-03-30 03:49:14 +0200257 if (_PyTime_FromSecondsObject(&secs, obj, _PyTime_ROUND_CEILING))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000258 return NULL;
Victor Stinner7f53a502011-07-05 22:00:25 +0200259 if (secs < 0) {
260 PyErr_SetString(PyExc_ValueError,
261 "sleep length must be non-negative");
262 return NULL;
263 }
Victor Stinnercb29f012015-03-27 13:31:18 +0100264 if (pysleep(secs) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000265 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200266 Py_RETURN_NONE;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000267}
268
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000269PyDoc_STRVAR(sleep_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000270"sleep(seconds)\n\
271\n\
272Delay execution for a given number of seconds. The argument may be\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000273a floating point number for subsecond precision.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000274
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000275static PyStructSequence_Field struct_time_type_fields[] = {
Alexander Belopolsky69f3fd02010-06-05 15:04:51 +0000276 {"tm_year", "year, for example, 1993"},
277 {"tm_mon", "month of year, range [1, 12]"},
278 {"tm_mday", "day of month, range [1, 31]"},
279 {"tm_hour", "hours, range [0, 23]"},
280 {"tm_min", "minutes, range [0, 59]"},
281 {"tm_sec", "seconds, range [0, 61])"},
282 {"tm_wday", "day of week, range [0, 6], Monday is 0"},
283 {"tm_yday", "day of year, range [1, 366]"},
284 {"tm_isdst", "1 if summer time is in effect, 0 if not, and -1 if unknown"},
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400285 {"tm_zone", "abbreviation of timezone name"},
286 {"tm_gmtoff", "offset from UTC in seconds"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000287 {0}
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000288};
289
290static PyStructSequence_Desc struct_time_type_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000291 "time.struct_time",
Alexander Belopolsky69f3fd02010-06-05 15:04:51 +0000292 "The time value as returned by gmtime(), localtime(), and strptime(), and\n"
293 " accepted by asctime(), mktime() and strftime(). May be considered as a\n"
294 " sequence of 9 integers.\n\n"
295 " Note that several fields' values are not the same as those defined by\n"
296 " the C language standard for struct tm. For example, the value of the\n"
297 " field tm_year is the actual year, not year - 1900. See individual\n"
298 " fields' descriptions for details.",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000299 struct_time_type_fields,
300 9,
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000301};
Tim Peters9ad4b682002-02-13 05:14:18 +0000302
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000303static int initialized;
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000304static PyTypeObject StructTimeType;
305
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400306
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000307static PyObject *
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -0400308tmtotuple(struct tm *p
309#ifndef HAVE_STRUCT_TM_TM_ZONE
Victor Stinner0d659e52017-04-25 01:22:42 +0200310 , const char *zone, time_t gmtoff
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -0400311#endif
312)
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000313{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000314 PyObject *v = PyStructSequence_New(&StructTimeType);
315 if (v == NULL)
316 return NULL;
Tim Peters9ad4b682002-02-13 05:14:18 +0000317
Christian Heimes217cfd12007-12-02 14:31:20 +0000318#define SET(i,val) PyStructSequence_SET_ITEM(v, i, PyLong_FromLong((long) val))
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000319
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000320 SET(0, p->tm_year + 1900);
321 SET(1, p->tm_mon + 1); /* Want January == 1 */
322 SET(2, p->tm_mday);
323 SET(3, p->tm_hour);
324 SET(4, p->tm_min);
325 SET(5, p->tm_sec);
326 SET(6, (p->tm_wday + 6) % 7); /* Want Monday == 0 */
327 SET(7, p->tm_yday + 1); /* Want January, 1 == 1 */
328 SET(8, p->tm_isdst);
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400329#ifdef HAVE_STRUCT_TM_TM_ZONE
330 PyStructSequence_SET_ITEM(v, 9,
331 PyUnicode_DecodeLocale(p->tm_zone, "surrogateescape"));
332 SET(10, p->tm_gmtoff);
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -0400333#else
334 PyStructSequence_SET_ITEM(v, 9,
335 PyUnicode_DecodeLocale(zone, "surrogateescape"));
Victor Stinner0d659e52017-04-25 01:22:42 +0200336 PyStructSequence_SET_ITEM(v, 10, _PyLong_FromTime_t(gmtoff));
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400337#endif /* HAVE_STRUCT_TM_TM_ZONE */
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000338#undef SET
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000339 if (PyErr_Occurred()) {
340 Py_XDECREF(v);
341 return NULL;
342 }
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000343
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000344 return v;
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000345}
346
Fred Drakef901abd2004-08-03 17:58:55 +0000347/* Parse arg tuple that can contain an optional float-or-None value;
348 format needs to be "|O:name".
349 Returns non-zero on success (parallels PyArg_ParseTuple).
350*/
351static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +0200352parse_time_t_args(PyObject *args, const char *format, time_t *pwhen)
Fred Drakef901abd2004-08-03 17:58:55 +0000353{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000354 PyObject *ot = NULL;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100355 time_t whent;
Fred Drakef901abd2004-08-03 17:58:55 +0000356
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000357 if (!PyArg_ParseTuple(args, format, &ot))
358 return 0;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100359 if (ot == NULL || ot == Py_None) {
360 whent = time(NULL);
361 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000362 else {
Victor Stinner02937aa2015-03-28 05:02:39 +0100363 if (_PyTime_ObjectToTime_t(ot, &whent, _PyTime_ROUND_FLOOR) == -1)
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100364 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000365 }
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100366 *pwhen = whent;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000367 return 1;
Fred Drakef901abd2004-08-03 17:58:55 +0000368}
369
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000370static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000371time_gmtime(PyObject *self, PyObject *args)
Guido van Rossum234f9421993-06-17 12:35:49 +0000372{
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100373 time_t when;
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -0400374 struct tm buf;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100375
376 if (!parse_time_t_args(args, "|O:gmtime", &when))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000377 return NULL;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100378
379 errno = 0;
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -0400380 if (_PyTime_gmtime(when, &buf) != 0)
381 return NULL;
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -0400382#ifdef HAVE_STRUCT_TM_TM_ZONE
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100383 return tmtotuple(&buf);
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -0400384#else
385 return tmtotuple(&buf, "UTC", 0);
386#endif
Guido van Rossum234f9421993-06-17 12:35:49 +0000387}
388
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -0400389#ifndef HAVE_TIMEGM
390static time_t
391timegm(struct tm *p)
392{
393 /* XXX: the following implementation will not work for tm_year < 1970.
394 but it is likely that platforms that don't have timegm do not support
395 negative timestamps anyways. */
396 return p->tm_sec + p->tm_min*60 + p->tm_hour*3600 + p->tm_yday*86400 +
397 (p->tm_year-70)*31536000 + ((p->tm_year-69)/4)*86400 -
398 ((p->tm_year-1)/100)*86400 + ((p->tm_year+299)/400)*86400;
399}
400#endif
401
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000402PyDoc_STRVAR(gmtime_doc,
Christian Heimes9a371592007-12-28 14:08:13 +0000403"gmtime([seconds]) -> (tm_year, tm_mon, tm_mday, tm_hour, tm_min,\n\
Fred Drake193a3f62002-03-12 21:38:49 +0000404 tm_sec, tm_wday, tm_yday, tm_isdst)\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000405\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000406Convert seconds since the Epoch to a time tuple expressing UTC (a.k.a.\n\
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400407GMT). When 'seconds' is not passed in, convert the current time instead.\n\
408\n\
409If the platform supports the tm_gmtoff and tm_zone, they are available as\n\
410attributes only.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000411
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000412static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000413time_localtime(PyObject *self, PyObject *args)
Guido van Rossum234f9421993-06-17 12:35:49 +0000414{
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100415 time_t when;
416 struct tm buf;
417
418 if (!parse_time_t_args(args, "|O:localtime", &when))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000419 return NULL;
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -0400420 if (_PyTime_localtime(when, &buf) != 0)
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100421 return NULL;
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -0400422#ifdef HAVE_STRUCT_TM_TM_ZONE
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100423 return tmtotuple(&buf);
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -0400424#else
425 {
426 struct tm local = buf;
427 char zone[100];
Victor Stinner0d659e52017-04-25 01:22:42 +0200428 time_t gmtoff;
Steve Dowerc3c6f712016-12-14 11:22:05 -0800429 strftime(zone, sizeof(zone), "%Z", &buf);
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -0400430 gmtoff = timegm(&buf) - when;
431 return tmtotuple(&local, zone, gmtoff);
432 }
433#endif
Guido van Rossum234f9421993-06-17 12:35:49 +0000434}
435
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000436PyDoc_STRVAR(localtime_doc,
Christian Heimes9a371592007-12-28 14:08:13 +0000437"localtime([seconds]) -> (tm_year,tm_mon,tm_mday,tm_hour,tm_min,\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000438 tm_sec,tm_wday,tm_yday,tm_isdst)\n\
Martin v. Löwisb3cfc1d2001-12-02 12:27:43 +0000439\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000440Convert seconds since the Epoch to a time tuple expressing local time.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000441When 'seconds' is not passed in, convert the current time instead.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000442
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000443/* Convert 9-item tuple to tm structure. Return 1 on success, set
444 * an exception and return 0 on error.
445 */
Guido van Rossum9e90a671993-06-24 11:10:19 +0000446static int
Oren Milman1d1d3e92017-08-20 18:35:36 +0300447gettmarg(PyObject *args, struct tm *p, const char *format)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000448{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000449 int y;
Guido van Rossumcfbaecc1998-08-25 14:51:12 +0000450
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000451 memset((void *) p, '\0', sizeof(struct tm));
Guido van Rossumb9081262007-08-25 03:14:09 +0000452
Alexander Belopolsky610e5442011-01-06 21:57:06 +0000453 if (!PyTuple_Check(args)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000454 PyErr_SetString(PyExc_TypeError,
455 "Tuple or struct_time argument required");
456 return 0;
457 }
Skip Montanaro41cfce92007-08-24 21:11:00 +0000458
Oren Milman1d1d3e92017-08-20 18:35:36 +0300459 if (!PyArg_ParseTuple(args, format,
Alexander Belopolsky610e5442011-01-06 21:57:06 +0000460 &y, &p->tm_mon, &p->tm_mday,
461 &p->tm_hour, &p->tm_min, &p->tm_sec,
462 &p->tm_wday, &p->tm_yday, &p->tm_isdst))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000463 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000464 p->tm_year = y - 1900;
465 p->tm_mon--;
466 p->tm_wday = (p->tm_wday + 1) % 7;
467 p->tm_yday--;
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400468#ifdef HAVE_STRUCT_TM_TM_ZONE
469 if (Py_TYPE(args) == &StructTimeType) {
470 PyObject *item;
471 item = PyTuple_GET_ITEM(args, 9);
Victor Stinner6e676952017-04-26 13:51:48 +0200472 p->tm_zone = item == Py_None ? NULL : (char*)PyUnicode_AsUTF8(item);
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400473 item = PyTuple_GET_ITEM(args, 10);
474 p->tm_gmtoff = item == Py_None ? 0 : PyLong_AsLong(item);
475 if (PyErr_Occurred())
476 return 0;
477 }
478#endif /* HAVE_STRUCT_TM_TM_ZONE */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000479 return 1;
Guido van Rossum9e90a671993-06-24 11:10:19 +0000480}
481
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000482/* Check values of the struct tm fields before it is passed to strftime() and
483 * asctime(). Return 1 if all values are valid, otherwise set an exception
484 * and returns 0.
485 */
Victor Stinneref128102010-10-07 01:00:52 +0000486static int
487checktm(struct tm* buf)
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000488{
Victor Stinneref128102010-10-07 01:00:52 +0000489 /* Checks added to make sure strftime() and asctime() does not crash Python by
490 indexing blindly into some array for a textual representation
491 by some bad index (fixes bug #897625 and #6608).
492
493 Also support values of zero from Python code for arguments in which
494 that is out of range by forcing that value to the lowest value that
495 is valid (fixed bug #1520914).
496
497 Valid ranges based on what is allowed in struct tm:
498
499 - tm_year: [0, max(int)] (1)
500 - tm_mon: [0, 11] (2)
501 - tm_mday: [1, 31]
502 - tm_hour: [0, 23]
503 - tm_min: [0, 59]
504 - tm_sec: [0, 60]
505 - tm_wday: [0, 6] (1)
506 - tm_yday: [0, 365] (2)
507 - tm_isdst: [-max(int), max(int)]
508
509 (1) gettmarg() handles bounds-checking.
510 (2) Python's acceptable range is one greater than the range in C,
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000511 thus need to check against automatic decrement by gettmarg().
512 */
513 if (buf->tm_mon == -1)
514 buf->tm_mon = 0;
515 else if (buf->tm_mon < 0 || buf->tm_mon > 11) {
516 PyErr_SetString(PyExc_ValueError, "month out of range");
517 return 0;
518 }
519 if (buf->tm_mday == 0)
520 buf->tm_mday = 1;
521 else if (buf->tm_mday < 0 || buf->tm_mday > 31) {
522 PyErr_SetString(PyExc_ValueError, "day of month out of range");
523 return 0;
524 }
525 if (buf->tm_hour < 0 || buf->tm_hour > 23) {
526 PyErr_SetString(PyExc_ValueError, "hour out of range");
527 return 0;
528 }
529 if (buf->tm_min < 0 || buf->tm_min > 59) {
530 PyErr_SetString(PyExc_ValueError, "minute out of range");
531 return 0;
532 }
533 if (buf->tm_sec < 0 || buf->tm_sec > 61) {
534 PyErr_SetString(PyExc_ValueError, "seconds out of range");
535 return 0;
536 }
537 /* tm_wday does not need checking of its upper-bound since taking
538 ``% 7`` in gettmarg() automatically restricts the range. */
539 if (buf->tm_wday < 0) {
540 PyErr_SetString(PyExc_ValueError, "day of week out of range");
541 return 0;
542 }
543 if (buf->tm_yday == -1)
544 buf->tm_yday = 0;
545 else if (buf->tm_yday < 0 || buf->tm_yday > 365) {
546 PyErr_SetString(PyExc_ValueError, "day of year out of range");
547 return 0;
548 }
549 return 1;
550}
551
Victor Stinnerc1f32ca2011-10-14 02:36:13 +0200552#ifdef MS_WINDOWS
553 /* wcsftime() doesn't format correctly time zones, see issue #10653 */
554# undef HAVE_WCSFTIME
555#endif
Alexander Belopolskycf774542012-10-02 18:39:16 -0400556#define STRFTIME_FORMAT_CODES \
557"Commonly used format codes:\n\
558\n\
559%Y Year with century as a decimal number.\n\
560%m Month as a decimal number [01,12].\n\
561%d Day of the month as a decimal number [01,31].\n\
562%H Hour (24-hour clock) as a decimal number [00,23].\n\
563%M Minute as a decimal number [00,59].\n\
564%S Second as a decimal number [00,61].\n\
565%z Time zone offset from UTC.\n\
566%a Locale's abbreviated weekday name.\n\
567%A Locale's full weekday name.\n\
568%b Locale's abbreviated month name.\n\
569%B Locale's full month name.\n\
570%c Locale's appropriate date and time representation.\n\
571%I Hour (12-hour clock) as a decimal number [01,12].\n\
572%p Locale's equivalent of either AM or PM.\n\
573\n\
574Other codes may be available on your platform. See documentation for\n\
575the C library strftime function.\n"
Victor Stinnerc1f32ca2011-10-14 02:36:13 +0200576
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000577#ifdef HAVE_STRFTIME
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000578#ifdef HAVE_WCSFTIME
579#define time_char wchar_t
580#define format_time wcsftime
581#define time_strlen wcslen
582#else
583#define time_char char
584#define format_time strftime
585#define time_strlen strlen
586#endif
587
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000588static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000589time_strftime(PyObject *self, PyObject *args)
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000590{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000591 PyObject *tup = NULL;
592 struct tm buf;
593 const time_char *fmt;
Victor Stinnerb2904782010-09-29 10:34:19 +0000594#ifdef HAVE_WCSFTIME
595 wchar_t *format;
596#else
597 PyObject *format;
598#endif
Victor Stinneref128102010-10-07 01:00:52 +0000599 PyObject *format_arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000600 size_t fmtlen, buflen;
Victor Stinnerb2904782010-09-29 10:34:19 +0000601 time_char *outbuf = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000602 size_t i;
Victor Stinnerb2904782010-09-29 10:34:19 +0000603 PyObject *ret = NULL;
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000604
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000605 memset((void *) &buf, '\0', sizeof(buf));
Guido van Rossum1f41f841998-04-27 19:04:26 +0000606
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000607 /* Will always expect a unicode string to be passed as format.
608 Given that there's no str type anymore in py3k this seems safe.
609 */
Victor Stinneref128102010-10-07 01:00:52 +0000610 if (!PyArg_ParseTuple(args, "U|O:strftime", &format_arg, &tup))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000611 return NULL;
Thomas Woutersfe385252001-01-19 23:16:56 +0000612
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000613 if (tup == NULL) {
614 time_t tt = time(NULL);
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -0400615 if (_PyTime_localtime(tt, &buf) != 0)
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100616 return NULL;
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000617 }
Oren Milman1d1d3e92017-08-20 18:35:36 +0300618 else if (!gettmarg(tup, &buf,
619 "iiiiiiiii;strftime(): illegal time tuple argument") ||
620 !checktm(&buf))
621 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000622 return NULL;
Oren Milman1d1d3e92017-08-20 18:35:36 +0300623 }
Guido van Rossum10b164a2001-09-25 13:59:01 +0000624
Victor Stinner36b82d82013-06-25 02:33:53 +0200625#if defined(_MSC_VER) || defined(sun) || defined(_AIX)
Victor Stinner73ea29c2011-01-08 01:56:31 +0000626 if (buf.tm_year + 1900 < 1 || 9999 < buf.tm_year + 1900) {
Victor Stinner6f0e4f92011-03-21 02:14:53 +0100627 PyErr_SetString(PyExc_ValueError,
628 "strftime() requires year in [1; 9999]");
Alexander Belopolsky0dd06f42011-01-08 01:23:02 +0000629 return NULL;
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000630 }
Victor Stinner73ea29c2011-01-08 01:56:31 +0000631#endif
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000632
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000633 /* Normalize tm_isdst just in case someone foolishly implements %Z
634 based on the assumption that tm_isdst falls within the range of
635 [-1, 1] */
636 if (buf.tm_isdst < -1)
637 buf.tm_isdst = -1;
638 else if (buf.tm_isdst > 1)
639 buf.tm_isdst = 1;
Brett Cannond1080a32004-03-02 04:38:10 +0000640
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000641#ifdef HAVE_WCSFTIME
Victor Stinnerbeb4135b2010-10-07 01:02:42 +0000642 format = PyUnicode_AsWideCharString(format_arg, NULL);
Victor Stinnerb2904782010-09-29 10:34:19 +0000643 if (format == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000644 return NULL;
Victor Stinnerb2904782010-09-29 10:34:19 +0000645 fmt = format;
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000646#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000647 /* Convert the unicode string to an ascii one */
Victor Stinner1b579672011-12-17 05:47:23 +0100648 format = PyUnicode_EncodeLocale(format_arg, "surrogateescape");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000649 if (format == NULL)
650 return NULL;
651 fmt = PyBytes_AS_STRING(format);
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000652#endif
Amaury Forgeot d'Arcb5be6d42009-03-02 23:52:57 +0000653
Stefan Krah4aea7d32012-02-27 16:30:26 +0100654#if defined(MS_WINDOWS) && !defined(HAVE_WCSFTIME)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000655 /* check that the format string contains only valid directives */
Steve Dowere5b58952015-09-06 19:20:51 -0700656 for (outbuf = strchr(fmt, '%');
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000657 outbuf != NULL;
Victor Stinner5a3ff792011-10-16 19:08:23 +0200658 outbuf = strchr(outbuf+2, '%'))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000659 {
Steve Dowere5b58952015-09-06 19:20:51 -0700660 if (outbuf[1] == '#')
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000661 ++outbuf; /* not documented by python, */
Steve Dowere5b58952015-09-06 19:20:51 -0700662 if (outbuf[1] == '\0')
663 break;
664 if ((outbuf[1] == 'y') && buf.tm_year < 0) {
Tim Golden6e51b8f2013-11-12 12:36:54 +0000665 PyErr_SetString(PyExc_ValueError,
666 "format %y requires year >= 1900 on Windows");
667 Py_DECREF(format);
668 return NULL;
669 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000670 }
Victor Stinner93965f72013-11-23 14:59:33 +0100671#elif (defined(_AIX) || defined(sun)) && defined(HAVE_WCSFTIME)
Steve Dowere5b58952015-09-06 19:20:51 -0700672 for (outbuf = wcschr(fmt, '%');
Victor Stinner55329f82013-11-17 23:39:21 +0100673 outbuf != NULL;
674 outbuf = wcschr(outbuf+2, '%'))
675 {
Steve Dowere5b58952015-09-06 19:20:51 -0700676 if (outbuf[1] == L'\0')
677 break;
Victor Stinner55329f82013-11-17 23:39:21 +0100678 /* Issue #19634: On AIX, wcsftime("y", (1899, 1, 1, 0, 0, 0, 0, 0, 0))
679 returns "0/" instead of "99" */
680 if (outbuf[1] == L'y' && buf.tm_year < 0) {
681 PyErr_SetString(PyExc_ValueError,
682 "format %y requires year >= 1900 on AIX");
Victor Stinner55329f82013-11-17 23:39:21 +0100683 return NULL;
684 }
685 }
Amaury Forgeot d'Arcb5be6d42009-03-02 23:52:57 +0000686#endif
687
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000688 fmtlen = time_strlen(fmt);
Guido van Rossumc222ec21999-02-23 00:00:10 +0000689
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000690 /* I hate these functions that presume you know how big the output
691 * will be ahead of time...
692 */
693 for (i = 1024; ; i += i) {
694 outbuf = (time_char *)PyMem_Malloc(i*sizeof(time_char));
695 if (outbuf == NULL) {
Victor Stinnerb2904782010-09-29 10:34:19 +0000696 PyErr_NoMemory();
697 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000698 }
Steve Dower57ab1cd2015-09-22 14:51:42 -0700699#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
700 errno = 0;
701#endif
Steve Dowerd9ef74e2015-05-22 15:08:34 -0700702 _Py_BEGIN_SUPPRESS_IPH
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000703 buflen = format_time(outbuf, i, fmt, &buf);
Steve Dowerd9ef74e2015-05-22 15:08:34 -0700704 _Py_END_SUPPRESS_IPH
Victor Stinner136ea492011-12-17 22:37:18 +0100705#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
Steve Dower97cded92015-09-08 19:12:51 -0700706 /* VisualStudio .NET 2005 does this properly */
707 if (buflen == 0 && errno == EINVAL) {
708 PyErr_SetString(PyExc_ValueError, "Invalid format string");
709 PyMem_Free(outbuf);
710 break;
711 }
Victor Stinner136ea492011-12-17 22:37:18 +0100712#endif
Steve Dower97cded92015-09-08 19:12:51 -0700713 if (buflen > 0 || i >= 256 * fmtlen) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000714 /* If the buffer is 256 times as long as the format,
715 it's probably not failing for lack of room!
716 More likely, the format yields an empty result,
717 e.g. an empty format, or %Z when the timezone
718 is unknown. */
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000719#ifdef HAVE_WCSFTIME
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000720 ret = PyUnicode_FromWideChar(outbuf, buflen);
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000721#else
Victor Stinner1b579672011-12-17 05:47:23 +0100722 ret = PyUnicode_DecodeLocaleAndSize(outbuf, buflen,
723 "surrogateescape");
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000724#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000725 PyMem_Free(outbuf);
Victor Stinnerb2904782010-09-29 10:34:19 +0000726 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000727 }
728 PyMem_Free(outbuf);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000729 }
Victor Stinnerb2904782010-09-29 10:34:19 +0000730#ifdef HAVE_WCSFTIME
731 PyMem_Free(format);
732#else
733 Py_DECREF(format);
734#endif
735 return ret;
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000736}
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000737
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000738#undef time_char
739#undef format_time
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000740PyDoc_STRVAR(strftime_doc,
Thomas Woutersfe385252001-01-19 23:16:56 +0000741"strftime(format[, tuple]) -> string\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000742\n\
743Convert a time tuple to a string according to a format specification.\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000744See the library reference manual for formatting codes. When the time tuple\n\
Alexander Belopolskycf774542012-10-02 18:39:16 -0400745is not present, current time as returned by localtime() is used.\n\
746\n" STRFTIME_FORMAT_CODES);
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000747#endif /* HAVE_STRFTIME */
748
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000749static PyObject *
750time_strptime(PyObject *self, PyObject *args)
751{
Victor Stinnerdbe28d22016-12-09 00:38:53 +0100752 PyObject *module, *func, *result;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200753 _Py_IDENTIFIER(_strptime_time);
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000754
Victor Stinnerdbe28d22016-12-09 00:38:53 +0100755 module = PyImport_ImportModuleNoBlock("_strptime");
756 if (!module)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000757 return NULL;
Victor Stinnerdbe28d22016-12-09 00:38:53 +0100758
759 func = _PyObject_GetAttrId(module, &PyId__strptime_time);
760 Py_DECREF(module);
761 if (!func) {
762 return NULL;
763 }
764
765 result = PyObject_Call(func, args, NULL);
766 Py_DECREF(func);
767 return result;
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000768}
769
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000770
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000771PyDoc_STRVAR(strptime_doc,
Brett Cannon20def8b2003-07-01 05:16:08 +0000772"strptime(string, format) -> struct_time\n\
Martin v. Löwisb3cfc1d2001-12-02 12:27:43 +0000773\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000774Parse a string to a time tuple according to a format specification.\n\
Alexander Belopolskycf774542012-10-02 18:39:16 -0400775See the library reference manual for formatting codes (same as\n\
776strftime()).\n\
777\n" STRFTIME_FORMAT_CODES);
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000778
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000779static PyObject *
780_asctime(struct tm *timeptr)
781{
782 /* Inspired by Open Group reference implementation available at
783 * http://pubs.opengroup.org/onlinepubs/009695399/functions/asctime.html */
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200784 static const char wday_name[7][4] = {
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000785 "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
786 };
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200787 static const char mon_name[12][4] = {
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000788 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
789 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
790 };
Victor Stinner499dfcf2011-03-21 13:26:24 +0100791 return PyUnicode_FromFormat(
792 "%s %s%3d %.2d:%.2d:%.2d %d",
793 wday_name[timeptr->tm_wday],
794 mon_name[timeptr->tm_mon],
795 timeptr->tm_mday, timeptr->tm_hour,
796 timeptr->tm_min, timeptr->tm_sec,
797 1900 + timeptr->tm_year);
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000798}
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000799
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000800static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000801time_asctime(PyObject *self, PyObject *args)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000802{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000803 PyObject *tup = NULL;
804 struct tm buf;
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000805
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000806 if (!PyArg_UnpackTuple(args, "asctime", 0, 1, &tup))
807 return NULL;
808 if (tup == NULL) {
809 time_t tt = time(NULL);
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -0400810 if (_PyTime_localtime(tt, &buf) != 0)
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100811 return NULL;
Oren Milman1d1d3e92017-08-20 18:35:36 +0300812 }
813 else if (!gettmarg(tup, &buf,
814 "iiiiiiiii;asctime(): illegal time tuple argument") ||
815 !checktm(&buf))
816 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000817 return NULL;
Oren Milman1d1d3e92017-08-20 18:35:36 +0300818 }
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000819 return _asctime(&buf);
Guido van Rossum9e90a671993-06-24 11:10:19 +0000820}
821
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000822PyDoc_STRVAR(asctime_doc,
Thomas Woutersfe385252001-01-19 23:16:56 +0000823"asctime([tuple]) -> string\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000824\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000825Convert a time tuple to a string, e.g. 'Sat Jun 06 16:26:11 1998'.\n\
826When the time tuple is not present, current time as returned by localtime()\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000827is used.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000828
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000829static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000830time_ctime(PyObject *self, PyObject *args)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000831{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000832 time_t tt;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100833 struct tm buf;
834 if (!parse_time_t_args(args, "|O:ctime", &tt))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000835 return NULL;
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -0400836 if (_PyTime_localtime(tt, &buf) != 0)
Alexander Belopolsky5da468f2011-01-04 17:15:52 +0000837 return NULL;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100838 return _asctime(&buf);
Guido van Rossum9e90a671993-06-24 11:10:19 +0000839}
840
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000841PyDoc_STRVAR(ctime_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000842"ctime(seconds) -> string\n\
843\n\
844Convert a time in seconds since the Epoch to a string in local time.\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000845This is equivalent to asctime(localtime(seconds)). When the time tuple is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000846not present, current time as returned by localtime() is used.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000847
Guido van Rossum60cd8131998-03-06 17:16:21 +0000848#ifdef HAVE_MKTIME
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000849static PyObject *
Victor Stinner4195b5c2012-02-08 23:03:19 +0100850time_mktime(PyObject *self, PyObject *tup)
Guido van Rossum234f9421993-06-17 12:35:49 +0000851{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000852 struct tm buf;
853 time_t tt;
Oren Milman1d1d3e92017-08-20 18:35:36 +0300854 if (!gettmarg(tup, &buf,
855 "iiiiiiiii;mktime(): illegal time tuple argument"))
856 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000857 return NULL;
Oren Milman1d1d3e92017-08-20 18:35:36 +0300858 }
Victor Stinner1ac42612014-02-21 09:27:17 +0100859#ifdef _AIX
860 /* year < 1902 or year > 2037 */
861 if (buf.tm_year < 2 || buf.tm_year > 137) {
862 /* Issue #19748: On AIX, mktime() doesn't report overflow error for
863 * timestamp < -2^31 or timestamp > 2**31-1. */
864 PyErr_SetString(PyExc_OverflowError,
865 "mktime argument out of range");
866 return NULL;
867 }
868#else
Alexander Belopolskyb7d40d12011-01-11 01:21:25 +0000869 buf.tm_wday = -1; /* sentinel; original value ignored */
Victor Stinner1ac42612014-02-21 09:27:17 +0100870#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000871 tt = mktime(&buf);
Alexander Belopolskyb7d40d12011-01-11 01:21:25 +0000872 /* Return value of -1 does not necessarily mean an error, but tm_wday
Ezio Melotti13925002011-03-16 11:05:33 +0200873 * cannot remain set to -1 if mktime succeeded. */
Victor Stinner93037492013-06-25 22:54:35 +0200874 if (tt == (time_t)(-1)
875#ifndef _AIX
876 /* Return value of -1 does not necessarily mean an error, but
877 * tm_wday cannot remain set to -1 if mktime succeeded. */
878 && buf.tm_wday == -1
879#else
880 /* on AIX, tm_wday is always sets, even on error */
881#endif
882 )
883 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000884 PyErr_SetString(PyExc_OverflowError,
885 "mktime argument out of range");
886 return NULL;
887 }
Victor Stinner4195b5c2012-02-08 23:03:19 +0100888 return PyFloat_FromDouble((double)tt);
Guido van Rossum234f9421993-06-17 12:35:49 +0000889}
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000890
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000891PyDoc_STRVAR(mktime_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000892"mktime(tuple) -> floating point number\n\
893\n\
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400894Convert a time tuple in local time to seconds since the Epoch.\n\
895Note that mktime(gmtime(0)) will not generally return zero for most\n\
896time zones; instead the returned value will either be equal to that\n\
897of the timezone or altzone attributes on the time module.");
Guido van Rossum60cd8131998-03-06 17:16:21 +0000898#endif /* HAVE_MKTIME */
Guido van Rossum234f9421993-06-17 12:35:49 +0000899
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000900#ifdef HAVE_WORKING_TZSET
Martin v. Löwis1a214512008-06-11 05:26:20 +0000901static void PyInit_timezone(PyObject *module);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000902
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000903static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000904time_tzset(PyObject *self, PyObject *unused)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000905{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000906 PyObject* m;
Fred Drake9bb74322002-04-01 14:49:59 +0000907
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000908 m = PyImport_ImportModuleNoBlock("time");
909 if (m == NULL) {
910 return NULL;
911 }
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000912
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000913 tzset();
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000914
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000915 /* Reset timezone, altzone, daylight and tzname */
916 PyInit_timezone(m);
917 Py_DECREF(m);
Victor Stinner2ff51b82013-07-17 21:42:45 +0200918 if (PyErr_Occurred())
919 return NULL;
Tim Peters1b6f7a92004-06-20 02:50:16 +0000920
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200921 Py_RETURN_NONE;
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000922}
923
924PyDoc_STRVAR(tzset_doc,
R. David Murray4d55bf92010-12-14 00:55:46 +0000925"tzset()\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000926\n\
927Initialize, or reinitialize, the local timezone to the value stored in\n\
928os.environ['TZ']. The TZ environment variable should be specified in\n\
Neal Norwitzdc8e1942004-07-20 22:34:37 +0000929standard Unix timezone format as documented in the tzset man page\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000930(eg. 'US/Eastern', 'Europe/Amsterdam'). Unknown timezones will silently\n\
931fall back to UTC. If the TZ environment variable is not set, the local\n\
932timezone is set to the systems best guess of wallclock time.\n\
933Changing the TZ environment variable without calling tzset *may* change\n\
934the local timezone used by methods such as localtime, but this behaviour\n\
935should not be relied on.");
936#endif /* HAVE_WORKING_TZSET */
937
Victor Stinnerae586492014-09-02 23:18:25 +0200938static PyObject *
Victor Stinnerec895392012-04-29 02:41:27 +0200939pymonotonic(_Py_clock_info_t *info)
Victor Stinnerb94b2662012-01-18 01:50:21 +0100940{
Victor Stinner4bfb4602015-03-27 22:27:24 +0100941 _PyTime_t t;
942 double d;
943 if (_PyTime_GetMonotonicClockWithInfo(&t, info) < 0) {
Victor Stinnerae586492014-09-02 23:18:25 +0200944 assert(info != NULL);
Victor Stinner071eca32012-03-15 01:17:09 +0100945 return NULL;
946 }
Victor Stinner4bfb4602015-03-27 22:27:24 +0100947 d = _PyTime_AsSecondsDouble(t);
948 return PyFloat_FromDouble(d);
Victor Stinner8b302012012-02-07 23:29:46 +0100949}
950
Victor Stinner071eca32012-03-15 01:17:09 +0100951static PyObject *
Victor Stinnerec895392012-04-29 02:41:27 +0200952time_monotonic(PyObject *self, PyObject *unused)
Victor Stinner071eca32012-03-15 01:17:09 +0100953{
Victor Stinnerec895392012-04-29 02:41:27 +0200954 return pymonotonic(NULL);
Victor Stinner071eca32012-03-15 01:17:09 +0100955}
956
Victor Stinnerec895392012-04-29 02:41:27 +0200957PyDoc_STRVAR(monotonic_doc,
958"monotonic() -> float\n\
Victor Stinner8b302012012-02-07 23:29:46 +0100959\n\
Victor Stinnerec895392012-04-29 02:41:27 +0200960Monotonic clock, cannot go backward.");
Victor Stinnerec919cc2012-03-15 00:58:32 +0100961
Victor Stinnerec895392012-04-29 02:41:27 +0200962static PyObject*
963perf_counter(_Py_clock_info_t *info)
964{
Victor Stinner54884492014-08-29 16:51:33 +0200965#ifdef WIN32_PERF_COUNTER
966 return win_perf_counter(info);
967#else
Victor Stinnerae586492014-09-02 23:18:25 +0200968 return pymonotonic(info);
Victor Stinner54884492014-08-29 16:51:33 +0200969#endif
Victor Stinnerec895392012-04-29 02:41:27 +0200970}
971
972static PyObject *
973time_perf_counter(PyObject *self, PyObject *unused)
974{
975 return perf_counter(NULL);
976}
977
978PyDoc_STRVAR(perf_counter_doc,
979"perf_counter() -> float\n\
980\n\
981Performance counter for benchmarking.");
982
983static PyObject*
984py_process_time(_Py_clock_info_t *info)
985{
986#if defined(MS_WINDOWS)
987 HANDLE process;
988 FILETIME creation_time, exit_time, kernel_time, user_time;
989 ULARGE_INTEGER large;
990 double total;
991 BOOL ok;
992
993 process = GetCurrentProcess();
994 ok = GetProcessTimes(process, &creation_time, &exit_time, &kernel_time, &user_time);
995 if (!ok)
996 return PyErr_SetFromWindowsErr(0);
997
998 large.u.LowPart = kernel_time.dwLowDateTime;
999 large.u.HighPart = kernel_time.dwHighDateTime;
1000 total = (double)large.QuadPart;
1001 large.u.LowPart = user_time.dwLowDateTime;
1002 large.u.HighPart = user_time.dwHighDateTime;
1003 total += (double)large.QuadPart;
1004 if (info) {
1005 info->implementation = "GetProcessTimes()";
1006 info->resolution = 1e-7;
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001007 info->monotonic = 1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001008 info->adjustable = 0;
Victor Stinnerec895392012-04-29 02:41:27 +02001009 }
1010 return PyFloat_FromDouble(total * 1e-7);
1011#else
1012
1013#if defined(HAVE_SYS_RESOURCE_H)
1014 struct rusage ru;
1015#endif
1016#ifdef HAVE_TIMES
1017 struct tms t;
1018 static long ticks_per_second = -1;
1019#endif
1020
1021#if defined(HAVE_CLOCK_GETTIME) \
1022 && (defined(CLOCK_PROCESS_CPUTIME_ID) || defined(CLOCK_PROF))
1023 struct timespec tp;
1024#ifdef CLOCK_PROF
1025 const clockid_t clk_id = CLOCK_PROF;
1026 const char *function = "clock_gettime(CLOCK_PROF)";
1027#else
1028 const clockid_t clk_id = CLOCK_PROCESS_CPUTIME_ID;
1029 const char *function = "clock_gettime(CLOCK_PROCESS_CPUTIME_ID)";
1030#endif
1031
1032 if (clock_gettime(clk_id, &tp) == 0) {
1033 if (info) {
1034 struct timespec res;
1035 info->implementation = function;
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001036 info->monotonic = 1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001037 info->adjustable = 0;
Victor Stinnerec895392012-04-29 02:41:27 +02001038 if (clock_getres(clk_id, &res) == 0)
1039 info->resolution = res.tv_sec + res.tv_nsec * 1e-9;
1040 else
1041 info->resolution = 1e-9;
1042 }
1043 return PyFloat_FromDouble(tp.tv_sec + tp.tv_nsec * 1e-9);
1044 }
1045#endif
1046
1047#if defined(HAVE_SYS_RESOURCE_H)
1048 if (getrusage(RUSAGE_SELF, &ru) == 0) {
1049 double total;
1050 total = ru.ru_utime.tv_sec + ru.ru_utime.tv_usec * 1e-6;
1051 total += ru.ru_stime.tv_sec + ru.ru_stime.tv_usec * 1e-6;
1052 if (info) {
1053 info->implementation = "getrusage(RUSAGE_SELF)";
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001054 info->monotonic = 1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001055 info->adjustable = 0;
Victor Stinnerec895392012-04-29 02:41:27 +02001056 info->resolution = 1e-6;
1057 }
1058 return PyFloat_FromDouble(total);
1059 }
1060#endif
1061
1062#ifdef HAVE_TIMES
1063 if (times(&t) != (clock_t)-1) {
1064 double total;
1065
1066 if (ticks_per_second == -1) {
1067#if defined(HAVE_SYSCONF) && defined(_SC_CLK_TCK)
1068 ticks_per_second = sysconf(_SC_CLK_TCK);
1069 if (ticks_per_second < 1)
1070 ticks_per_second = -1;
1071#elif defined(HZ)
1072 ticks_per_second = HZ;
1073#else
1074 ticks_per_second = 60; /* magic fallback value; may be bogus */
1075#endif
1076 }
1077
1078 if (ticks_per_second != -1) {
1079 total = (double)t.tms_utime / ticks_per_second;
1080 total += (double)t.tms_stime / ticks_per_second;
1081 if (info) {
1082 info->implementation = "times()";
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001083 info->monotonic = 1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001084 info->adjustable = 0;
Victor Stinnerec895392012-04-29 02:41:27 +02001085 info->resolution = 1.0 / ticks_per_second;
1086 }
1087 return PyFloat_FromDouble(total);
1088 }
1089 }
1090#endif
1091
Victor Stinner53e22bf2016-07-08 17:55:01 +02001092 /* Currently, Python 3 requires clock() to build: see issue #22624 */
Victor Stinnerec895392012-04-29 02:41:27 +02001093 return floatclock(info);
1094#endif
1095}
1096
1097static PyObject *
1098time_process_time(PyObject *self, PyObject *unused)
1099{
1100 return py_process_time(NULL);
1101}
1102
1103PyDoc_STRVAR(process_time_doc,
1104"process_time() -> float\n\
1105\n\
1106Process time for profiling: sum of the kernel and user-space CPU time.");
1107
1108
Victor Stinnerec895392012-04-29 02:41:27 +02001109static PyObject *
1110time_get_clock_info(PyObject *self, PyObject *args)
1111{
1112 char *name;
Victor Stinnerec895392012-04-29 02:41:27 +02001113 _Py_clock_info_t info;
Victor Stinnerbda4b882012-06-12 22:11:44 +02001114 PyObject *obj = NULL, *dict, *ns;
Victor Stinnerec895392012-04-29 02:41:27 +02001115
1116 if (!PyArg_ParseTuple(args, "s:get_clock_info", &name))
1117 return NULL;
1118
1119#ifdef Py_DEBUG
1120 info.implementation = NULL;
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001121 info.monotonic = -1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001122 info.adjustable = -1;
Victor Stinnerec895392012-04-29 02:41:27 +02001123 info.resolution = -1.0;
1124#else
1125 info.implementation = "";
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001126 info.monotonic = 0;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001127 info.adjustable = 0;
Victor Stinnerec895392012-04-29 02:41:27 +02001128 info.resolution = 1.0;
1129#endif
1130
1131 if (strcmp(name, "time") == 0)
1132 obj = floattime(&info);
1133#ifdef PYCLOCK
1134 else if (strcmp(name, "clock") == 0)
1135 obj = pyclock(&info);
1136#endif
Victor Stinnerec895392012-04-29 02:41:27 +02001137 else if (strcmp(name, "monotonic") == 0)
1138 obj = pymonotonic(&info);
Victor Stinnerec895392012-04-29 02:41:27 +02001139 else if (strcmp(name, "perf_counter") == 0)
1140 obj = perf_counter(&info);
1141 else if (strcmp(name, "process_time") == 0)
1142 obj = py_process_time(&info);
1143 else {
1144 PyErr_SetString(PyExc_ValueError, "unknown clock");
1145 return NULL;
1146 }
1147 if (obj == NULL)
1148 return NULL;
1149 Py_DECREF(obj);
1150
Victor Stinnerbda4b882012-06-12 22:11:44 +02001151 dict = PyDict_New();
1152 if (dict == NULL)
Victor Stinnerec895392012-04-29 02:41:27 +02001153 return NULL;
1154
1155 assert(info.implementation != NULL);
1156 obj = PyUnicode_FromString(info.implementation);
1157 if (obj == NULL)
1158 goto error;
Victor Stinnerbda4b882012-06-12 22:11:44 +02001159 if (PyDict_SetItemString(dict, "implementation", obj) == -1)
1160 goto error;
1161 Py_CLEAR(obj);
Victor Stinnerec895392012-04-29 02:41:27 +02001162
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001163 assert(info.monotonic != -1);
1164 obj = PyBool_FromLong(info.monotonic);
Victor Stinnerec895392012-04-29 02:41:27 +02001165 if (obj == NULL)
1166 goto error;
Victor Stinnerbda4b882012-06-12 22:11:44 +02001167 if (PyDict_SetItemString(dict, "monotonic", obj) == -1)
1168 goto error;
1169 Py_CLEAR(obj);
Victor Stinnerec895392012-04-29 02:41:27 +02001170
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001171 assert(info.adjustable != -1);
1172 obj = PyBool_FromLong(info.adjustable);
Victor Stinnerec895392012-04-29 02:41:27 +02001173 if (obj == NULL)
1174 goto error;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001175 if (PyDict_SetItemString(dict, "adjustable", obj) == -1)
Victor Stinnerbda4b882012-06-12 22:11:44 +02001176 goto error;
1177 Py_CLEAR(obj);
Victor Stinnerec895392012-04-29 02:41:27 +02001178
1179 assert(info.resolution > 0.0);
1180 assert(info.resolution <= 1.0);
1181 obj = PyFloat_FromDouble(info.resolution);
1182 if (obj == NULL)
1183 goto error;
Victor Stinnerbda4b882012-06-12 22:11:44 +02001184 if (PyDict_SetItemString(dict, "resolution", obj) == -1)
1185 goto error;
1186 Py_CLEAR(obj);
Victor Stinnerec895392012-04-29 02:41:27 +02001187
Victor Stinnerbda4b882012-06-12 22:11:44 +02001188 ns = _PyNamespace_New(dict);
1189 Py_DECREF(dict);
1190 return ns;
Victor Stinnerec895392012-04-29 02:41:27 +02001191
1192error:
Victor Stinnerbda4b882012-06-12 22:11:44 +02001193 Py_DECREF(dict);
1194 Py_XDECREF(obj);
Victor Stinnerec895392012-04-29 02:41:27 +02001195 return NULL;
1196}
1197
1198PyDoc_STRVAR(get_clock_info_doc,
1199"get_clock_info(name: str) -> dict\n\
1200\n\
1201Get information of the specified clock.");
Victor Stinner8b302012012-02-07 23:29:46 +01001202
Victor Stinner8f5cdfa2017-04-20 13:41:09 +02001203#if !defined(HAVE_TZNAME) || defined(__GLIBC__) || defined(__CYGWIN__)
Martin v. Löwisd218dc12008-04-07 03:17:54 +00001204static void
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -04001205get_zone(char *zone, int n, struct tm *p)
1206{
1207#ifdef HAVE_STRUCT_TM_TM_ZONE
1208 strncpy(zone, p->tm_zone ? p->tm_zone : " ", n);
1209#else
1210 tzset();
1211 strftime(zone, n, "%Z", p);
1212#endif
1213}
1214
1215static int
1216get_gmtoff(time_t t, struct tm *p)
1217{
1218#ifdef HAVE_STRUCT_TM_TM_ZONE
1219 return p->tm_gmtoff;
1220#else
1221 return timegm(p) - t;
1222#endif
1223}
Victor Stinner8f5cdfa2017-04-20 13:41:09 +02001224#endif /* !defined(HAVE_TZNAME) || defined(__GLIBC__) || defined(__CYGWIN__) */
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -04001225
1226static void
Martin v. Löwis1a214512008-06-11 05:26:20 +00001227PyInit_timezone(PyObject *m) {
1228 /* This code moved from PyInit_time wholesale to allow calling it from
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001229 time_tzset. In the future, some parts of it can be moved back
1230 (for platforms that don't HAVE_WORKING_TZSET, when we know what they
1231 are), and the extraneous calls to tzset(3) should be removed.
1232 I haven't done this yet, as I don't want to change this code as
1233 little as possible when introducing the time.tzset and time.tzsetwall
1234 methods. This should simply be a method of doing the following once,
1235 at the top of this function and removing the call to tzset() from
1236 time_tzset():
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001237
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001238 #ifdef HAVE_TZSET
1239 tzset()
1240 #endif
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001241
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001242 And I'm lazy and hate C so nyer.
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001243 */
Guido van Rossum10b164a2001-09-25 13:59:01 +00001244#if defined(HAVE_TZNAME) && !defined(__GLIBC__) && !defined(__CYGWIN__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001245 PyObject *otz0, *otz1;
1246 tzset();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001247 PyModule_AddIntConstant(m, "timezone", timezone);
Guido van Rossumb6775db1994-08-01 11:34:53 +00001248#ifdef HAVE_ALTZONE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001249 PyModule_AddIntConstant(m, "altzone", altzone);
Guido van Rossumb6775db1994-08-01 11:34:53 +00001250#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001251 PyModule_AddIntConstant(m, "altzone", timezone-3600);
Guido van Rossumb6775db1994-08-01 11:34:53 +00001252#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001253 PyModule_AddIntConstant(m, "daylight", daylight);
Victor Stinner1b579672011-12-17 05:47:23 +01001254 otz0 = PyUnicode_DecodeLocale(tzname[0], "surrogateescape");
1255 otz1 = PyUnicode_DecodeLocale(tzname[1], "surrogateescape");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001256 PyModule_AddObject(m, "tzname", Py_BuildValue("(NN)", otz0, otz1));
Guido van Rossum10b164a2001-09-25 13:59:01 +00001257#else /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001258 {
Guido van Rossum234f9421993-06-17 12:35:49 +00001259#define YEAR ((time_t)((365 * 24 + 6) * 3600))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001260 time_t t;
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -04001261 struct tm p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001262 long janzone, julyzone;
1263 char janname[10], julyname[10];
1264 t = (time((time_t *)0) / YEAR) * YEAR;
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -04001265 _PyTime_localtime(t, &p);
1266 get_zone(janname, 9, &p);
1267 janzone = -get_gmtoff(t, &p);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001268 janname[9] = '\0';
1269 t += YEAR/2;
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -04001270 _PyTime_localtime(t, &p);
1271 get_zone(julyname, 9, &p);
1272 julyzone = -get_gmtoff(t, &p);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001273 julyname[9] = '\0';
Guido van Rossum10b164a2001-09-25 13:59:01 +00001274
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001275 if( janzone < julyzone ) {
1276 /* DST is reversed in the southern hemisphere */
1277 PyModule_AddIntConstant(m, "timezone", julyzone);
1278 PyModule_AddIntConstant(m, "altzone", janzone);
1279 PyModule_AddIntConstant(m, "daylight",
1280 janzone != julyzone);
1281 PyModule_AddObject(m, "tzname",
1282 Py_BuildValue("(zz)",
1283 julyname, janname));
1284 } else {
1285 PyModule_AddIntConstant(m, "timezone", janzone);
1286 PyModule_AddIntConstant(m, "altzone", julyzone);
1287 PyModule_AddIntConstant(m, "daylight",
1288 janzone != julyzone);
1289 PyModule_AddObject(m, "tzname",
1290 Py_BuildValue("(zz)",
1291 janname, julyname));
1292 }
1293 }
Tim Peters26ae7cd2001-03-20 03:26:49 +00001294#ifdef __CYGWIN__
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001295 tzset();
1296 PyModule_AddIntConstant(m, "timezone", _timezone);
1297 PyModule_AddIntConstant(m, "altzone", _timezone-3600);
1298 PyModule_AddIntConstant(m, "daylight", _daylight);
1299 PyModule_AddObject(m, "tzname",
1300 Py_BuildValue("(zz)", _tzname[0], _tzname[1]));
Tim Peters26ae7cd2001-03-20 03:26:49 +00001301#endif /* __CYGWIN__ */
Guido van Rossum10b164a2001-09-25 13:59:01 +00001302#endif /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001303}
1304
1305
1306static PyMethodDef time_methods[] = {
Victor Stinner4195b5c2012-02-08 23:03:19 +01001307 {"time", time_time, METH_NOARGS, time_doc},
Victor Stinnerec895392012-04-29 02:41:27 +02001308#ifdef PYCLOCK
Victor Stinner4195b5c2012-02-08 23:03:19 +01001309 {"clock", time_clock, METH_NOARGS, clock_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001310#endif
Victor Stinnere0be4232011-10-25 13:06:09 +02001311#ifdef HAVE_CLOCK_GETTIME
Victor Stinner4195b5c2012-02-08 23:03:19 +01001312 {"clock_gettime", time_clock_gettime, METH_VARARGS, clock_gettime_doc},
Benjamin Peterson37098cd2016-09-13 22:55:09 -07001313#endif
1314#ifdef HAVE_CLOCK_SETTIME
Victor Stinner30d79472012-04-03 00:45:07 +02001315 {"clock_settime", time_clock_settime, METH_VARARGS, clock_settime_doc},
Benjamin Peterson37098cd2016-09-13 22:55:09 -07001316#endif
1317#ifdef HAVE_CLOCK_GETRES
Victor Stinner4195b5c2012-02-08 23:03:19 +01001318 {"clock_getres", time_clock_getres, METH_VARARGS, clock_getres_doc},
Victor Stinnere0be4232011-10-25 13:06:09 +02001319#endif
pdoxe14679c2017-10-05 00:01:56 -07001320#ifdef HAVE_PTHREAD_GETCPUCLOCKID
1321 {"pthread_getcpuclockid", time_pthread_getcpuclockid, METH_VARARGS, pthread_getcpuclockid_doc},
1322#endif
Victor Stinnercb29f012015-03-27 13:31:18 +01001323 {"sleep", time_sleep, METH_O, sleep_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001324 {"gmtime", time_gmtime, METH_VARARGS, gmtime_doc},
1325 {"localtime", time_localtime, METH_VARARGS, localtime_doc},
1326 {"asctime", time_asctime, METH_VARARGS, asctime_doc},
1327 {"ctime", time_ctime, METH_VARARGS, ctime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001328#ifdef HAVE_MKTIME
Victor Stinner4195b5c2012-02-08 23:03:19 +01001329 {"mktime", time_mktime, METH_O, mktime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001330#endif
1331#ifdef HAVE_STRFTIME
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001332 {"strftime", time_strftime, METH_VARARGS, strftime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001333#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001334 {"strptime", time_strptime, METH_VARARGS, strptime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001335#ifdef HAVE_WORKING_TZSET
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001336 {"tzset", time_tzset, METH_NOARGS, tzset_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001337#endif
Victor Stinnerec895392012-04-29 02:41:27 +02001338 {"monotonic", time_monotonic, METH_NOARGS, monotonic_doc},
Victor Stinnerec895392012-04-29 02:41:27 +02001339 {"process_time", time_process_time, METH_NOARGS, process_time_doc},
1340 {"perf_counter", time_perf_counter, METH_NOARGS, perf_counter_doc},
1341 {"get_clock_info", time_get_clock_info, METH_VARARGS, get_clock_info_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001342 {NULL, NULL} /* sentinel */
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001343};
1344
1345
1346PyDoc_STRVAR(module_doc,
1347"This module provides various functions to manipulate time values.\n\
1348\n\
1349There are two standard representations of time. One is the number\n\
1350of seconds since the Epoch, in UTC (a.k.a. GMT). It may be an integer\n\
1351or a floating point number (to represent fractions of seconds).\n\
1352The Epoch is system-defined; on Unix, it is generally January 1st, 1970.\n\
1353The actual value can be retrieved by calling gmtime(0).\n\
1354\n\
1355The other representation is a tuple of 9 integers giving local time.\n\
1356The tuple items are:\n\
Alexander Belopolsky03163ac2011-05-02 12:20:52 -04001357 year (including century, e.g. 1998)\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001358 month (1-12)\n\
1359 day (1-31)\n\
1360 hours (0-23)\n\
1361 minutes (0-59)\n\
1362 seconds (0-59)\n\
1363 weekday (0-6, Monday is 0)\n\
1364 Julian day (day in the year, 1-366)\n\
1365 DST (Daylight Savings Time) flag (-1, 0 or 1)\n\
1366If the DST flag is 0, the time is given in the regular time zone;\n\
1367if it is 1, the time is given in the DST time zone;\n\
1368if it is -1, mktime() should guess based on the date and time.\n\
1369\n\
1370Variables:\n\
1371\n\
1372timezone -- difference in seconds between UTC and local standard time\n\
1373altzone -- difference in seconds between UTC and local DST time\n\
1374daylight -- whether local time should reflect DST\n\
1375tzname -- tuple of (standard time zone name, DST time zone name)\n\
1376\n\
1377Functions:\n\
1378\n\
1379time() -- return current time in seconds since the Epoch as a float\n\
1380clock() -- return CPU time since process start as a float\n\
1381sleep() -- delay for a number of seconds given as a float\n\
1382gmtime() -- convert seconds since Epoch to UTC tuple\n\
1383localtime() -- convert seconds since Epoch to local time tuple\n\
1384asctime() -- convert time tuple to string\n\
1385ctime() -- convert time in seconds to string\n\
1386mktime() -- convert local time tuple to seconds since Epoch\n\
1387strftime() -- convert time tuple to string according to format specification\n\
1388strptime() -- parse string to time tuple according to format specification\n\
1389tzset() -- change the local timezone");
1390
1391
Martin v. Löwis1a214512008-06-11 05:26:20 +00001392
1393static struct PyModuleDef timemodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001394 PyModuleDef_HEAD_INIT,
1395 "time",
1396 module_doc,
1397 -1,
1398 time_methods,
1399 NULL,
1400 NULL,
1401 NULL,
1402 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00001403};
1404
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001405PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00001406PyInit_time(void)
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001407{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001408 PyObject *m;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001409 m = PyModule_Create(&timemodule);
1410 if (m == NULL)
1411 return NULL;
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001412
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001413 /* Set, or reset, module variables like time.timezone */
1414 PyInit_timezone(m);
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001415
Benjamin Peterson37098cd2016-09-13 22:55:09 -07001416#ifdef CLOCK_REALTIME
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -04001417 PyModule_AddIntMacro(m, CLOCK_REALTIME);
Benjamin Peterson37098cd2016-09-13 22:55:09 -07001418#endif
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -04001419#ifdef CLOCK_MONOTONIC
1420 PyModule_AddIntMacro(m, CLOCK_MONOTONIC);
1421#endif
1422#ifdef CLOCK_MONOTONIC_RAW
1423 PyModule_AddIntMacro(m, CLOCK_MONOTONIC_RAW);
1424#endif
1425#ifdef CLOCK_HIGHRES
1426 PyModule_AddIntMacro(m, CLOCK_HIGHRES);
1427#endif
1428#ifdef CLOCK_PROCESS_CPUTIME_ID
1429 PyModule_AddIntMacro(m, CLOCK_PROCESS_CPUTIME_ID);
1430#endif
1431#ifdef CLOCK_THREAD_CPUTIME_ID
1432 PyModule_AddIntMacro(m, CLOCK_THREAD_CPUTIME_ID);
1433#endif
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -04001434
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001435 if (!initialized) {
Victor Stinner1c8f0592013-07-22 22:24:54 +02001436 if (PyStructSequence_InitType2(&StructTimeType,
1437 &struct_time_type_desc) < 0)
1438 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001439 }
1440 Py_INCREF(&StructTimeType);
Alexander Belopolskyc142bba2012-06-13 22:15:26 -04001441 PyModule_AddIntConstant(m, "_STRUCT_TM_ITEMS", 11);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001442 PyModule_AddObject(m, "struct_time", (PyObject*) &StructTimeType);
1443 initialized = 1;
1444 return m;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001445}
1446
Victor Stinner071eca32012-03-15 01:17:09 +01001447static PyObject*
Victor Stinnerec895392012-04-29 02:41:27 +02001448floattime(_Py_clock_info_t *info)
Victor Stinner4195b5c2012-02-08 23:03:19 +01001449{
Victor Stinnera47b8812015-03-27 18:16:17 +01001450 _PyTime_t t;
1451 double d;
1452 if (_PyTime_GetSystemClockWithInfo(&t, info) < 0) {
Victor Stinner00111242014-08-29 16:31:59 +02001453 assert(info != NULL);
1454 return NULL;
1455 }
Victor Stinnera47b8812015-03-27 18:16:17 +01001456 d = _PyTime_AsSecondsDouble(t);
1457 return PyFloat_FromDouble(d);
Victor Stinner4195b5c2012-02-08 23:03:19 +01001458}
1459
1460
Victor Stinnercb29f012015-03-27 13:31:18 +01001461/* Implement pysleep() for various platforms.
Guido van Rossumb6775db1994-08-01 11:34:53 +00001462 When interrupted (or when another error occurs), return -1 and
1463 set an exception; else return 0. */
1464
1465static int
Victor Stinnercb29f012015-03-27 13:31:18 +01001466pysleep(_PyTime_t secs)
Guido van Rossum426035c1991-02-19 12:27:35 +00001467{
Victor Stinnercb29f012015-03-27 13:31:18 +01001468 _PyTime_t deadline, monotonic;
Victor Stinner79d68f92015-03-19 21:54:09 +01001469#ifndef MS_WINDOWS
1470 struct timeval timeout;
Victor Stinner79d68f92015-03-19 21:54:09 +01001471 int err = 0;
1472#else
Victor Stinnercb29f012015-03-27 13:31:18 +01001473 _PyTime_t millisecs;
Victor Stinner79d68f92015-03-19 21:54:09 +01001474 unsigned long ul_millis;
1475 DWORD rc;
1476 HANDLE hInterruptEvent;
Victor Stinner0c2fd892015-03-17 10:49:17 +01001477#endif
Victor Stinner79d68f92015-03-19 21:54:09 +01001478
Victor Stinnercb29f012015-03-27 13:31:18 +01001479 deadline = _PyTime_GetMonotonicClock() + secs;
Victor Stinner79d68f92015-03-19 21:54:09 +01001480
1481 do {
1482#ifndef MS_WINDOWS
Victor Stinner869e1772015-03-30 03:49:14 +02001483 if (_PyTime_AsTimeval(secs, &timeout, _PyTime_ROUND_CEILING) < 0)
Victor Stinnercb29f012015-03-27 13:31:18 +01001484 return -1;
Victor Stinner79d68f92015-03-19 21:54:09 +01001485
1486 Py_BEGIN_ALLOW_THREADS
1487 err = select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &timeout);
1488 Py_END_ALLOW_THREADS
1489
1490 if (err == 0)
1491 break;
1492
1493 if (errno != EINTR) {
Victor Stinner0c2fd892015-03-17 10:49:17 +01001494 PyErr_SetFromErrno(PyExc_OSError);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001495 return -1;
1496 }
Victor Stinner79d68f92015-03-19 21:54:09 +01001497#else
Victor Stinner869e1772015-03-30 03:49:14 +02001498 millisecs = _PyTime_AsMilliseconds(secs, _PyTime_ROUND_CEILING);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001499 if (millisecs > (double)ULONG_MAX) {
1500 PyErr_SetString(PyExc_OverflowError,
1501 "sleep length is too large");
1502 return -1;
1503 }
Victor Stinner79d68f92015-03-19 21:54:09 +01001504
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001505 /* Allow sleep(0) to maintain win32 semantics, and as decreed
1506 * by Guido, only the main thread can be interrupted.
1507 */
1508 ul_millis = (unsigned long)millisecs;
Victor Stinner79d68f92015-03-19 21:54:09 +01001509 if (ul_millis == 0 || !_PyOS_IsMainThread()) {
1510 Py_BEGIN_ALLOW_THREADS
Victor Stinner0eac1302015-03-20 03:06:12 +01001511 Sleep(ul_millis);
Victor Stinner79d68f92015-03-19 21:54:09 +01001512 Py_END_ALLOW_THREADS
1513 break;
Victor Stinner945c82e2015-03-12 16:19:01 +01001514 }
Victor Stinner79d68f92015-03-19 21:54:09 +01001515
1516 hInterruptEvent = _PyOS_SigintEvent();
1517 ResetEvent(hInterruptEvent);
1518
1519 Py_BEGIN_ALLOW_THREADS
1520 rc = WaitForSingleObjectEx(hInterruptEvent, ul_millis, FALSE);
Victor Stinner0c2fd892015-03-17 10:49:17 +01001521 Py_END_ALLOW_THREADS
Victor Stinner79d68f92015-03-19 21:54:09 +01001522
1523 if (rc != WAIT_OBJECT_0)
1524 break;
Victor Stinner945c82e2015-03-12 16:19:01 +01001525#endif
Victor Stinner0c2fd892015-03-17 10:49:17 +01001526
Victor Stinner79d68f92015-03-19 21:54:09 +01001527 /* sleep was interrupted by SIGINT */
1528 if (PyErr_CheckSignals())
1529 return -1;
1530
Victor Stinnercb29f012015-03-27 13:31:18 +01001531 monotonic = _PyTime_GetMonotonicClock();
1532 secs = deadline - monotonic;
Victor Stinner6aa446c2015-03-30 21:33:51 +02001533 if (secs < 0)
Victor Stinner79d68f92015-03-19 21:54:09 +01001534 break;
1535 /* retry with the recomputed delay */
1536 } while (1);
1537
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001538 return 0;
Guido van Rossum80c9d881991-04-16 08:47:51 +00001539}