blob: 6cf9e7c641e33be0041bff3c7814f4f97ac7f6f7 [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
Victor Stinnerc29b5852017-11-02 07:28:27 -070037#define SEC_TO_NS (1000 * 1000 * 1000)
38
Guido van Rossum234f9421993-06-17 12:35:49 +000039/* Forward declarations */
Victor Stinnercb29f012015-03-27 13:31:18 +010040static int pysleep(_PyTime_t);
Victor Stinnerec895392012-04-29 02:41:27 +020041
Victor Stinner85fdfa82012-01-27 00:38:48 +010042
Victor Stinnera997c7b2017-10-10 02:51:50 -070043static PyObject*
44_PyFloat_FromPyTime(_PyTime_t t)
45{
46 double d = _PyTime_AsSecondsDouble(t);
47 return PyFloat_FromDouble(d);
48}
49
Victor Stinnerc29b5852017-11-02 07:28:27 -070050
Victor Stinner4195b5c2012-02-08 23:03:19 +010051static PyObject *
Victor Stinnerc29b5852017-11-02 07:28:27 -070052time_time(PyObject *self, PyObject *unused)
Victor Stinner85fdfa82012-01-27 00:38:48 +010053{
Victor Stinnerc29b5852017-11-02 07:28:27 -070054 _PyTime_t t = _PyTime_GetSystemClock();
55 return _PyFloat_FromPyTime(t);
56}
57
58
59PyDoc_STRVAR(time_doc,
60"time() -> floating point number\n\
61\n\
62Return the current time in seconds since the Epoch.\n\
63Fractions of a second may be present if the system clock provides them.");
64
65static PyObject *
66time_time_ns(PyObject *self, PyObject *unused)
67{
68 _PyTime_t t = _PyTime_GetSystemClock();
69 return _PyTime_AsNanosecondsObject(t);
70}
71
72PyDoc_STRVAR(time_ns_doc,
73"time_ns() -> int\n\
74\n\
75Return the current time in nanoseconds since the Epoch.");
76
77#if defined(HAVE_CLOCK)
78
79#ifndef CLOCKS_PER_SEC
80# ifdef CLK_TCK
81# define CLOCKS_PER_SEC CLK_TCK
82# else
83# define CLOCKS_PER_SEC 1000000
84# endif
85#endif
86
87static int
88_PyTime_GetClockWithInfo(_PyTime_t *tp, _Py_clock_info_t *info)
89{
90 static int initialized = 0;
91 clock_t ticks;
92
93 if (!initialized) {
94 initialized = 1;
95
96 /* must sure that _PyTime_MulDiv(ticks, SEC_TO_NS, CLOCKS_PER_SEC)
97 above cannot overflow */
98 if ((_PyTime_t)CLOCKS_PER_SEC > _PyTime_MAX / SEC_TO_NS) {
99 PyErr_SetString(PyExc_OverflowError,
100 "CLOCKS_PER_SEC is too large");
101 return -1;
102 }
Victor Stinner85fdfa82012-01-27 00:38:48 +0100103 }
Victor Stinnerc29b5852017-11-02 07:28:27 -0700104
Victor Stinnerec895392012-04-29 02:41:27 +0200105 if (info) {
106 info->implementation = "clock()";
107 info->resolution = 1.0 / (double)CLOCKS_PER_SEC;
Benjamin Peterson49a69e42012-05-01 09:38:34 -0400108 info->monotonic = 1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +0200109 info->adjustable = 0;
Victor Stinnerec895392012-04-29 02:41:27 +0200110 }
Victor Stinnerc29b5852017-11-02 07:28:27 -0700111
112 ticks = clock();
113 if (ticks == (clock_t)-1) {
114 PyErr_SetString(PyExc_RuntimeError,
115 "the processor time used is not available "
116 "or its value cannot be represented");
117 return -1;
118 }
119 *tp = _PyTime_MulDiv(ticks, SEC_TO_NS, (_PyTime_t)CLOCKS_PER_SEC);
120 return 0;
Victor Stinner85fdfa82012-01-27 00:38:48 +0100121}
122#endif /* HAVE_CLOCK */
123
Victor Stinnercba9a0c2017-10-12 08:51:56 -0700124static PyObject*
125perf_counter(_Py_clock_info_t *info)
126{
Victor Stinnerbdaeb7d2017-10-16 08:44:31 -0700127 _PyTime_t t;
128 if (_PyTime_GetPerfCounterWithInfo(&t, info) < 0) {
Victor Stinnercba9a0c2017-10-12 08:51:56 -0700129 return NULL;
130 }
Victor Stinnerc29b5852017-11-02 07:28:27 -0700131 return _PyFloat_FromPyTime(t);
Victor Stinnercba9a0c2017-10-12 08:51:56 -0700132}
133
Victor Stinnera997c7b2017-10-10 02:51:50 -0700134#if defined(MS_WINDOWS) || defined(HAVE_CLOCK)
Victor Stinnerec895392012-04-29 02:41:27 +0200135#define PYCLOCK
136static PyObject*
137pyclock(_Py_clock_info_t *info)
138{
Victor Stinner884d13a2017-10-17 14:46:45 -0700139 if (PyErr_WarnEx(PyExc_DeprecationWarning,
140 "time.clock has been deprecated in Python 3.3 and will "
141 "be removed from Python 3.8: "
142 "use time.perf_counter or time.process_time "
143 "instead", 1) < 0) {
144 return NULL;
145 }
Victor Stinnerc29b5852017-11-02 07:28:27 -0700146
Victor Stinnera997c7b2017-10-10 02:51:50 -0700147#ifdef MS_WINDOWS
Victor Stinnercba9a0c2017-10-12 08:51:56 -0700148 return perf_counter(info);
Victor Stinner54884492014-08-29 16:51:33 +0200149#else
Victor Stinnerc29b5852017-11-02 07:28:27 -0700150 _PyTime_t t;
151 if (_PyTime_GetClockWithInfo(&t, info) < 0) {
152 return NULL;
153 }
154 return _PyFloat_FromPyTime(t);
Victor Stinner54884492014-08-29 16:51:33 +0200155#endif
Victor Stinnerec895392012-04-29 02:41:27 +0200156}
157
Victor Stinner9122fdd2011-07-04 13:55:40 +0200158static PyObject *
Victor Stinner4195b5c2012-02-08 23:03:19 +0100159time_clock(PyObject *self, PyObject *unused)
Victor Stinner9122fdd2011-07-04 13:55:40 +0200160{
Victor Stinnerec895392012-04-29 02:41:27 +0200161 return pyclock(NULL);
Victor Stinner9122fdd2011-07-04 13:55:40 +0200162}
Victor Stinner9122fdd2011-07-04 13:55:40 +0200163
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000164PyDoc_STRVAR(clock_doc,
Victor Stinner4195b5c2012-02-08 23:03:19 +0100165"clock() -> floating point number\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000166\n\
167Return the CPU time or real time since the start of the process or since\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000168the first call to clock(). This has as much precision as the system\n\
169records.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000170#endif
171
Victor Stinnere0be4232011-10-25 13:06:09 +0200172#ifdef HAVE_CLOCK_GETTIME
173static PyObject *
Victor Stinner4195b5c2012-02-08 23:03:19 +0100174time_clock_gettime(PyObject *self, PyObject *args)
Victor Stinnere0be4232011-10-25 13:06:09 +0200175{
176 int ret;
Victor Stinnerb8d01692012-04-13 23:44:05 +0200177 int clk_id;
Victor Stinnere0be4232011-10-25 13:06:09 +0200178 struct timespec tp;
179
Victor Stinnerc29b5852017-11-02 07:28:27 -0700180 if (!PyArg_ParseTuple(args, "i:clock_gettime", &clk_id)) {
Victor Stinnere0be4232011-10-25 13:06:09 +0200181 return NULL;
Victor Stinnerc29b5852017-11-02 07:28:27 -0700182 }
Victor Stinnere0be4232011-10-25 13:06:09 +0200183
184 ret = clock_gettime((clockid_t)clk_id, &tp);
Antoine Pitrou2c085602012-01-18 01:41:44 +0100185 if (ret != 0) {
Victor Stinnera734af32014-07-31 13:07:17 +0200186 PyErr_SetFromErrno(PyExc_OSError);
Antoine Pitrou2c085602012-01-18 01:41:44 +0100187 return NULL;
188 }
Victor Stinner4195b5c2012-02-08 23:03:19 +0100189 return PyFloat_FromDouble(tp.tv_sec + tp.tv_nsec * 1e-9);
Victor Stinnere0be4232011-10-25 13:06:09 +0200190}
191
192PyDoc_STRVAR(clock_gettime_doc,
Victor Stinnerc29b5852017-11-02 07:28:27 -0700193"clock_gettime(clk_id) -> float\n\
Victor Stinnere0be4232011-10-25 13:06:09 +0200194\n\
195Return the time of the specified clock clk_id.");
Victor Stinnerc29b5852017-11-02 07:28:27 -0700196
197static PyObject *
198time_clock_gettime_ns(PyObject *self, PyObject *args)
199{
200 int ret;
201 int clk_id;
202 struct timespec ts;
203 _PyTime_t t;
204
205 if (!PyArg_ParseTuple(args, "i:clock_gettime", &clk_id)) {
206 return NULL;
207 }
208
209 ret = clock_gettime((clockid_t)clk_id, &ts);
210 if (ret != 0) {
211 PyErr_SetFromErrno(PyExc_OSError);
212 return NULL;
213 }
214 if (_PyTime_FromTimespec(&t, &ts) < 0) {
215 return NULL;
216 }
217 return _PyTime_AsNanosecondsObject(t);
218}
219
220PyDoc_STRVAR(clock_gettime_ns_doc,
221"clock_gettime_ns(clk_id) -> int\n\
222\n\
223Return the time of the specified clock clk_id as nanoseconds.");
Benjamin Peterson37098cd2016-09-13 22:55:09 -0700224#endif /* HAVE_CLOCK_GETTIME */
Victor Stinner30d79472012-04-03 00:45:07 +0200225
Benjamin Peterson37098cd2016-09-13 22:55:09 -0700226#ifdef HAVE_CLOCK_SETTIME
Victor Stinner30d79472012-04-03 00:45:07 +0200227static PyObject *
228time_clock_settime(PyObject *self, PyObject *args)
229{
Victor Stinnerb8d01692012-04-13 23:44:05 +0200230 int clk_id;
Victor Stinner30d79472012-04-03 00:45:07 +0200231 PyObject *obj;
Victor Stinnerb3b45442015-03-28 04:09:41 +0100232 _PyTime_t t;
Victor Stinner30d79472012-04-03 00:45:07 +0200233 struct timespec tp;
234 int ret;
235
236 if (!PyArg_ParseTuple(args, "iO:clock_settime", &clk_id, &obj))
237 return NULL;
238
Victor Stinner02937aa2015-03-28 05:02:39 +0100239 if (_PyTime_FromSecondsObject(&t, obj, _PyTime_ROUND_FLOOR) < 0)
Victor Stinner30d79472012-04-03 00:45:07 +0200240 return NULL;
Victor Stinnerb3b45442015-03-28 04:09:41 +0100241
242 if (_PyTime_AsTimespec(t, &tp) == -1)
243 return NULL;
Victor Stinner30d79472012-04-03 00:45:07 +0200244
245 ret = clock_settime((clockid_t)clk_id, &tp);
246 if (ret != 0) {
Victor Stinnera734af32014-07-31 13:07:17 +0200247 PyErr_SetFromErrno(PyExc_OSError);
Victor Stinner30d79472012-04-03 00:45:07 +0200248 return NULL;
249 }
250 Py_RETURN_NONE;
251}
252
253PyDoc_STRVAR(clock_settime_doc,
254"clock_settime(clk_id, time)\n\
255\n\
256Set the time of the specified clock clk_id.");
Victor Stinnerc29b5852017-11-02 07:28:27 -0700257
258static PyObject *
259time_clock_settime_ns(PyObject *self, PyObject *args)
260{
261 int clk_id;
262 PyObject *obj;
263 _PyTime_t t;
264 struct timespec ts;
265 int ret;
266
267 if (!PyArg_ParseTuple(args, "iO:clock_settime", &clk_id, &obj)) {
268 return NULL;
269 }
270
271 if (_PyTime_FromNanosecondsObject(&t, obj) < 0) {
272 return NULL;
273 }
274 if (_PyTime_AsTimespec(t, &ts) == -1) {
275 return NULL;
276 }
277
278 ret = clock_settime((clockid_t)clk_id, &ts);
279 if (ret != 0) {
280 PyErr_SetFromErrno(PyExc_OSError);
281 return NULL;
282 }
283 Py_RETURN_NONE;
284}
285
286PyDoc_STRVAR(clock_settime_ns_doc,
287"clock_settime_ns(clk_id, time)\n\
288\n\
289Set the time of the specified clock clk_id with nanoseconds.");
Benjamin Peterson37098cd2016-09-13 22:55:09 -0700290#endif /* HAVE_CLOCK_SETTIME */
Victor Stinnere0be4232011-10-25 13:06:09 +0200291
Benjamin Peterson37098cd2016-09-13 22:55:09 -0700292#ifdef HAVE_CLOCK_GETRES
Victor Stinnere0be4232011-10-25 13:06:09 +0200293static PyObject *
Victor Stinner4195b5c2012-02-08 23:03:19 +0100294time_clock_getres(PyObject *self, PyObject *args)
Victor Stinnere0be4232011-10-25 13:06:09 +0200295{
296 int ret;
Victor Stinnerb8d01692012-04-13 23:44:05 +0200297 int clk_id;
Victor Stinnere0be4232011-10-25 13:06:09 +0200298 struct timespec tp;
299
Victor Stinner4195b5c2012-02-08 23:03:19 +0100300 if (!PyArg_ParseTuple(args, "i:clock_getres", &clk_id))
Victor Stinnere0be4232011-10-25 13:06:09 +0200301 return NULL;
302
303 ret = clock_getres((clockid_t)clk_id, &tp);
Antoine Pitrou2c085602012-01-18 01:41:44 +0100304 if (ret != 0) {
Victor Stinnera734af32014-07-31 13:07:17 +0200305 PyErr_SetFromErrno(PyExc_OSError);
Antoine Pitrou2c085602012-01-18 01:41:44 +0100306 return NULL;
307 }
Victor Stinner4195b5c2012-02-08 23:03:19 +0100308
309 return PyFloat_FromDouble(tp.tv_sec + tp.tv_nsec * 1e-9);
Victor Stinnere0be4232011-10-25 13:06:09 +0200310}
311
312PyDoc_STRVAR(clock_getres_doc,
Victor Stinner4195b5c2012-02-08 23:03:19 +0100313"clock_getres(clk_id) -> floating point number\n\
Victor Stinnere0be4232011-10-25 13:06:09 +0200314\n\
315Return the resolution (precision) of the specified clock clk_id.");
Benjamin Peterson37098cd2016-09-13 22:55:09 -0700316#endif /* HAVE_CLOCK_GETRES */
Victor Stinnere0be4232011-10-25 13:06:09 +0200317
pdoxe14679c2017-10-05 00:01:56 -0700318#ifdef HAVE_PTHREAD_GETCPUCLOCKID
319static PyObject *
320time_pthread_getcpuclockid(PyObject *self, PyObject *args)
321{
322 unsigned long thread_id;
323 int err;
324 clockid_t clk_id;
325 if (!PyArg_ParseTuple(args, "k:pthread_getcpuclockid", &thread_id)) {
326 return NULL;
327 }
328 err = pthread_getcpuclockid((pthread_t)thread_id, &clk_id);
329 if (err) {
330 errno = err;
331 PyErr_SetFromErrno(PyExc_OSError);
332 return NULL;
333 }
334 return PyLong_FromLong(clk_id);
335}
336
337PyDoc_STRVAR(pthread_getcpuclockid_doc,
338"pthread_getcpuclockid(thread_id) -> int\n\
339\n\
340Return the clk_id of a thread's CPU time clock.");
341#endif /* HAVE_PTHREAD_GETCPUCLOCKID */
342
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000343static PyObject *
Victor Stinnercb29f012015-03-27 13:31:18 +0100344time_sleep(PyObject *self, PyObject *obj)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000345{
Victor Stinnercb29f012015-03-27 13:31:18 +0100346 _PyTime_t secs;
Pablo Galindo59af94f2017-10-18 08:13:09 +0100347 if (_PyTime_FromSecondsObject(&secs, obj, _PyTime_ROUND_TIMEOUT))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000348 return NULL;
Victor Stinner7f53a502011-07-05 22:00:25 +0200349 if (secs < 0) {
350 PyErr_SetString(PyExc_ValueError,
351 "sleep length must be non-negative");
352 return NULL;
353 }
Victor Stinnercb29f012015-03-27 13:31:18 +0100354 if (pysleep(secs) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000355 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200356 Py_RETURN_NONE;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000357}
358
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000359PyDoc_STRVAR(sleep_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000360"sleep(seconds)\n\
361\n\
362Delay execution for a given number of seconds. The argument may be\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000363a floating point number for subsecond precision.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000364
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000365static PyStructSequence_Field struct_time_type_fields[] = {
Alexander Belopolsky69f3fd02010-06-05 15:04:51 +0000366 {"tm_year", "year, for example, 1993"},
367 {"tm_mon", "month of year, range [1, 12]"},
368 {"tm_mday", "day of month, range [1, 31]"},
369 {"tm_hour", "hours, range [0, 23]"},
370 {"tm_min", "minutes, range [0, 59]"},
371 {"tm_sec", "seconds, range [0, 61])"},
372 {"tm_wday", "day of week, range [0, 6], Monday is 0"},
373 {"tm_yday", "day of year, range [1, 366]"},
374 {"tm_isdst", "1 if summer time is in effect, 0 if not, and -1 if unknown"},
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400375 {"tm_zone", "abbreviation of timezone name"},
376 {"tm_gmtoff", "offset from UTC in seconds"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000377 {0}
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000378};
379
380static PyStructSequence_Desc struct_time_type_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000381 "time.struct_time",
Alexander Belopolsky69f3fd02010-06-05 15:04:51 +0000382 "The time value as returned by gmtime(), localtime(), and strptime(), and\n"
383 " accepted by asctime(), mktime() and strftime(). May be considered as a\n"
384 " sequence of 9 integers.\n\n"
385 " Note that several fields' values are not the same as those defined by\n"
386 " the C language standard for struct tm. For example, the value of the\n"
387 " field tm_year is the actual year, not year - 1900. See individual\n"
388 " fields' descriptions for details.",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000389 struct_time_type_fields,
390 9,
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000391};
Tim Peters9ad4b682002-02-13 05:14:18 +0000392
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000393static int initialized;
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000394static PyTypeObject StructTimeType;
395
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400396
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000397static PyObject *
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -0400398tmtotuple(struct tm *p
399#ifndef HAVE_STRUCT_TM_TM_ZONE
Victor Stinner0d659e52017-04-25 01:22:42 +0200400 , const char *zone, time_t gmtoff
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -0400401#endif
402)
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000403{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000404 PyObject *v = PyStructSequence_New(&StructTimeType);
405 if (v == NULL)
406 return NULL;
Tim Peters9ad4b682002-02-13 05:14:18 +0000407
Christian Heimes217cfd12007-12-02 14:31:20 +0000408#define SET(i,val) PyStructSequence_SET_ITEM(v, i, PyLong_FromLong((long) val))
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000409
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000410 SET(0, p->tm_year + 1900);
411 SET(1, p->tm_mon + 1); /* Want January == 1 */
412 SET(2, p->tm_mday);
413 SET(3, p->tm_hour);
414 SET(4, p->tm_min);
415 SET(5, p->tm_sec);
416 SET(6, (p->tm_wday + 6) % 7); /* Want Monday == 0 */
417 SET(7, p->tm_yday + 1); /* Want January, 1 == 1 */
418 SET(8, p->tm_isdst);
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400419#ifdef HAVE_STRUCT_TM_TM_ZONE
420 PyStructSequence_SET_ITEM(v, 9,
Victor Stinner7ed7aea2018-01-15 10:45:49 +0100421 PyUnicode_DecodeLocale(p->tm_zone, "surrogateescape"));
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400422 SET(10, p->tm_gmtoff);
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -0400423#else
424 PyStructSequence_SET_ITEM(v, 9,
Victor Stinner7ed7aea2018-01-15 10:45:49 +0100425 PyUnicode_DecodeLocale(zone, "surrogateescape"));
Victor Stinner0d659e52017-04-25 01:22:42 +0200426 PyStructSequence_SET_ITEM(v, 10, _PyLong_FromTime_t(gmtoff));
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400427#endif /* HAVE_STRUCT_TM_TM_ZONE */
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000428#undef SET
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000429 if (PyErr_Occurred()) {
430 Py_XDECREF(v);
431 return NULL;
432 }
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000433
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000434 return v;
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000435}
436
Fred Drakef901abd2004-08-03 17:58:55 +0000437/* Parse arg tuple that can contain an optional float-or-None value;
438 format needs to be "|O:name".
439 Returns non-zero on success (parallels PyArg_ParseTuple).
440*/
441static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +0200442parse_time_t_args(PyObject *args, const char *format, time_t *pwhen)
Fred Drakef901abd2004-08-03 17:58:55 +0000443{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000444 PyObject *ot = NULL;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100445 time_t whent;
Fred Drakef901abd2004-08-03 17:58:55 +0000446
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000447 if (!PyArg_ParseTuple(args, format, &ot))
448 return 0;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100449 if (ot == NULL || ot == Py_None) {
450 whent = time(NULL);
451 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000452 else {
Victor Stinner02937aa2015-03-28 05:02:39 +0100453 if (_PyTime_ObjectToTime_t(ot, &whent, _PyTime_ROUND_FLOOR) == -1)
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100454 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000455 }
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100456 *pwhen = whent;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000457 return 1;
Fred Drakef901abd2004-08-03 17:58:55 +0000458}
459
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000460static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000461time_gmtime(PyObject *self, PyObject *args)
Guido van Rossum234f9421993-06-17 12:35:49 +0000462{
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100463 time_t when;
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -0400464 struct tm buf;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100465
466 if (!parse_time_t_args(args, "|O:gmtime", &when))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000467 return NULL;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100468
469 errno = 0;
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -0400470 if (_PyTime_gmtime(when, &buf) != 0)
471 return NULL;
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -0400472#ifdef HAVE_STRUCT_TM_TM_ZONE
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100473 return tmtotuple(&buf);
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -0400474#else
475 return tmtotuple(&buf, "UTC", 0);
476#endif
Guido van Rossum234f9421993-06-17 12:35:49 +0000477}
478
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -0400479#ifndef HAVE_TIMEGM
480static time_t
481timegm(struct tm *p)
482{
483 /* XXX: the following implementation will not work for tm_year < 1970.
484 but it is likely that platforms that don't have timegm do not support
485 negative timestamps anyways. */
486 return p->tm_sec + p->tm_min*60 + p->tm_hour*3600 + p->tm_yday*86400 +
487 (p->tm_year-70)*31536000 + ((p->tm_year-69)/4)*86400 -
488 ((p->tm_year-1)/100)*86400 + ((p->tm_year+299)/400)*86400;
489}
490#endif
491
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000492PyDoc_STRVAR(gmtime_doc,
Christian Heimes9a371592007-12-28 14:08:13 +0000493"gmtime([seconds]) -> (tm_year, tm_mon, tm_mday, tm_hour, tm_min,\n\
Fred Drake193a3f62002-03-12 21:38:49 +0000494 tm_sec, tm_wday, tm_yday, tm_isdst)\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000495\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000496Convert seconds since the Epoch to a time tuple expressing UTC (a.k.a.\n\
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400497GMT). When 'seconds' is not passed in, convert the current time instead.\n\
498\n\
499If the platform supports the tm_gmtoff and tm_zone, they are available as\n\
500attributes only.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000501
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000502static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000503time_localtime(PyObject *self, PyObject *args)
Guido van Rossum234f9421993-06-17 12:35:49 +0000504{
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100505 time_t when;
506 struct tm buf;
507
508 if (!parse_time_t_args(args, "|O:localtime", &when))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000509 return NULL;
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -0400510 if (_PyTime_localtime(when, &buf) != 0)
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100511 return NULL;
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -0400512#ifdef HAVE_STRUCT_TM_TM_ZONE
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100513 return tmtotuple(&buf);
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -0400514#else
515 {
516 struct tm local = buf;
517 char zone[100];
Victor Stinner0d659e52017-04-25 01:22:42 +0200518 time_t gmtoff;
Steve Dowerc3c6f712016-12-14 11:22:05 -0800519 strftime(zone, sizeof(zone), "%Z", &buf);
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -0400520 gmtoff = timegm(&buf) - when;
521 return tmtotuple(&local, zone, gmtoff);
522 }
523#endif
Guido van Rossum234f9421993-06-17 12:35:49 +0000524}
525
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000526PyDoc_STRVAR(localtime_doc,
Christian Heimes9a371592007-12-28 14:08:13 +0000527"localtime([seconds]) -> (tm_year,tm_mon,tm_mday,tm_hour,tm_min,\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000528 tm_sec,tm_wday,tm_yday,tm_isdst)\n\
Martin v. Löwisb3cfc1d2001-12-02 12:27:43 +0000529\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000530Convert seconds since the Epoch to a time tuple expressing local time.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000531When 'seconds' is not passed in, convert the current time instead.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000532
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000533/* Convert 9-item tuple to tm structure. Return 1 on success, set
534 * an exception and return 0 on error.
535 */
Guido van Rossum9e90a671993-06-24 11:10:19 +0000536static int
Oren Milman1d1d3e92017-08-20 18:35:36 +0300537gettmarg(PyObject *args, struct tm *p, const char *format)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000538{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000539 int y;
Guido van Rossumcfbaecc1998-08-25 14:51:12 +0000540
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000541 memset((void *) p, '\0', sizeof(struct tm));
Guido van Rossumb9081262007-08-25 03:14:09 +0000542
Alexander Belopolsky610e5442011-01-06 21:57:06 +0000543 if (!PyTuple_Check(args)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000544 PyErr_SetString(PyExc_TypeError,
545 "Tuple or struct_time argument required");
546 return 0;
547 }
Skip Montanaro41cfce92007-08-24 21:11:00 +0000548
Oren Milman1d1d3e92017-08-20 18:35:36 +0300549 if (!PyArg_ParseTuple(args, format,
Alexander Belopolsky610e5442011-01-06 21:57:06 +0000550 &y, &p->tm_mon, &p->tm_mday,
551 &p->tm_hour, &p->tm_min, &p->tm_sec,
552 &p->tm_wday, &p->tm_yday, &p->tm_isdst))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000553 return 0;
Miss Islington (bot)d5f017b2018-08-25 01:53:00 -0400554
555 if (y < INT_MIN + 1900) {
556 PyErr_SetString(PyExc_OverflowError, "year out of range");
557 return 0;
558 }
559
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000560 p->tm_year = y - 1900;
561 p->tm_mon--;
562 p->tm_wday = (p->tm_wday + 1) % 7;
563 p->tm_yday--;
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400564#ifdef HAVE_STRUCT_TM_TM_ZONE
565 if (Py_TYPE(args) == &StructTimeType) {
566 PyObject *item;
567 item = PyTuple_GET_ITEM(args, 9);
Victor Stinner6e676952017-04-26 13:51:48 +0200568 p->tm_zone = item == Py_None ? NULL : (char*)PyUnicode_AsUTF8(item);
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400569 item = PyTuple_GET_ITEM(args, 10);
570 p->tm_gmtoff = item == Py_None ? 0 : PyLong_AsLong(item);
571 if (PyErr_Occurred())
572 return 0;
573 }
574#endif /* HAVE_STRUCT_TM_TM_ZONE */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000575 return 1;
Guido van Rossum9e90a671993-06-24 11:10:19 +0000576}
577
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000578/* Check values of the struct tm fields before it is passed to strftime() and
579 * asctime(). Return 1 if all values are valid, otherwise set an exception
580 * and returns 0.
581 */
Victor Stinneref128102010-10-07 01:00:52 +0000582static int
583checktm(struct tm* buf)
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000584{
Victor Stinneref128102010-10-07 01:00:52 +0000585 /* Checks added to make sure strftime() and asctime() does not crash Python by
586 indexing blindly into some array for a textual representation
587 by some bad index (fixes bug #897625 and #6608).
588
589 Also support values of zero from Python code for arguments in which
590 that is out of range by forcing that value to the lowest value that
591 is valid (fixed bug #1520914).
592
593 Valid ranges based on what is allowed in struct tm:
594
595 - tm_year: [0, max(int)] (1)
596 - tm_mon: [0, 11] (2)
597 - tm_mday: [1, 31]
598 - tm_hour: [0, 23]
599 - tm_min: [0, 59]
600 - tm_sec: [0, 60]
601 - tm_wday: [0, 6] (1)
602 - tm_yday: [0, 365] (2)
603 - tm_isdst: [-max(int), max(int)]
604
605 (1) gettmarg() handles bounds-checking.
606 (2) Python's acceptable range is one greater than the range in C,
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000607 thus need to check against automatic decrement by gettmarg().
608 */
609 if (buf->tm_mon == -1)
610 buf->tm_mon = 0;
611 else if (buf->tm_mon < 0 || buf->tm_mon > 11) {
612 PyErr_SetString(PyExc_ValueError, "month out of range");
613 return 0;
614 }
615 if (buf->tm_mday == 0)
616 buf->tm_mday = 1;
617 else if (buf->tm_mday < 0 || buf->tm_mday > 31) {
618 PyErr_SetString(PyExc_ValueError, "day of month out of range");
619 return 0;
620 }
621 if (buf->tm_hour < 0 || buf->tm_hour > 23) {
622 PyErr_SetString(PyExc_ValueError, "hour out of range");
623 return 0;
624 }
625 if (buf->tm_min < 0 || buf->tm_min > 59) {
626 PyErr_SetString(PyExc_ValueError, "minute out of range");
627 return 0;
628 }
629 if (buf->tm_sec < 0 || buf->tm_sec > 61) {
630 PyErr_SetString(PyExc_ValueError, "seconds out of range");
631 return 0;
632 }
633 /* tm_wday does not need checking of its upper-bound since taking
634 ``% 7`` in gettmarg() automatically restricts the range. */
635 if (buf->tm_wday < 0) {
636 PyErr_SetString(PyExc_ValueError, "day of week out of range");
637 return 0;
638 }
639 if (buf->tm_yday == -1)
640 buf->tm_yday = 0;
641 else if (buf->tm_yday < 0 || buf->tm_yday > 365) {
642 PyErr_SetString(PyExc_ValueError, "day of year out of range");
643 return 0;
644 }
645 return 1;
646}
647
Victor Stinnerc1f32ca2011-10-14 02:36:13 +0200648#ifdef MS_WINDOWS
649 /* wcsftime() doesn't format correctly time zones, see issue #10653 */
650# undef HAVE_WCSFTIME
651#endif
Alexander Belopolskycf774542012-10-02 18:39:16 -0400652#define STRFTIME_FORMAT_CODES \
653"Commonly used format codes:\n\
654\n\
655%Y Year with century as a decimal number.\n\
656%m Month as a decimal number [01,12].\n\
657%d Day of the month as a decimal number [01,31].\n\
658%H Hour (24-hour clock) as a decimal number [00,23].\n\
659%M Minute as a decimal number [00,59].\n\
660%S Second as a decimal number [00,61].\n\
661%z Time zone offset from UTC.\n\
662%a Locale's abbreviated weekday name.\n\
663%A Locale's full weekday name.\n\
664%b Locale's abbreviated month name.\n\
665%B Locale's full month name.\n\
666%c Locale's appropriate date and time representation.\n\
667%I Hour (12-hour clock) as a decimal number [01,12].\n\
668%p Locale's equivalent of either AM or PM.\n\
669\n\
670Other codes may be available on your platform. See documentation for\n\
671the C library strftime function.\n"
Victor Stinnerc1f32ca2011-10-14 02:36:13 +0200672
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000673#ifdef HAVE_STRFTIME
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000674#ifdef HAVE_WCSFTIME
675#define time_char wchar_t
676#define format_time wcsftime
677#define time_strlen wcslen
678#else
679#define time_char char
680#define format_time strftime
681#define time_strlen strlen
682#endif
683
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000684static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000685time_strftime(PyObject *self, PyObject *args)
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000686{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000687 PyObject *tup = NULL;
688 struct tm buf;
689 const time_char *fmt;
Victor Stinnerb2904782010-09-29 10:34:19 +0000690#ifdef HAVE_WCSFTIME
691 wchar_t *format;
692#else
693 PyObject *format;
694#endif
Victor Stinneref128102010-10-07 01:00:52 +0000695 PyObject *format_arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000696 size_t fmtlen, buflen;
Victor Stinnerb2904782010-09-29 10:34:19 +0000697 time_char *outbuf = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000698 size_t i;
Victor Stinnerb2904782010-09-29 10:34:19 +0000699 PyObject *ret = NULL;
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000700
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000701 memset((void *) &buf, '\0', sizeof(buf));
Guido van Rossum1f41f841998-04-27 19:04:26 +0000702
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000703 /* Will always expect a unicode string to be passed as format.
704 Given that there's no str type anymore in py3k this seems safe.
705 */
Victor Stinneref128102010-10-07 01:00:52 +0000706 if (!PyArg_ParseTuple(args, "U|O:strftime", &format_arg, &tup))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000707 return NULL;
Thomas Woutersfe385252001-01-19 23:16:56 +0000708
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000709 if (tup == NULL) {
710 time_t tt = time(NULL);
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -0400711 if (_PyTime_localtime(tt, &buf) != 0)
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100712 return NULL;
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000713 }
Oren Milman1d1d3e92017-08-20 18:35:36 +0300714 else if (!gettmarg(tup, &buf,
715 "iiiiiiiii;strftime(): illegal time tuple argument") ||
716 !checktm(&buf))
717 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000718 return NULL;
Oren Milman1d1d3e92017-08-20 18:35:36 +0300719 }
Guido van Rossum10b164a2001-09-25 13:59:01 +0000720
Victor Stinner36b82d82013-06-25 02:33:53 +0200721#if defined(_MSC_VER) || defined(sun) || defined(_AIX)
Victor Stinner73ea29c2011-01-08 01:56:31 +0000722 if (buf.tm_year + 1900 < 1 || 9999 < buf.tm_year + 1900) {
Victor Stinner6f0e4f92011-03-21 02:14:53 +0100723 PyErr_SetString(PyExc_ValueError,
724 "strftime() requires year in [1; 9999]");
Alexander Belopolsky0dd06f42011-01-08 01:23:02 +0000725 return NULL;
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000726 }
Victor Stinner73ea29c2011-01-08 01:56:31 +0000727#endif
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000728
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000729 /* Normalize tm_isdst just in case someone foolishly implements %Z
730 based on the assumption that tm_isdst falls within the range of
731 [-1, 1] */
732 if (buf.tm_isdst < -1)
733 buf.tm_isdst = -1;
734 else if (buf.tm_isdst > 1)
735 buf.tm_isdst = 1;
Brett Cannond1080a32004-03-02 04:38:10 +0000736
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000737#ifdef HAVE_WCSFTIME
Victor Stinnerbeb4135b2010-10-07 01:02:42 +0000738 format = PyUnicode_AsWideCharString(format_arg, NULL);
Victor Stinnerb2904782010-09-29 10:34:19 +0000739 if (format == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000740 return NULL;
Victor Stinnerb2904782010-09-29 10:34:19 +0000741 fmt = format;
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000742#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000743 /* Convert the unicode string to an ascii one */
Victor Stinner1b579672011-12-17 05:47:23 +0100744 format = PyUnicode_EncodeLocale(format_arg, "surrogateescape");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000745 if (format == NULL)
746 return NULL;
747 fmt = PyBytes_AS_STRING(format);
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000748#endif
Amaury Forgeot d'Arcb5be6d42009-03-02 23:52:57 +0000749
Stefan Krah4aea7d32012-02-27 16:30:26 +0100750#if defined(MS_WINDOWS) && !defined(HAVE_WCSFTIME)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000751 /* check that the format string contains only valid directives */
Steve Dowere5b58952015-09-06 19:20:51 -0700752 for (outbuf = strchr(fmt, '%');
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000753 outbuf != NULL;
Victor Stinner5a3ff792011-10-16 19:08:23 +0200754 outbuf = strchr(outbuf+2, '%'))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000755 {
Steve Dowere5b58952015-09-06 19:20:51 -0700756 if (outbuf[1] == '#')
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000757 ++outbuf; /* not documented by python, */
Steve Dowere5b58952015-09-06 19:20:51 -0700758 if (outbuf[1] == '\0')
759 break;
760 if ((outbuf[1] == 'y') && buf.tm_year < 0) {
Tim Golden6e51b8f2013-11-12 12:36:54 +0000761 PyErr_SetString(PyExc_ValueError,
762 "format %y requires year >= 1900 on Windows");
763 Py_DECREF(format);
764 return NULL;
765 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000766 }
Victor Stinner93965f72013-11-23 14:59:33 +0100767#elif (defined(_AIX) || defined(sun)) && defined(HAVE_WCSFTIME)
Steve Dowere5b58952015-09-06 19:20:51 -0700768 for (outbuf = wcschr(fmt, '%');
Victor Stinner55329f82013-11-17 23:39:21 +0100769 outbuf != NULL;
770 outbuf = wcschr(outbuf+2, '%'))
771 {
Steve Dowere5b58952015-09-06 19:20:51 -0700772 if (outbuf[1] == L'\0')
773 break;
Victor Stinner55329f82013-11-17 23:39:21 +0100774 /* Issue #19634: On AIX, wcsftime("y", (1899, 1, 1, 0, 0, 0, 0, 0, 0))
775 returns "0/" instead of "99" */
776 if (outbuf[1] == L'y' && buf.tm_year < 0) {
777 PyErr_SetString(PyExc_ValueError,
778 "format %y requires year >= 1900 on AIX");
Miss Islington (bot)975f3cb2018-09-21 00:41:50 -0700779 PyMem_Free(format);
Victor Stinner55329f82013-11-17 23:39:21 +0100780 return NULL;
781 }
782 }
Amaury Forgeot d'Arcb5be6d42009-03-02 23:52:57 +0000783#endif
784
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000785 fmtlen = time_strlen(fmt);
Guido van Rossumc222ec21999-02-23 00:00:10 +0000786
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000787 /* I hate these functions that presume you know how big the output
788 * will be ahead of time...
789 */
790 for (i = 1024; ; i += i) {
791 outbuf = (time_char *)PyMem_Malloc(i*sizeof(time_char));
792 if (outbuf == NULL) {
Victor Stinnerb2904782010-09-29 10:34:19 +0000793 PyErr_NoMemory();
794 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000795 }
Steve Dower57ab1cd2015-09-22 14:51:42 -0700796#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
797 errno = 0;
798#endif
Steve Dowerd9ef74e2015-05-22 15:08:34 -0700799 _Py_BEGIN_SUPPRESS_IPH
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000800 buflen = format_time(outbuf, i, fmt, &buf);
Steve Dowerd9ef74e2015-05-22 15:08:34 -0700801 _Py_END_SUPPRESS_IPH
Victor Stinner136ea492011-12-17 22:37:18 +0100802#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
Steve Dower97cded92015-09-08 19:12:51 -0700803 /* VisualStudio .NET 2005 does this properly */
804 if (buflen == 0 && errno == EINVAL) {
805 PyErr_SetString(PyExc_ValueError, "Invalid format string");
806 PyMem_Free(outbuf);
807 break;
808 }
Victor Stinner136ea492011-12-17 22:37:18 +0100809#endif
Steve Dower97cded92015-09-08 19:12:51 -0700810 if (buflen > 0 || i >= 256 * fmtlen) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000811 /* If the buffer is 256 times as long as the format,
812 it's probably not failing for lack of room!
813 More likely, the format yields an empty result,
814 e.g. an empty format, or %Z when the timezone
815 is unknown. */
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000816#ifdef HAVE_WCSFTIME
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000817 ret = PyUnicode_FromWideChar(outbuf, buflen);
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000818#else
Victor Stinner7ed7aea2018-01-15 10:45:49 +0100819 ret = PyUnicode_DecodeLocaleAndSize(outbuf, buflen, "surrogateescape");
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000820#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000821 PyMem_Free(outbuf);
Victor Stinnerb2904782010-09-29 10:34:19 +0000822 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000823 }
824 PyMem_Free(outbuf);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000825 }
Victor Stinnerb2904782010-09-29 10:34:19 +0000826#ifdef HAVE_WCSFTIME
827 PyMem_Free(format);
828#else
829 Py_DECREF(format);
830#endif
831 return ret;
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000832}
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000833
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000834#undef time_char
835#undef format_time
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000836PyDoc_STRVAR(strftime_doc,
Thomas Woutersfe385252001-01-19 23:16:56 +0000837"strftime(format[, tuple]) -> string\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000838\n\
839Convert a time tuple to a string according to a format specification.\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000840See the library reference manual for formatting codes. When the time tuple\n\
Alexander Belopolskycf774542012-10-02 18:39:16 -0400841is not present, current time as returned by localtime() is used.\n\
842\n" STRFTIME_FORMAT_CODES);
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000843#endif /* HAVE_STRFTIME */
844
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000845static PyObject *
846time_strptime(PyObject *self, PyObject *args)
847{
Victor Stinnerdbe28d22016-12-09 00:38:53 +0100848 PyObject *module, *func, *result;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200849 _Py_IDENTIFIER(_strptime_time);
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000850
Victor Stinnerdbe28d22016-12-09 00:38:53 +0100851 module = PyImport_ImportModuleNoBlock("_strptime");
852 if (!module)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000853 return NULL;
Victor Stinnerdbe28d22016-12-09 00:38:53 +0100854
855 func = _PyObject_GetAttrId(module, &PyId__strptime_time);
856 Py_DECREF(module);
857 if (!func) {
858 return NULL;
859 }
860
861 result = PyObject_Call(func, args, NULL);
862 Py_DECREF(func);
863 return result;
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000864}
865
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000866
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000867PyDoc_STRVAR(strptime_doc,
Brett Cannon20def8b2003-07-01 05:16:08 +0000868"strptime(string, format) -> struct_time\n\
Martin v. Löwisb3cfc1d2001-12-02 12:27:43 +0000869\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000870Parse a string to a time tuple according to a format specification.\n\
Alexander Belopolskycf774542012-10-02 18:39:16 -0400871See the library reference manual for formatting codes (same as\n\
872strftime()).\n\
873\n" STRFTIME_FORMAT_CODES);
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000874
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000875static PyObject *
876_asctime(struct tm *timeptr)
877{
878 /* Inspired by Open Group reference implementation available at
879 * http://pubs.opengroup.org/onlinepubs/009695399/functions/asctime.html */
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200880 static const char wday_name[7][4] = {
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000881 "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
882 };
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200883 static const char mon_name[12][4] = {
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000884 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
885 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
886 };
Victor Stinner499dfcf2011-03-21 13:26:24 +0100887 return PyUnicode_FromFormat(
888 "%s %s%3d %.2d:%.2d:%.2d %d",
889 wday_name[timeptr->tm_wday],
890 mon_name[timeptr->tm_mon],
891 timeptr->tm_mday, timeptr->tm_hour,
892 timeptr->tm_min, timeptr->tm_sec,
893 1900 + timeptr->tm_year);
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000894}
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000895
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000896static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000897time_asctime(PyObject *self, PyObject *args)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000898{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000899 PyObject *tup = NULL;
900 struct tm buf;
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000901
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000902 if (!PyArg_UnpackTuple(args, "asctime", 0, 1, &tup))
903 return NULL;
904 if (tup == NULL) {
905 time_t tt = time(NULL);
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -0400906 if (_PyTime_localtime(tt, &buf) != 0)
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100907 return NULL;
Oren Milman1d1d3e92017-08-20 18:35:36 +0300908 }
909 else if (!gettmarg(tup, &buf,
910 "iiiiiiiii;asctime(): illegal time tuple argument") ||
911 !checktm(&buf))
912 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000913 return NULL;
Oren Milman1d1d3e92017-08-20 18:35:36 +0300914 }
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000915 return _asctime(&buf);
Guido van Rossum9e90a671993-06-24 11:10:19 +0000916}
917
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000918PyDoc_STRVAR(asctime_doc,
Thomas Woutersfe385252001-01-19 23:16:56 +0000919"asctime([tuple]) -> string\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000920\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000921Convert a time tuple to a string, e.g. 'Sat Jun 06 16:26:11 1998'.\n\
922When the time tuple is not present, current time as returned by localtime()\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000923is used.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000924
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000925static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000926time_ctime(PyObject *self, PyObject *args)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000927{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000928 time_t tt;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100929 struct tm buf;
930 if (!parse_time_t_args(args, "|O:ctime", &tt))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000931 return NULL;
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -0400932 if (_PyTime_localtime(tt, &buf) != 0)
Alexander Belopolsky5da468f2011-01-04 17:15:52 +0000933 return NULL;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100934 return _asctime(&buf);
Guido van Rossum9e90a671993-06-24 11:10:19 +0000935}
936
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000937PyDoc_STRVAR(ctime_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000938"ctime(seconds) -> string\n\
939\n\
940Convert a time in seconds since the Epoch to a string in local time.\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000941This is equivalent to asctime(localtime(seconds)). When the time tuple is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000942not present, current time as returned by localtime() is used.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000943
Guido van Rossum60cd8131998-03-06 17:16:21 +0000944#ifdef HAVE_MKTIME
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000945static PyObject *
Victor Stinner4195b5c2012-02-08 23:03:19 +0100946time_mktime(PyObject *self, PyObject *tup)
Guido van Rossum234f9421993-06-17 12:35:49 +0000947{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000948 struct tm buf;
949 time_t tt;
Oren Milman1d1d3e92017-08-20 18:35:36 +0300950 if (!gettmarg(tup, &buf,
951 "iiiiiiiii;mktime(): illegal time tuple argument"))
952 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000953 return NULL;
Oren Milman1d1d3e92017-08-20 18:35:36 +0300954 }
Victor Stinner1ac42612014-02-21 09:27:17 +0100955#ifdef _AIX
956 /* year < 1902 or year > 2037 */
957 if (buf.tm_year < 2 || buf.tm_year > 137) {
958 /* Issue #19748: On AIX, mktime() doesn't report overflow error for
959 * timestamp < -2^31 or timestamp > 2**31-1. */
960 PyErr_SetString(PyExc_OverflowError,
961 "mktime argument out of range");
962 return NULL;
963 }
964#else
Alexander Belopolskyb7d40d12011-01-11 01:21:25 +0000965 buf.tm_wday = -1; /* sentinel; original value ignored */
Victor Stinner1ac42612014-02-21 09:27:17 +0100966#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000967 tt = mktime(&buf);
Alexander Belopolskyb7d40d12011-01-11 01:21:25 +0000968 /* Return value of -1 does not necessarily mean an error, but tm_wday
Ezio Melotti13925002011-03-16 11:05:33 +0200969 * cannot remain set to -1 if mktime succeeded. */
Victor Stinner93037492013-06-25 22:54:35 +0200970 if (tt == (time_t)(-1)
971#ifndef _AIX
972 /* Return value of -1 does not necessarily mean an error, but
973 * tm_wday cannot remain set to -1 if mktime succeeded. */
974 && buf.tm_wday == -1
975#else
976 /* on AIX, tm_wday is always sets, even on error */
977#endif
978 )
979 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000980 PyErr_SetString(PyExc_OverflowError,
981 "mktime argument out of range");
982 return NULL;
983 }
Victor Stinner4195b5c2012-02-08 23:03:19 +0100984 return PyFloat_FromDouble((double)tt);
Guido van Rossum234f9421993-06-17 12:35:49 +0000985}
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000986
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000987PyDoc_STRVAR(mktime_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000988"mktime(tuple) -> floating point number\n\
989\n\
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400990Convert a time tuple in local time to seconds since the Epoch.\n\
991Note that mktime(gmtime(0)) will not generally return zero for most\n\
992time zones; instead the returned value will either be equal to that\n\
993of the timezone or altzone attributes on the time module.");
Guido van Rossum60cd8131998-03-06 17:16:21 +0000994#endif /* HAVE_MKTIME */
Guido van Rossum234f9421993-06-17 12:35:49 +0000995
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000996#ifdef HAVE_WORKING_TZSET
Victor Stinner38c06d92018-12-01 01:24:21 +0100997static int PyInit_timezone(PyObject *module);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000998
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000999static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001000time_tzset(PyObject *self, PyObject *unused)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001001{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001002 PyObject* m;
Fred Drake9bb74322002-04-01 14:49:59 +00001003
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001004 m = PyImport_ImportModuleNoBlock("time");
1005 if (m == NULL) {
1006 return NULL;
1007 }
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001008
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001009 tzset();
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001010
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001011 /* Reset timezone, altzone, daylight and tzname */
Victor Stinner38c06d92018-12-01 01:24:21 +01001012 if (PyInit_timezone(m) < 0) {
1013 return NULL;
1014 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001015 Py_DECREF(m);
Victor Stinner2ff51b82013-07-17 21:42:45 +02001016 if (PyErr_Occurred())
1017 return NULL;
Tim Peters1b6f7a92004-06-20 02:50:16 +00001018
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001019 Py_RETURN_NONE;
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001020}
1021
1022PyDoc_STRVAR(tzset_doc,
R. David Murray4d55bf92010-12-14 00:55:46 +00001023"tzset()\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001024\n\
1025Initialize, or reinitialize, the local timezone to the value stored in\n\
1026os.environ['TZ']. The TZ environment variable should be specified in\n\
Neal Norwitzdc8e1942004-07-20 22:34:37 +00001027standard Unix timezone format as documented in the tzset man page\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001028(eg. 'US/Eastern', 'Europe/Amsterdam'). Unknown timezones will silently\n\
1029fall back to UTC. If the TZ environment variable is not set, the local\n\
1030timezone is set to the systems best guess of wallclock time.\n\
1031Changing the TZ environment variable without calling tzset *may* change\n\
1032the local timezone used by methods such as localtime, but this behaviour\n\
1033should not be relied on.");
1034#endif /* HAVE_WORKING_TZSET */
1035
Victor Stinnerae586492014-09-02 23:18:25 +02001036static PyObject *
Victor Stinnerec895392012-04-29 02:41:27 +02001037time_monotonic(PyObject *self, PyObject *unused)
Victor Stinner071eca32012-03-15 01:17:09 +01001038{
Victor Stinnerc29b5852017-11-02 07:28:27 -07001039 _PyTime_t t = _PyTime_GetMonotonicClock();
1040 return _PyFloat_FromPyTime(t);
Victor Stinner071eca32012-03-15 01:17:09 +01001041}
1042
Victor Stinnerec895392012-04-29 02:41:27 +02001043PyDoc_STRVAR(monotonic_doc,
1044"monotonic() -> float\n\
Victor Stinner8b302012012-02-07 23:29:46 +01001045\n\
Victor Stinnerec895392012-04-29 02:41:27 +02001046Monotonic clock, cannot go backward.");
Victor Stinnerec919cc2012-03-15 00:58:32 +01001047
Victor Stinnerec895392012-04-29 02:41:27 +02001048static PyObject *
Victor Stinnerc29b5852017-11-02 07:28:27 -07001049time_monotonic_ns(PyObject *self, PyObject *unused)
1050{
1051 _PyTime_t t = _PyTime_GetMonotonicClock();
1052 return _PyTime_AsNanosecondsObject(t);
1053}
1054
1055PyDoc_STRVAR(monotonic_ns_doc,
1056"monotonic_ns() -> int\n\
1057\n\
1058Monotonic clock, cannot go backward, as nanoseconds.");
1059
1060static PyObject *
Victor Stinnerec895392012-04-29 02:41:27 +02001061time_perf_counter(PyObject *self, PyObject *unused)
1062{
1063 return perf_counter(NULL);
1064}
1065
1066PyDoc_STRVAR(perf_counter_doc,
1067"perf_counter() -> float\n\
1068\n\
1069Performance counter for benchmarking.");
1070
Victor Stinnerc29b5852017-11-02 07:28:27 -07001071static PyObject *
1072time_perf_counter_ns(PyObject *self, PyObject *unused)
1073{
1074 _PyTime_t t = _PyTime_GetPerfCounter();
1075 return _PyTime_AsNanosecondsObject(t);
1076}
1077
1078PyDoc_STRVAR(perf_counter_ns_doc,
1079"perf_counter_ns() -> int\n\
1080\n\
1081Performance counter for benchmarking as nanoseconds.");
1082
1083static int
1084_PyTime_GetProcessTimeWithInfo(_PyTime_t *tp, _Py_clock_info_t *info)
Victor Stinnerec895392012-04-29 02:41:27 +02001085{
1086#if defined(MS_WINDOWS)
1087 HANDLE process;
1088 FILETIME creation_time, exit_time, kernel_time, user_time;
1089 ULARGE_INTEGER large;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001090 _PyTime_t ktime, utime, t;
Victor Stinnerec895392012-04-29 02:41:27 +02001091 BOOL ok;
1092
1093 process = GetCurrentProcess();
Victor Stinnerc29b5852017-11-02 07:28:27 -07001094 ok = GetProcessTimes(process, &creation_time, &exit_time,
1095 &kernel_time, &user_time);
1096 if (!ok) {
1097 PyErr_SetFromWindowsErr(0);
1098 return -1;
1099 }
Victor Stinnerec895392012-04-29 02:41:27 +02001100
Victor Stinnerec895392012-04-29 02:41:27 +02001101 if (info) {
1102 info->implementation = "GetProcessTimes()";
1103 info->resolution = 1e-7;
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001104 info->monotonic = 1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001105 info->adjustable = 0;
Victor Stinnerec895392012-04-29 02:41:27 +02001106 }
Victor Stinnerc29b5852017-11-02 07:28:27 -07001107
1108 large.u.LowPart = kernel_time.dwLowDateTime;
1109 large.u.HighPart = kernel_time.dwHighDateTime;
1110 ktime = large.QuadPart;
1111
1112 large.u.LowPart = user_time.dwLowDateTime;
1113 large.u.HighPart = user_time.dwHighDateTime;
1114 utime = large.QuadPart;
1115
1116 /* ktime and utime have a resolution of 100 nanoseconds */
1117 t = _PyTime_FromNanoseconds((ktime + utime) * 100);
1118 *tp = t;
1119 return 0;
Victor Stinnerec895392012-04-29 02:41:27 +02001120#else
1121
Victor Stinnerc29b5852017-11-02 07:28:27 -07001122 /* clock_gettime */
Victor Stinnerec895392012-04-29 02:41:27 +02001123#if defined(HAVE_CLOCK_GETTIME) \
1124 && (defined(CLOCK_PROCESS_CPUTIME_ID) || defined(CLOCK_PROF))
Victor Stinnerc29b5852017-11-02 07:28:27 -07001125 struct timespec ts;
Victor Stinnerec895392012-04-29 02:41:27 +02001126#ifdef CLOCK_PROF
1127 const clockid_t clk_id = CLOCK_PROF;
1128 const char *function = "clock_gettime(CLOCK_PROF)";
1129#else
1130 const clockid_t clk_id = CLOCK_PROCESS_CPUTIME_ID;
1131 const char *function = "clock_gettime(CLOCK_PROCESS_CPUTIME_ID)";
1132#endif
1133
Victor Stinnerc29b5852017-11-02 07:28:27 -07001134 if (clock_gettime(clk_id, &ts) == 0) {
Victor Stinnerec895392012-04-29 02:41:27 +02001135 if (info) {
1136 struct timespec res;
1137 info->implementation = function;
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001138 info->monotonic = 1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001139 info->adjustable = 0;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001140 if (clock_getres(clk_id, &res)) {
1141 PyErr_SetFromErrno(PyExc_OSError);
1142 return -1;
1143 }
1144 info->resolution = res.tv_sec + res.tv_nsec * 1e-9;
Victor Stinnerec895392012-04-29 02:41:27 +02001145 }
Victor Stinnerc29b5852017-11-02 07:28:27 -07001146
1147 if (_PyTime_FromTimespec(tp, &ts) < 0) {
1148 return -1;
1149 }
1150 return 0;
Victor Stinnerec895392012-04-29 02:41:27 +02001151 }
1152#endif
1153
Victor Stinnerc29b5852017-11-02 07:28:27 -07001154 /* getrusage(RUSAGE_SELF) */
Victor Stinnerec895392012-04-29 02:41:27 +02001155#if defined(HAVE_SYS_RESOURCE_H)
Victor Stinnerc29b5852017-11-02 07:28:27 -07001156 struct rusage ru;
1157
Victor Stinnerec895392012-04-29 02:41:27 +02001158 if (getrusage(RUSAGE_SELF, &ru) == 0) {
Victor Stinnerc29b5852017-11-02 07:28:27 -07001159 _PyTime_t utime, stime;
1160
Victor Stinnerec895392012-04-29 02:41:27 +02001161 if (info) {
1162 info->implementation = "getrusage(RUSAGE_SELF)";
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001163 info->monotonic = 1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001164 info->adjustable = 0;
Victor Stinnerec895392012-04-29 02:41:27 +02001165 info->resolution = 1e-6;
1166 }
Victor Stinnerc29b5852017-11-02 07:28:27 -07001167
1168 if (_PyTime_FromTimeval(&utime, &ru.ru_utime) < 0) {
1169 return -1;
1170 }
1171 if (_PyTime_FromTimeval(&stime, &ru.ru_stime) < 0) {
1172 return -1;
1173 }
1174
1175 _PyTime_t total = utime + utime;
1176 *tp = total;
1177 return 0;
Victor Stinnerec895392012-04-29 02:41:27 +02001178 }
1179#endif
1180
Victor Stinnerc29b5852017-11-02 07:28:27 -07001181 /* times() */
Victor Stinnerec895392012-04-29 02:41:27 +02001182#ifdef HAVE_TIMES
Victor Stinnerc29b5852017-11-02 07:28:27 -07001183 struct tms t;
1184
Victor Stinnerec895392012-04-29 02:41:27 +02001185 if (times(&t) != (clock_t)-1) {
Victor Stinnerc29b5852017-11-02 07:28:27 -07001186 static long ticks_per_second = -1;
Victor Stinnerec895392012-04-29 02:41:27 +02001187
1188 if (ticks_per_second == -1) {
Victor Stinnerc29b5852017-11-02 07:28:27 -07001189 long freq;
Victor Stinnerec895392012-04-29 02:41:27 +02001190#if defined(HAVE_SYSCONF) && defined(_SC_CLK_TCK)
Victor Stinnerc29b5852017-11-02 07:28:27 -07001191 freq = sysconf(_SC_CLK_TCK);
1192 if (freq < 1) {
1193 freq = -1;
1194 }
Victor Stinnerec895392012-04-29 02:41:27 +02001195#elif defined(HZ)
Victor Stinnerc29b5852017-11-02 07:28:27 -07001196 freq = HZ;
Victor Stinnerec895392012-04-29 02:41:27 +02001197#else
Victor Stinnerc29b5852017-11-02 07:28:27 -07001198 freq = 60; /* magic fallback value; may be bogus */
Victor Stinnerec895392012-04-29 02:41:27 +02001199#endif
Victor Stinnerc29b5852017-11-02 07:28:27 -07001200
1201 if (freq != -1) {
1202 /* check that _PyTime_MulDiv(t, SEC_TO_NS, ticks_per_second)
1203 cannot overflow below */
Miss Islington (bot)7df80492018-02-09 07:56:34 -08001204#if LONG_MAX > _PyTime_MAX / SEC_TO_NS
Victor Stinnerc29b5852017-11-02 07:28:27 -07001205 if ((_PyTime_t)freq > _PyTime_MAX / SEC_TO_NS) {
1206 PyErr_SetString(PyExc_OverflowError,
1207 "_SC_CLK_TCK is too large");
1208 return -1;
1209 }
Miss Islington (bot)7df80492018-02-09 07:56:34 -08001210#endif
Victor Stinnerc29b5852017-11-02 07:28:27 -07001211
1212 ticks_per_second = freq;
1213 }
Victor Stinnerec895392012-04-29 02:41:27 +02001214 }
1215
1216 if (ticks_per_second != -1) {
Victor Stinnerec895392012-04-29 02:41:27 +02001217 if (info) {
1218 info->implementation = "times()";
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001219 info->monotonic = 1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001220 info->adjustable = 0;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001221 info->resolution = 1.0 / (double)ticks_per_second;
Victor Stinnerec895392012-04-29 02:41:27 +02001222 }
Victor Stinnerc29b5852017-11-02 07:28:27 -07001223
1224 _PyTime_t total;
1225 total = _PyTime_MulDiv(t.tms_utime, SEC_TO_NS, ticks_per_second);
1226 total += _PyTime_MulDiv(t.tms_stime, SEC_TO_NS, ticks_per_second);
1227 *tp = total;
1228 return 0;
Victor Stinnerec895392012-04-29 02:41:27 +02001229 }
1230 }
1231#endif
1232
Victor Stinnerc29b5852017-11-02 07:28:27 -07001233 /* clock */
Victor Stinner53e22bf2016-07-08 17:55:01 +02001234 /* Currently, Python 3 requires clock() to build: see issue #22624 */
Victor Stinnerc29b5852017-11-02 07:28:27 -07001235 return _PyTime_GetClockWithInfo(tp, info);
Victor Stinnerec895392012-04-29 02:41:27 +02001236#endif
1237}
1238
1239static PyObject *
1240time_process_time(PyObject *self, PyObject *unused)
1241{
Victor Stinnerc29b5852017-11-02 07:28:27 -07001242 _PyTime_t t;
1243 if (_PyTime_GetProcessTimeWithInfo(&t, NULL) < 0) {
1244 return NULL;
1245 }
1246 return _PyFloat_FromPyTime(t);
Victor Stinnerec895392012-04-29 02:41:27 +02001247}
1248
1249PyDoc_STRVAR(process_time_doc,
1250"process_time() -> float\n\
1251\n\
1252Process time for profiling: sum of the kernel and user-space CPU time.");
1253
Victor Stinnerc29b5852017-11-02 07:28:27 -07001254static PyObject *
1255time_process_time_ns(PyObject *self, PyObject *unused)
1256{
1257 _PyTime_t t;
1258 if (_PyTime_GetProcessTimeWithInfo(&t, NULL) < 0) {
1259 return NULL;
1260 }
1261 return _PyTime_AsNanosecondsObject(t);
1262}
1263
1264PyDoc_STRVAR(process_time_ns_doc,
1265"process_time() -> int\n\
1266\n\
1267Process time for profiling as nanoseconds:\n\
1268sum of the kernel and user-space CPU time.");
1269
Victor Stinnerec895392012-04-29 02:41:27 +02001270
Antoine Pitrou4bd41c92017-11-15 22:52:21 +01001271#if defined(MS_WINDOWS)
1272#define HAVE_THREAD_TIME
1273static int
1274_PyTime_GetThreadTimeWithInfo(_PyTime_t *tp, _Py_clock_info_t *info)
1275{
1276 HANDLE thread;
1277 FILETIME creation_time, exit_time, kernel_time, user_time;
1278 ULARGE_INTEGER large;
1279 _PyTime_t ktime, utime, t;
1280 BOOL ok;
1281
1282 thread = GetCurrentThread();
1283 ok = GetThreadTimes(thread, &creation_time, &exit_time,
1284 &kernel_time, &user_time);
1285 if (!ok) {
1286 PyErr_SetFromWindowsErr(0);
1287 return -1;
1288 }
1289
1290 if (info) {
1291 info->implementation = "GetThreadTimes()";
1292 info->resolution = 1e-7;
1293 info->monotonic = 1;
1294 info->adjustable = 0;
1295 }
1296
1297 large.u.LowPart = kernel_time.dwLowDateTime;
1298 large.u.HighPart = kernel_time.dwHighDateTime;
1299 ktime = large.QuadPart;
1300
1301 large.u.LowPart = user_time.dwLowDateTime;
1302 large.u.HighPart = user_time.dwHighDateTime;
1303 utime = large.QuadPart;
1304
1305 /* ktime and utime have a resolution of 100 nanoseconds */
1306 t = _PyTime_FromNanoseconds((ktime + utime) * 100);
1307 *tp = t;
1308 return 0;
1309}
1310
1311#elif defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_PROCESS_CPUTIME_ID)
1312#define HAVE_THREAD_TIME
1313static int
1314_PyTime_GetThreadTimeWithInfo(_PyTime_t *tp, _Py_clock_info_t *info)
1315{
1316 struct timespec ts;
1317 const clockid_t clk_id = CLOCK_THREAD_CPUTIME_ID;
1318 const char *function = "clock_gettime(CLOCK_THREAD_CPUTIME_ID)";
1319
1320 if (clock_gettime(clk_id, &ts)) {
1321 PyErr_SetFromErrno(PyExc_OSError);
1322 return -1;
1323 }
1324 if (info) {
1325 struct timespec res;
1326 info->implementation = function;
1327 info->monotonic = 1;
1328 info->adjustable = 0;
1329 if (clock_getres(clk_id, &res)) {
1330 PyErr_SetFromErrno(PyExc_OSError);
1331 return -1;
1332 }
1333 info->resolution = res.tv_sec + res.tv_nsec * 1e-9;
1334 }
1335
1336 if (_PyTime_FromTimespec(tp, &ts) < 0) {
1337 return -1;
1338 }
1339 return 0;
1340}
1341#endif
1342
1343#ifdef HAVE_THREAD_TIME
1344static PyObject *
1345time_thread_time(PyObject *self, PyObject *unused)
1346{
1347 _PyTime_t t;
1348 if (_PyTime_GetThreadTimeWithInfo(&t, NULL) < 0) {
1349 return NULL;
1350 }
1351 return _PyFloat_FromPyTime(t);
1352}
1353
1354PyDoc_STRVAR(thread_time_doc,
1355"thread_time() -> float\n\
1356\n\
1357Thread time for profiling: sum of the kernel and user-space CPU time.");
1358
1359static PyObject *
1360time_thread_time_ns(PyObject *self, PyObject *unused)
1361{
1362 _PyTime_t t;
1363 if (_PyTime_GetThreadTimeWithInfo(&t, NULL) < 0) {
1364 return NULL;
1365 }
1366 return _PyTime_AsNanosecondsObject(t);
1367}
1368
1369PyDoc_STRVAR(thread_time_ns_doc,
1370"thread_time() -> int\n\
1371\n\
1372Thread time for profiling as nanoseconds:\n\
1373sum of the kernel and user-space CPU time.");
1374#endif
1375
1376
Victor Stinnerec895392012-04-29 02:41:27 +02001377static PyObject *
1378time_get_clock_info(PyObject *self, PyObject *args)
1379{
1380 char *name;
Victor Stinnerec895392012-04-29 02:41:27 +02001381 _Py_clock_info_t info;
Victor Stinnerbda4b882012-06-12 22:11:44 +02001382 PyObject *obj = NULL, *dict, *ns;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001383 _PyTime_t t;
Victor Stinnerec895392012-04-29 02:41:27 +02001384
Victor Stinnerc29b5852017-11-02 07:28:27 -07001385 if (!PyArg_ParseTuple(args, "s:get_clock_info", &name)) {
Victor Stinnerec895392012-04-29 02:41:27 +02001386 return NULL;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001387 }
Victor Stinnerec895392012-04-29 02:41:27 +02001388
1389#ifdef Py_DEBUG
1390 info.implementation = NULL;
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001391 info.monotonic = -1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001392 info.adjustable = -1;
Victor Stinnerec895392012-04-29 02:41:27 +02001393 info.resolution = -1.0;
1394#else
1395 info.implementation = "";
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001396 info.monotonic = 0;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001397 info.adjustable = 0;
Victor Stinnerec895392012-04-29 02:41:27 +02001398 info.resolution = 1.0;
1399#endif
1400
Victor Stinnerc29b5852017-11-02 07:28:27 -07001401 if (strcmp(name, "time") == 0) {
1402 if (_PyTime_GetSystemClockWithInfo(&t, &info) < 0) {
1403 return NULL;
1404 }
1405 }
Victor Stinnerec895392012-04-29 02:41:27 +02001406#ifdef PYCLOCK
Victor Stinnerc29b5852017-11-02 07:28:27 -07001407 else if (strcmp(name, "clock") == 0) {
Victor Stinnerec895392012-04-29 02:41:27 +02001408 obj = pyclock(&info);
Victor Stinnerc29b5852017-11-02 07:28:27 -07001409 if (obj == NULL) {
1410 return NULL;
1411 }
1412 Py_DECREF(obj);
1413 }
Victor Stinnerec895392012-04-29 02:41:27 +02001414#endif
Victor Stinnerc29b5852017-11-02 07:28:27 -07001415 else if (strcmp(name, "monotonic") == 0) {
1416 if (_PyTime_GetMonotonicClockWithInfo(&t, &info) < 0) {
1417 return NULL;
1418 }
1419 }
1420 else if (strcmp(name, "perf_counter") == 0) {
1421 if (_PyTime_GetPerfCounterWithInfo(&t, &info) < 0) {
1422 return NULL;
1423 }
1424 }
1425 else if (strcmp(name, "process_time") == 0) {
1426 if (_PyTime_GetProcessTimeWithInfo(&t, &info) < 0) {
1427 return NULL;
1428 }
1429 }
Antoine Pitrou4bd41c92017-11-15 22:52:21 +01001430#ifdef HAVE_THREAD_TIME
1431 else if (strcmp(name, "thread_time") == 0) {
1432 if (_PyTime_GetThreadTimeWithInfo(&t, &info) < 0) {
1433 return NULL;
1434 }
1435 }
1436#endif
Victor Stinnerec895392012-04-29 02:41:27 +02001437 else {
1438 PyErr_SetString(PyExc_ValueError, "unknown clock");
1439 return NULL;
1440 }
Victor Stinnerec895392012-04-29 02:41:27 +02001441
Victor Stinnerbda4b882012-06-12 22:11:44 +02001442 dict = PyDict_New();
Victor Stinnerc29b5852017-11-02 07:28:27 -07001443 if (dict == NULL) {
Victor Stinnerec895392012-04-29 02:41:27 +02001444 return NULL;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001445 }
Victor Stinnerec895392012-04-29 02:41:27 +02001446
1447 assert(info.implementation != NULL);
1448 obj = PyUnicode_FromString(info.implementation);
Victor Stinnerc29b5852017-11-02 07:28:27 -07001449 if (obj == NULL) {
Victor Stinnerec895392012-04-29 02:41:27 +02001450 goto error;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001451 }
1452 if (PyDict_SetItemString(dict, "implementation", obj) == -1) {
Victor Stinnerbda4b882012-06-12 22:11:44 +02001453 goto error;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001454 }
Victor Stinnerbda4b882012-06-12 22:11:44 +02001455 Py_CLEAR(obj);
Victor Stinnerec895392012-04-29 02:41:27 +02001456
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001457 assert(info.monotonic != -1);
1458 obj = PyBool_FromLong(info.monotonic);
Victor Stinnerc29b5852017-11-02 07:28:27 -07001459 if (obj == NULL) {
Victor Stinnerec895392012-04-29 02:41:27 +02001460 goto error;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001461 }
1462 if (PyDict_SetItemString(dict, "monotonic", obj) == -1) {
Victor Stinnerbda4b882012-06-12 22:11:44 +02001463 goto error;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001464 }
Victor Stinnerbda4b882012-06-12 22:11:44 +02001465 Py_CLEAR(obj);
Victor Stinnerec895392012-04-29 02:41:27 +02001466
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001467 assert(info.adjustable != -1);
1468 obj = PyBool_FromLong(info.adjustable);
Victor Stinnerc29b5852017-11-02 07:28:27 -07001469 if (obj == NULL) {
Victor Stinnerec895392012-04-29 02:41:27 +02001470 goto error;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001471 }
1472 if (PyDict_SetItemString(dict, "adjustable", obj) == -1) {
Victor Stinnerbda4b882012-06-12 22:11:44 +02001473 goto error;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001474 }
Victor Stinnerbda4b882012-06-12 22:11:44 +02001475 Py_CLEAR(obj);
Victor Stinnerec895392012-04-29 02:41:27 +02001476
1477 assert(info.resolution > 0.0);
1478 assert(info.resolution <= 1.0);
1479 obj = PyFloat_FromDouble(info.resolution);
Victor Stinnerc29b5852017-11-02 07:28:27 -07001480 if (obj == NULL) {
Victor Stinnerec895392012-04-29 02:41:27 +02001481 goto error;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001482 }
1483 if (PyDict_SetItemString(dict, "resolution", obj) == -1) {
Victor Stinnerbda4b882012-06-12 22:11:44 +02001484 goto error;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001485 }
Victor Stinnerbda4b882012-06-12 22:11:44 +02001486 Py_CLEAR(obj);
Victor Stinnerec895392012-04-29 02:41:27 +02001487
Victor Stinnerbda4b882012-06-12 22:11:44 +02001488 ns = _PyNamespace_New(dict);
1489 Py_DECREF(dict);
1490 return ns;
Victor Stinnerec895392012-04-29 02:41:27 +02001491
1492error:
Victor Stinnerbda4b882012-06-12 22:11:44 +02001493 Py_DECREF(dict);
1494 Py_XDECREF(obj);
Victor Stinnerec895392012-04-29 02:41:27 +02001495 return NULL;
1496}
1497
1498PyDoc_STRVAR(get_clock_info_doc,
1499"get_clock_info(name: str) -> dict\n\
1500\n\
1501Get information of the specified clock.");
Victor Stinner8b302012012-02-07 23:29:46 +01001502
Victor Stinner8f5cdfa2017-04-20 13:41:09 +02001503#if !defined(HAVE_TZNAME) || defined(__GLIBC__) || defined(__CYGWIN__)
Martin v. Löwisd218dc12008-04-07 03:17:54 +00001504static void
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -04001505get_zone(char *zone, int n, struct tm *p)
1506{
1507#ifdef HAVE_STRUCT_TM_TM_ZONE
1508 strncpy(zone, p->tm_zone ? p->tm_zone : " ", n);
1509#else
1510 tzset();
1511 strftime(zone, n, "%Z", p);
1512#endif
1513}
1514
Victor Stinner38c06d92018-12-01 01:24:21 +01001515static time_t
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -04001516get_gmtoff(time_t t, struct tm *p)
1517{
1518#ifdef HAVE_STRUCT_TM_TM_ZONE
1519 return p->tm_gmtoff;
1520#else
1521 return timegm(p) - t;
1522#endif
1523}
Victor Stinner8f5cdfa2017-04-20 13:41:09 +02001524#endif /* !defined(HAVE_TZNAME) || defined(__GLIBC__) || defined(__CYGWIN__) */
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -04001525
Victor Stinner38c06d92018-12-01 01:24:21 +01001526static int
1527PyInit_timezone(PyObject *m)
1528{
1529 assert(!PyErr_Occurred());
1530
Martin v. Löwis1a214512008-06-11 05:26:20 +00001531 /* This code moved from PyInit_time wholesale to allow calling it from
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001532 time_tzset. In the future, some parts of it can be moved back
1533 (for platforms that don't HAVE_WORKING_TZSET, when we know what they
1534 are), and the extraneous calls to tzset(3) should be removed.
1535 I haven't done this yet, as I don't want to change this code as
1536 little as possible when introducing the time.tzset and time.tzsetwall
1537 methods. This should simply be a method of doing the following once,
1538 at the top of this function and removing the call to tzset() from
1539 time_tzset():
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001540
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001541 #ifdef HAVE_TZSET
1542 tzset()
1543 #endif
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001544
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001545 And I'm lazy and hate C so nyer.
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001546 */
Guido van Rossum10b164a2001-09-25 13:59:01 +00001547#if defined(HAVE_TZNAME) && !defined(__GLIBC__) && !defined(__CYGWIN__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001548 PyObject *otz0, *otz1;
1549 tzset();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001550 PyModule_AddIntConstant(m, "timezone", timezone);
Guido van Rossumb6775db1994-08-01 11:34:53 +00001551#ifdef HAVE_ALTZONE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001552 PyModule_AddIntConstant(m, "altzone", altzone);
Guido van Rossumb6775db1994-08-01 11:34:53 +00001553#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001554 PyModule_AddIntConstant(m, "altzone", timezone-3600);
Guido van Rossumb6775db1994-08-01 11:34:53 +00001555#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001556 PyModule_AddIntConstant(m, "daylight", daylight);
Victor Stinner7ed7aea2018-01-15 10:45:49 +01001557 otz0 = PyUnicode_DecodeLocale(tzname[0], "surrogateescape");
1558 otz1 = PyUnicode_DecodeLocale(tzname[1], "surrogateescape");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001559 PyModule_AddObject(m, "tzname", Py_BuildValue("(NN)", otz0, otz1));
Guido van Rossum10b164a2001-09-25 13:59:01 +00001560#else /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001561 {
Guido van Rossum234f9421993-06-17 12:35:49 +00001562#define YEAR ((time_t)((365 * 24 + 6) * 3600))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001563 time_t t;
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -04001564 struct tm p;
Victor Stinner38c06d92018-12-01 01:24:21 +01001565 time_t janzone_t, julyzone_t;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001566 char janname[10], julyname[10];
1567 t = (time((time_t *)0) / YEAR) * YEAR;
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -04001568 _PyTime_localtime(t, &p);
1569 get_zone(janname, 9, &p);
Victor Stinner38c06d92018-12-01 01:24:21 +01001570 janzone_t = -get_gmtoff(t, &p);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001571 janname[9] = '\0';
1572 t += YEAR/2;
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -04001573 _PyTime_localtime(t, &p);
1574 get_zone(julyname, 9, &p);
Victor Stinner38c06d92018-12-01 01:24:21 +01001575 julyzone_t = -get_gmtoff(t, &p);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001576 julyname[9] = '\0';
Guido van Rossum10b164a2001-09-25 13:59:01 +00001577
Victor Stinner38c06d92018-12-01 01:24:21 +01001578 /* Sanity check, don't check for the validity of timezones.
1579 In practice, it should be more in range -12 hours .. +14 hours. */
1580#define MAX_TIMEZONE (48 * 3600)
1581 if (janzone_t < -MAX_TIMEZONE || janzone_t > MAX_TIMEZONE
1582 || julyzone_t < -MAX_TIMEZONE || julyzone_t > MAX_TIMEZONE)
1583 {
1584 PyErr_SetString(PyExc_RuntimeError, "invalid GMT offset");
1585 return -1;
1586 }
1587 int janzone = (int)janzone_t;
1588 int julyzone = (int)julyzone_t;
1589
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001590 if( janzone < julyzone ) {
1591 /* DST is reversed in the southern hemisphere */
1592 PyModule_AddIntConstant(m, "timezone", julyzone);
1593 PyModule_AddIntConstant(m, "altzone", janzone);
1594 PyModule_AddIntConstant(m, "daylight",
1595 janzone != julyzone);
1596 PyModule_AddObject(m, "tzname",
1597 Py_BuildValue("(zz)",
1598 julyname, janname));
1599 } else {
1600 PyModule_AddIntConstant(m, "timezone", janzone);
1601 PyModule_AddIntConstant(m, "altzone", julyzone);
1602 PyModule_AddIntConstant(m, "daylight",
1603 janzone != julyzone);
1604 PyModule_AddObject(m, "tzname",
1605 Py_BuildValue("(zz)",
1606 janname, julyname));
1607 }
1608 }
Tim Peters26ae7cd2001-03-20 03:26:49 +00001609#ifdef __CYGWIN__
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001610 tzset();
1611 PyModule_AddIntConstant(m, "timezone", _timezone);
1612 PyModule_AddIntConstant(m, "altzone", _timezone-3600);
1613 PyModule_AddIntConstant(m, "daylight", _daylight);
1614 PyModule_AddObject(m, "tzname",
1615 Py_BuildValue("(zz)", _tzname[0], _tzname[1]));
Tim Peters26ae7cd2001-03-20 03:26:49 +00001616#endif /* __CYGWIN__ */
Guido van Rossum10b164a2001-09-25 13:59:01 +00001617#endif /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/
Victor Stinner38c06d92018-12-01 01:24:21 +01001618 return 0;
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001619}
1620
1621
1622static PyMethodDef time_methods[] = {
Victor Stinner4195b5c2012-02-08 23:03:19 +01001623 {"time", time_time, METH_NOARGS, time_doc},
Victor Stinnerc29b5852017-11-02 07:28:27 -07001624 {"time_ns", time_time_ns, METH_NOARGS, time_ns_doc},
Victor Stinnerec895392012-04-29 02:41:27 +02001625#ifdef PYCLOCK
Victor Stinner4195b5c2012-02-08 23:03:19 +01001626 {"clock", time_clock, METH_NOARGS, clock_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001627#endif
Victor Stinnere0be4232011-10-25 13:06:09 +02001628#ifdef HAVE_CLOCK_GETTIME
Victor Stinner4195b5c2012-02-08 23:03:19 +01001629 {"clock_gettime", time_clock_gettime, METH_VARARGS, clock_gettime_doc},
Victor Stinnerc29b5852017-11-02 07:28:27 -07001630 {"clock_gettime_ns",time_clock_gettime_ns, METH_VARARGS, clock_gettime_ns_doc},
Benjamin Peterson37098cd2016-09-13 22:55:09 -07001631#endif
1632#ifdef HAVE_CLOCK_SETTIME
Victor Stinner30d79472012-04-03 00:45:07 +02001633 {"clock_settime", time_clock_settime, METH_VARARGS, clock_settime_doc},
Victor Stinnerc29b5852017-11-02 07:28:27 -07001634 {"clock_settime_ns",time_clock_settime_ns, METH_VARARGS, clock_settime_ns_doc},
Benjamin Peterson37098cd2016-09-13 22:55:09 -07001635#endif
1636#ifdef HAVE_CLOCK_GETRES
Victor Stinner4195b5c2012-02-08 23:03:19 +01001637 {"clock_getres", time_clock_getres, METH_VARARGS, clock_getres_doc},
Victor Stinnere0be4232011-10-25 13:06:09 +02001638#endif
pdoxe14679c2017-10-05 00:01:56 -07001639#ifdef HAVE_PTHREAD_GETCPUCLOCKID
1640 {"pthread_getcpuclockid", time_pthread_getcpuclockid, METH_VARARGS, pthread_getcpuclockid_doc},
1641#endif
Victor Stinnercb29f012015-03-27 13:31:18 +01001642 {"sleep", time_sleep, METH_O, sleep_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001643 {"gmtime", time_gmtime, METH_VARARGS, gmtime_doc},
1644 {"localtime", time_localtime, METH_VARARGS, localtime_doc},
1645 {"asctime", time_asctime, METH_VARARGS, asctime_doc},
1646 {"ctime", time_ctime, METH_VARARGS, ctime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001647#ifdef HAVE_MKTIME
Victor Stinner4195b5c2012-02-08 23:03:19 +01001648 {"mktime", time_mktime, METH_O, mktime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001649#endif
1650#ifdef HAVE_STRFTIME
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001651 {"strftime", time_strftime, METH_VARARGS, strftime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001652#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001653 {"strptime", time_strptime, METH_VARARGS, strptime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001654#ifdef HAVE_WORKING_TZSET
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001655 {"tzset", time_tzset, METH_NOARGS, tzset_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001656#endif
Victor Stinnerec895392012-04-29 02:41:27 +02001657 {"monotonic", time_monotonic, METH_NOARGS, monotonic_doc},
Victor Stinnerc29b5852017-11-02 07:28:27 -07001658 {"monotonic_ns", time_monotonic_ns, METH_NOARGS, monotonic_ns_doc},
Victor Stinnerec895392012-04-29 02:41:27 +02001659 {"process_time", time_process_time, METH_NOARGS, process_time_doc},
Victor Stinnerc29b5852017-11-02 07:28:27 -07001660 {"process_time_ns", time_process_time_ns, METH_NOARGS, process_time_ns_doc},
Antoine Pitrou4bd41c92017-11-15 22:52:21 +01001661#ifdef HAVE_THREAD_TIME
1662 {"thread_time", time_thread_time, METH_NOARGS, thread_time_doc},
1663 {"thread_time_ns", time_thread_time_ns, METH_NOARGS, thread_time_ns_doc},
1664#endif
Victor Stinnerec895392012-04-29 02:41:27 +02001665 {"perf_counter", time_perf_counter, METH_NOARGS, perf_counter_doc},
Victor Stinnerc29b5852017-11-02 07:28:27 -07001666 {"perf_counter_ns", time_perf_counter_ns, METH_NOARGS, perf_counter_ns_doc},
Victor Stinnerec895392012-04-29 02:41:27 +02001667 {"get_clock_info", time_get_clock_info, METH_VARARGS, get_clock_info_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001668 {NULL, NULL} /* sentinel */
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001669};
1670
1671
1672PyDoc_STRVAR(module_doc,
1673"This module provides various functions to manipulate time values.\n\
1674\n\
1675There are two standard representations of time. One is the number\n\
1676of seconds since the Epoch, in UTC (a.k.a. GMT). It may be an integer\n\
1677or a floating point number (to represent fractions of seconds).\n\
1678The Epoch is system-defined; on Unix, it is generally January 1st, 1970.\n\
1679The actual value can be retrieved by calling gmtime(0).\n\
1680\n\
1681The other representation is a tuple of 9 integers giving local time.\n\
1682The tuple items are:\n\
Alexander Belopolsky03163ac2011-05-02 12:20:52 -04001683 year (including century, e.g. 1998)\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001684 month (1-12)\n\
1685 day (1-31)\n\
1686 hours (0-23)\n\
1687 minutes (0-59)\n\
1688 seconds (0-59)\n\
1689 weekday (0-6, Monday is 0)\n\
1690 Julian day (day in the year, 1-366)\n\
1691 DST (Daylight Savings Time) flag (-1, 0 or 1)\n\
1692If the DST flag is 0, the time is given in the regular time zone;\n\
1693if it is 1, the time is given in the DST time zone;\n\
Cheryl Sabella703ff382017-10-11 09:29:14 -04001694if it is -1, mktime() should guess based on the date and time.\n");
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001695
1696
Martin v. Löwis1a214512008-06-11 05:26:20 +00001697
1698static struct PyModuleDef timemodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001699 PyModuleDef_HEAD_INIT,
1700 "time",
1701 module_doc,
1702 -1,
1703 time_methods,
1704 NULL,
1705 NULL,
1706 NULL,
1707 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00001708};
1709
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001710PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00001711PyInit_time(void)
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001712{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001713 PyObject *m;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001714 m = PyModule_Create(&timemodule);
1715 if (m == NULL)
1716 return NULL;
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001717
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001718 /* Set, or reset, module variables like time.timezone */
Victor Stinner38c06d92018-12-01 01:24:21 +01001719 if (PyInit_timezone(m) < 0) {
1720 return NULL;
1721 }
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001722
Miss Islington (bot)002aef32018-10-20 17:41:38 -07001723#if defined(HAVE_CLOCK_GETTIME) || defined(HAVE_CLOCK_SETTIME) || defined(HAVE_CLOCK_GETRES)
1724
Benjamin Peterson37098cd2016-09-13 22:55:09 -07001725#ifdef CLOCK_REALTIME
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -04001726 PyModule_AddIntMacro(m, CLOCK_REALTIME);
Benjamin Peterson37098cd2016-09-13 22:55:09 -07001727#endif
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -04001728#ifdef CLOCK_MONOTONIC
1729 PyModule_AddIntMacro(m, CLOCK_MONOTONIC);
1730#endif
1731#ifdef CLOCK_MONOTONIC_RAW
1732 PyModule_AddIntMacro(m, CLOCK_MONOTONIC_RAW);
1733#endif
1734#ifdef CLOCK_HIGHRES
1735 PyModule_AddIntMacro(m, CLOCK_HIGHRES);
1736#endif
1737#ifdef CLOCK_PROCESS_CPUTIME_ID
1738 PyModule_AddIntMacro(m, CLOCK_PROCESS_CPUTIME_ID);
1739#endif
1740#ifdef CLOCK_THREAD_CPUTIME_ID
1741 PyModule_AddIntMacro(m, CLOCK_THREAD_CPUTIME_ID);
1742#endif
Victor Stinnera64ce972017-11-02 04:19:19 -07001743#ifdef CLOCK_PROF
1744 PyModule_AddIntMacro(m, CLOCK_PROF);
1745#endif
1746#ifdef CLOCK_BOOTTIME
1747 PyModule_AddIntMacro(m, CLOCK_BOOTTIME);
1748#endif
1749#ifdef CLOCK_UPTIME
1750 PyModule_AddIntMacro(m, CLOCK_UPTIME);
1751#endif
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -04001752
Miss Islington (bot)002aef32018-10-20 17:41:38 -07001753#endif /* defined(HAVE_CLOCK_GETTIME) || defined(HAVE_CLOCK_SETTIME) || defined(HAVE_CLOCK_GETRES) */
1754
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001755 if (!initialized) {
Victor Stinner1c8f0592013-07-22 22:24:54 +02001756 if (PyStructSequence_InitType2(&StructTimeType,
1757 &struct_time_type_desc) < 0)
1758 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001759 }
1760 Py_INCREF(&StructTimeType);
Alexander Belopolskyc142bba2012-06-13 22:15:26 -04001761 PyModule_AddIntConstant(m, "_STRUCT_TM_ITEMS", 11);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001762 PyModule_AddObject(m, "struct_time", (PyObject*) &StructTimeType);
1763 initialized = 1;
1764 return m;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001765}
1766
Victor Stinnercb29f012015-03-27 13:31:18 +01001767/* Implement pysleep() for various platforms.
Guido van Rossumb6775db1994-08-01 11:34:53 +00001768 When interrupted (or when another error occurs), return -1 and
1769 set an exception; else return 0. */
1770
1771static int
Victor Stinnercb29f012015-03-27 13:31:18 +01001772pysleep(_PyTime_t secs)
Guido van Rossum426035c1991-02-19 12:27:35 +00001773{
Victor Stinnercb29f012015-03-27 13:31:18 +01001774 _PyTime_t deadline, monotonic;
Victor Stinner79d68f92015-03-19 21:54:09 +01001775#ifndef MS_WINDOWS
1776 struct timeval timeout;
Victor Stinner79d68f92015-03-19 21:54:09 +01001777 int err = 0;
1778#else
Victor Stinnercb29f012015-03-27 13:31:18 +01001779 _PyTime_t millisecs;
Victor Stinner79d68f92015-03-19 21:54:09 +01001780 unsigned long ul_millis;
1781 DWORD rc;
1782 HANDLE hInterruptEvent;
Victor Stinner0c2fd892015-03-17 10:49:17 +01001783#endif
Victor Stinner79d68f92015-03-19 21:54:09 +01001784
Victor Stinnercb29f012015-03-27 13:31:18 +01001785 deadline = _PyTime_GetMonotonicClock() + secs;
Victor Stinner79d68f92015-03-19 21:54:09 +01001786
1787 do {
1788#ifndef MS_WINDOWS
Victor Stinner869e1772015-03-30 03:49:14 +02001789 if (_PyTime_AsTimeval(secs, &timeout, _PyTime_ROUND_CEILING) < 0)
Victor Stinnercb29f012015-03-27 13:31:18 +01001790 return -1;
Victor Stinner79d68f92015-03-19 21:54:09 +01001791
1792 Py_BEGIN_ALLOW_THREADS
1793 err = select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &timeout);
1794 Py_END_ALLOW_THREADS
1795
1796 if (err == 0)
1797 break;
1798
1799 if (errno != EINTR) {
Victor Stinner0c2fd892015-03-17 10:49:17 +01001800 PyErr_SetFromErrno(PyExc_OSError);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001801 return -1;
1802 }
Victor Stinner79d68f92015-03-19 21:54:09 +01001803#else
Victor Stinner869e1772015-03-30 03:49:14 +02001804 millisecs = _PyTime_AsMilliseconds(secs, _PyTime_ROUND_CEILING);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001805 if (millisecs > (double)ULONG_MAX) {
1806 PyErr_SetString(PyExc_OverflowError,
1807 "sleep length is too large");
1808 return -1;
1809 }
Victor Stinner79d68f92015-03-19 21:54:09 +01001810
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001811 /* Allow sleep(0) to maintain win32 semantics, and as decreed
1812 * by Guido, only the main thread can be interrupted.
1813 */
1814 ul_millis = (unsigned long)millisecs;
Victor Stinner79d68f92015-03-19 21:54:09 +01001815 if (ul_millis == 0 || !_PyOS_IsMainThread()) {
1816 Py_BEGIN_ALLOW_THREADS
Victor Stinner0eac1302015-03-20 03:06:12 +01001817 Sleep(ul_millis);
Victor Stinner79d68f92015-03-19 21:54:09 +01001818 Py_END_ALLOW_THREADS
1819 break;
Victor Stinner945c82e2015-03-12 16:19:01 +01001820 }
Victor Stinner79d68f92015-03-19 21:54:09 +01001821
1822 hInterruptEvent = _PyOS_SigintEvent();
1823 ResetEvent(hInterruptEvent);
1824
1825 Py_BEGIN_ALLOW_THREADS
1826 rc = WaitForSingleObjectEx(hInterruptEvent, ul_millis, FALSE);
Victor Stinner0c2fd892015-03-17 10:49:17 +01001827 Py_END_ALLOW_THREADS
Victor Stinner79d68f92015-03-19 21:54:09 +01001828
1829 if (rc != WAIT_OBJECT_0)
1830 break;
Victor Stinner945c82e2015-03-12 16:19:01 +01001831#endif
Victor Stinner0c2fd892015-03-17 10:49:17 +01001832
Victor Stinner79d68f92015-03-19 21:54:09 +01001833 /* sleep was interrupted by SIGINT */
1834 if (PyErr_CheckSignals())
1835 return -1;
1836
Victor Stinnercb29f012015-03-27 13:31:18 +01001837 monotonic = _PyTime_GetMonotonicClock();
1838 secs = deadline - monotonic;
Victor Stinner6aa446c2015-03-30 21:33:51 +02001839 if (secs < 0)
Victor Stinner79d68f92015-03-19 21:54:09 +01001840 break;
1841 /* retry with the recomputed delay */
1842 } while (1);
1843
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001844 return 0;
Guido van Rossum80c9d881991-04-16 08:47:51 +00001845}