blob: 3df17ac4fb68f57ab6641d72ced1792d79e6f2be [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
Gregory P. Smithb474e672018-12-30 17:05:36 -080037#ifdef _Py_MEMORY_SANITIZER
38# include <sanitizer/msan_interface.h>
39#endif
40
Zackery Spytz6673dec2019-02-25 16:56:44 -070041#ifdef _MSC_VER
42#define _Py_timezone _timezone
43#define _Py_daylight _daylight
44#define _Py_tzname _tzname
45#else
46#define _Py_timezone timezone
47#define _Py_daylight daylight
48#define _Py_tzname tzname
49#endif
50
Victor Stinnerc29b5852017-11-02 07:28:27 -070051#define SEC_TO_NS (1000 * 1000 * 1000)
52
Guido van Rossum234f9421993-06-17 12:35:49 +000053/* Forward declarations */
Victor Stinnercb29f012015-03-27 13:31:18 +010054static int pysleep(_PyTime_t);
Victor Stinnerec895392012-04-29 02:41:27 +020055
Victor Stinner85fdfa82012-01-27 00:38:48 +010056
Victor Stinnera997c7b2017-10-10 02:51:50 -070057static PyObject*
58_PyFloat_FromPyTime(_PyTime_t t)
59{
60 double d = _PyTime_AsSecondsDouble(t);
61 return PyFloat_FromDouble(d);
62}
63
Victor Stinnerc29b5852017-11-02 07:28:27 -070064
Victor Stinner4195b5c2012-02-08 23:03:19 +010065static PyObject *
Victor Stinnerc29b5852017-11-02 07:28:27 -070066time_time(PyObject *self, PyObject *unused)
Victor Stinner85fdfa82012-01-27 00:38:48 +010067{
Victor Stinnerc29b5852017-11-02 07:28:27 -070068 _PyTime_t t = _PyTime_GetSystemClock();
69 return _PyFloat_FromPyTime(t);
70}
71
72
73PyDoc_STRVAR(time_doc,
74"time() -> floating point number\n\
75\n\
76Return the current time in seconds since the Epoch.\n\
77Fractions of a second may be present if the system clock provides them.");
78
79static PyObject *
80time_time_ns(PyObject *self, PyObject *unused)
81{
82 _PyTime_t t = _PyTime_GetSystemClock();
83 return _PyTime_AsNanosecondsObject(t);
84}
85
86PyDoc_STRVAR(time_ns_doc,
87"time_ns() -> int\n\
88\n\
89Return the current time in nanoseconds since the Epoch.");
90
91#if defined(HAVE_CLOCK)
92
93#ifndef CLOCKS_PER_SEC
94# ifdef CLK_TCK
95# define CLOCKS_PER_SEC CLK_TCK
96# else
97# define CLOCKS_PER_SEC 1000000
98# endif
99#endif
100
101static int
102_PyTime_GetClockWithInfo(_PyTime_t *tp, _Py_clock_info_t *info)
103{
104 static int initialized = 0;
105 clock_t ticks;
106
107 if (!initialized) {
108 initialized = 1;
109
110 /* must sure that _PyTime_MulDiv(ticks, SEC_TO_NS, CLOCKS_PER_SEC)
111 above cannot overflow */
112 if ((_PyTime_t)CLOCKS_PER_SEC > _PyTime_MAX / SEC_TO_NS) {
113 PyErr_SetString(PyExc_OverflowError,
114 "CLOCKS_PER_SEC is too large");
115 return -1;
116 }
Victor Stinner85fdfa82012-01-27 00:38:48 +0100117 }
Victor Stinnerc29b5852017-11-02 07:28:27 -0700118
Victor Stinnerec895392012-04-29 02:41:27 +0200119 if (info) {
120 info->implementation = "clock()";
121 info->resolution = 1.0 / (double)CLOCKS_PER_SEC;
Benjamin Peterson49a69e42012-05-01 09:38:34 -0400122 info->monotonic = 1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +0200123 info->adjustable = 0;
Victor Stinnerec895392012-04-29 02:41:27 +0200124 }
Victor Stinnerc29b5852017-11-02 07:28:27 -0700125
126 ticks = clock();
127 if (ticks == (clock_t)-1) {
128 PyErr_SetString(PyExc_RuntimeError,
129 "the processor time used is not available "
130 "or its value cannot be represented");
131 return -1;
132 }
133 *tp = _PyTime_MulDiv(ticks, SEC_TO_NS, (_PyTime_t)CLOCKS_PER_SEC);
134 return 0;
Victor Stinner85fdfa82012-01-27 00:38:48 +0100135}
136#endif /* HAVE_CLOCK */
137
Victor Stinnercba9a0c2017-10-12 08:51:56 -0700138static PyObject*
139perf_counter(_Py_clock_info_t *info)
140{
Victor Stinnerbdaeb7d2017-10-16 08:44:31 -0700141 _PyTime_t t;
142 if (_PyTime_GetPerfCounterWithInfo(&t, info) < 0) {
Victor Stinnercba9a0c2017-10-12 08:51:56 -0700143 return NULL;
144 }
Victor Stinnerc29b5852017-11-02 07:28:27 -0700145 return _PyFloat_FromPyTime(t);
Victor Stinnercba9a0c2017-10-12 08:51:56 -0700146}
147
pxinwrf1464f42019-04-15 17:06:21 +0800148#if (defined(MS_WINDOWS) || defined(HAVE_CLOCK)) && !defined(__VXWORKS__)
Victor Stinnerec895392012-04-29 02:41:27 +0200149#define PYCLOCK
150static PyObject*
151pyclock(_Py_clock_info_t *info)
152{
Victor Stinner884d13a2017-10-17 14:46:45 -0700153 if (PyErr_WarnEx(PyExc_DeprecationWarning,
154 "time.clock has been deprecated in Python 3.3 and will "
155 "be removed from Python 3.8: "
156 "use time.perf_counter or time.process_time "
157 "instead", 1) < 0) {
158 return NULL;
159 }
Victor Stinnerc29b5852017-11-02 07:28:27 -0700160
Victor Stinnera997c7b2017-10-10 02:51:50 -0700161#ifdef MS_WINDOWS
Victor Stinnercba9a0c2017-10-12 08:51:56 -0700162 return perf_counter(info);
Victor Stinner54884492014-08-29 16:51:33 +0200163#else
Victor Stinnerc29b5852017-11-02 07:28:27 -0700164 _PyTime_t t;
165 if (_PyTime_GetClockWithInfo(&t, info) < 0) {
166 return NULL;
167 }
168 return _PyFloat_FromPyTime(t);
Victor Stinner54884492014-08-29 16:51:33 +0200169#endif
Victor Stinnerec895392012-04-29 02:41:27 +0200170}
171
Victor Stinner9122fdd2011-07-04 13:55:40 +0200172static PyObject *
Victor Stinner4195b5c2012-02-08 23:03:19 +0100173time_clock(PyObject *self, PyObject *unused)
Victor Stinner9122fdd2011-07-04 13:55:40 +0200174{
Victor Stinnerec895392012-04-29 02:41:27 +0200175 return pyclock(NULL);
Victor Stinner9122fdd2011-07-04 13:55:40 +0200176}
Victor Stinner9122fdd2011-07-04 13:55:40 +0200177
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000178PyDoc_STRVAR(clock_doc,
Victor Stinner4195b5c2012-02-08 23:03:19 +0100179"clock() -> floating point number\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000180\n\
181Return the CPU time or real time since the start of the process or since\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000182the first call to clock(). This has as much precision as the system\n\
183records.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000184#endif
185
Victor Stinnere0be4232011-10-25 13:06:09 +0200186#ifdef HAVE_CLOCK_GETTIME
187static PyObject *
Victor Stinner4195b5c2012-02-08 23:03:19 +0100188time_clock_gettime(PyObject *self, PyObject *args)
Victor Stinnere0be4232011-10-25 13:06:09 +0200189{
190 int ret;
Victor Stinnere0be4232011-10-25 13:06:09 +0200191 struct timespec tp;
192
Michael Felte2926b72018-12-28 14:57:37 +0100193#if defined(_AIX) && (SIZEOF_LONG == 8)
194 long clk_id;
195 if (!PyArg_ParseTuple(args, "l:clock_gettime", &clk_id)) {
196#else
197 int clk_id;
Victor Stinnerc29b5852017-11-02 07:28:27 -0700198 if (!PyArg_ParseTuple(args, "i:clock_gettime", &clk_id)) {
Michael Felte2926b72018-12-28 14:57:37 +0100199#endif
Victor Stinnere0be4232011-10-25 13:06:09 +0200200 return NULL;
Victor Stinnerc29b5852017-11-02 07:28:27 -0700201 }
Victor Stinnere0be4232011-10-25 13:06:09 +0200202
203 ret = clock_gettime((clockid_t)clk_id, &tp);
Antoine Pitrou2c085602012-01-18 01:41:44 +0100204 if (ret != 0) {
Victor Stinnera734af32014-07-31 13:07:17 +0200205 PyErr_SetFromErrno(PyExc_OSError);
Antoine Pitrou2c085602012-01-18 01:41:44 +0100206 return NULL;
207 }
Victor Stinner4195b5c2012-02-08 23:03:19 +0100208 return PyFloat_FromDouble(tp.tv_sec + tp.tv_nsec * 1e-9);
Victor Stinnere0be4232011-10-25 13:06:09 +0200209}
210
211PyDoc_STRVAR(clock_gettime_doc,
Victor Stinnerc29b5852017-11-02 07:28:27 -0700212"clock_gettime(clk_id) -> float\n\
Victor Stinnere0be4232011-10-25 13:06:09 +0200213\n\
214Return the time of the specified clock clk_id.");
Victor Stinnerc29b5852017-11-02 07:28:27 -0700215
216static PyObject *
217time_clock_gettime_ns(PyObject *self, PyObject *args)
218{
219 int ret;
220 int clk_id;
221 struct timespec ts;
222 _PyTime_t t;
223
224 if (!PyArg_ParseTuple(args, "i:clock_gettime", &clk_id)) {
225 return NULL;
226 }
227
228 ret = clock_gettime((clockid_t)clk_id, &ts);
229 if (ret != 0) {
230 PyErr_SetFromErrno(PyExc_OSError);
231 return NULL;
232 }
233 if (_PyTime_FromTimespec(&t, &ts) < 0) {
234 return NULL;
235 }
236 return _PyTime_AsNanosecondsObject(t);
237}
238
239PyDoc_STRVAR(clock_gettime_ns_doc,
240"clock_gettime_ns(clk_id) -> int\n\
241\n\
242Return the time of the specified clock clk_id as nanoseconds.");
Benjamin Peterson37098cd2016-09-13 22:55:09 -0700243#endif /* HAVE_CLOCK_GETTIME */
Victor Stinner30d79472012-04-03 00:45:07 +0200244
Benjamin Peterson37098cd2016-09-13 22:55:09 -0700245#ifdef HAVE_CLOCK_SETTIME
Victor Stinner30d79472012-04-03 00:45:07 +0200246static PyObject *
247time_clock_settime(PyObject *self, PyObject *args)
248{
Victor Stinnerb8d01692012-04-13 23:44:05 +0200249 int clk_id;
Victor Stinner30d79472012-04-03 00:45:07 +0200250 PyObject *obj;
Victor Stinnerb3b45442015-03-28 04:09:41 +0100251 _PyTime_t t;
Victor Stinner30d79472012-04-03 00:45:07 +0200252 struct timespec tp;
253 int ret;
254
255 if (!PyArg_ParseTuple(args, "iO:clock_settime", &clk_id, &obj))
256 return NULL;
257
Victor Stinner02937aa2015-03-28 05:02:39 +0100258 if (_PyTime_FromSecondsObject(&t, obj, _PyTime_ROUND_FLOOR) < 0)
Victor Stinner30d79472012-04-03 00:45:07 +0200259 return NULL;
Victor Stinnerb3b45442015-03-28 04:09:41 +0100260
261 if (_PyTime_AsTimespec(t, &tp) == -1)
262 return NULL;
Victor Stinner30d79472012-04-03 00:45:07 +0200263
264 ret = clock_settime((clockid_t)clk_id, &tp);
265 if (ret != 0) {
Victor Stinnera734af32014-07-31 13:07:17 +0200266 PyErr_SetFromErrno(PyExc_OSError);
Victor Stinner30d79472012-04-03 00:45:07 +0200267 return NULL;
268 }
269 Py_RETURN_NONE;
270}
271
272PyDoc_STRVAR(clock_settime_doc,
273"clock_settime(clk_id, time)\n\
274\n\
275Set the time of the specified clock clk_id.");
Victor Stinnerc29b5852017-11-02 07:28:27 -0700276
277static PyObject *
278time_clock_settime_ns(PyObject *self, PyObject *args)
279{
280 int clk_id;
281 PyObject *obj;
282 _PyTime_t t;
283 struct timespec ts;
284 int ret;
285
286 if (!PyArg_ParseTuple(args, "iO:clock_settime", &clk_id, &obj)) {
287 return NULL;
288 }
289
290 if (_PyTime_FromNanosecondsObject(&t, obj) < 0) {
291 return NULL;
292 }
293 if (_PyTime_AsTimespec(t, &ts) == -1) {
294 return NULL;
295 }
296
297 ret = clock_settime((clockid_t)clk_id, &ts);
298 if (ret != 0) {
299 PyErr_SetFromErrno(PyExc_OSError);
300 return NULL;
301 }
302 Py_RETURN_NONE;
303}
304
305PyDoc_STRVAR(clock_settime_ns_doc,
306"clock_settime_ns(clk_id, time)\n\
307\n\
308Set the time of the specified clock clk_id with nanoseconds.");
Benjamin Peterson37098cd2016-09-13 22:55:09 -0700309#endif /* HAVE_CLOCK_SETTIME */
Victor Stinnere0be4232011-10-25 13:06:09 +0200310
Benjamin Peterson37098cd2016-09-13 22:55:09 -0700311#ifdef HAVE_CLOCK_GETRES
Victor Stinnere0be4232011-10-25 13:06:09 +0200312static PyObject *
Victor Stinner4195b5c2012-02-08 23:03:19 +0100313time_clock_getres(PyObject *self, PyObject *args)
Victor Stinnere0be4232011-10-25 13:06:09 +0200314{
315 int ret;
Victor Stinnerb8d01692012-04-13 23:44:05 +0200316 int clk_id;
Victor Stinnere0be4232011-10-25 13:06:09 +0200317 struct timespec tp;
318
Victor Stinner4195b5c2012-02-08 23:03:19 +0100319 if (!PyArg_ParseTuple(args, "i:clock_getres", &clk_id))
Victor Stinnere0be4232011-10-25 13:06:09 +0200320 return NULL;
321
322 ret = clock_getres((clockid_t)clk_id, &tp);
Antoine Pitrou2c085602012-01-18 01:41:44 +0100323 if (ret != 0) {
Victor Stinnera734af32014-07-31 13:07:17 +0200324 PyErr_SetFromErrno(PyExc_OSError);
Antoine Pitrou2c085602012-01-18 01:41:44 +0100325 return NULL;
326 }
Victor Stinner4195b5c2012-02-08 23:03:19 +0100327
328 return PyFloat_FromDouble(tp.tv_sec + tp.tv_nsec * 1e-9);
Victor Stinnere0be4232011-10-25 13:06:09 +0200329}
330
331PyDoc_STRVAR(clock_getres_doc,
Victor Stinner4195b5c2012-02-08 23:03:19 +0100332"clock_getres(clk_id) -> floating point number\n\
Victor Stinnere0be4232011-10-25 13:06:09 +0200333\n\
334Return the resolution (precision) of the specified clock clk_id.");
Benjamin Peterson37098cd2016-09-13 22:55:09 -0700335#endif /* HAVE_CLOCK_GETRES */
Victor Stinnere0be4232011-10-25 13:06:09 +0200336
pdoxe14679c2017-10-05 00:01:56 -0700337#ifdef HAVE_PTHREAD_GETCPUCLOCKID
338static PyObject *
339time_pthread_getcpuclockid(PyObject *self, PyObject *args)
340{
341 unsigned long thread_id;
342 int err;
343 clockid_t clk_id;
344 if (!PyArg_ParseTuple(args, "k:pthread_getcpuclockid", &thread_id)) {
345 return NULL;
346 }
347 err = pthread_getcpuclockid((pthread_t)thread_id, &clk_id);
348 if (err) {
349 errno = err;
350 PyErr_SetFromErrno(PyExc_OSError);
351 return NULL;
352 }
Gregory P. Smithb474e672018-12-30 17:05:36 -0800353#ifdef _Py_MEMORY_SANITIZER
354 __msan_unpoison(&clk_id, sizeof(clk_id));
355#endif
pdoxe14679c2017-10-05 00:01:56 -0700356 return PyLong_FromLong(clk_id);
357}
358
359PyDoc_STRVAR(pthread_getcpuclockid_doc,
360"pthread_getcpuclockid(thread_id) -> int\n\
361\n\
362Return the clk_id of a thread's CPU time clock.");
363#endif /* HAVE_PTHREAD_GETCPUCLOCKID */
364
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000365static PyObject *
Victor Stinnercb29f012015-03-27 13:31:18 +0100366time_sleep(PyObject *self, PyObject *obj)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000367{
Victor Stinnercb29f012015-03-27 13:31:18 +0100368 _PyTime_t secs;
Pablo Galindo59af94f2017-10-18 08:13:09 +0100369 if (_PyTime_FromSecondsObject(&secs, obj, _PyTime_ROUND_TIMEOUT))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000370 return NULL;
Victor Stinner7f53a502011-07-05 22:00:25 +0200371 if (secs < 0) {
372 PyErr_SetString(PyExc_ValueError,
373 "sleep length must be non-negative");
374 return NULL;
375 }
Victor Stinnercb29f012015-03-27 13:31:18 +0100376 if (pysleep(secs) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000377 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200378 Py_RETURN_NONE;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000379}
380
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000381PyDoc_STRVAR(sleep_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000382"sleep(seconds)\n\
383\n\
384Delay execution for a given number of seconds. The argument may be\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000385a floating point number for subsecond precision.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000386
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000387static PyStructSequence_Field struct_time_type_fields[] = {
Alexander Belopolsky69f3fd02010-06-05 15:04:51 +0000388 {"tm_year", "year, for example, 1993"},
389 {"tm_mon", "month of year, range [1, 12]"},
390 {"tm_mday", "day of month, range [1, 31]"},
391 {"tm_hour", "hours, range [0, 23]"},
392 {"tm_min", "minutes, range [0, 59]"},
393 {"tm_sec", "seconds, range [0, 61])"},
394 {"tm_wday", "day of week, range [0, 6], Monday is 0"},
395 {"tm_yday", "day of year, range [1, 366]"},
396 {"tm_isdst", "1 if summer time is in effect, 0 if not, and -1 if unknown"},
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400397 {"tm_zone", "abbreviation of timezone name"},
398 {"tm_gmtoff", "offset from UTC in seconds"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000399 {0}
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000400};
401
402static PyStructSequence_Desc struct_time_type_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000403 "time.struct_time",
Alexander Belopolsky69f3fd02010-06-05 15:04:51 +0000404 "The time value as returned by gmtime(), localtime(), and strptime(), and\n"
405 " accepted by asctime(), mktime() and strftime(). May be considered as a\n"
406 " sequence of 9 integers.\n\n"
407 " Note that several fields' values are not the same as those defined by\n"
408 " the C language standard for struct tm. For example, the value of the\n"
409 " field tm_year is the actual year, not year - 1900. See individual\n"
410 " fields' descriptions for details.",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000411 struct_time_type_fields,
412 9,
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000413};
Tim Peters9ad4b682002-02-13 05:14:18 +0000414
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000415static int initialized;
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000416static PyTypeObject StructTimeType;
417
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400418
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000419static PyObject *
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -0400420tmtotuple(struct tm *p
421#ifndef HAVE_STRUCT_TM_TM_ZONE
Victor Stinner0d659e52017-04-25 01:22:42 +0200422 , const char *zone, time_t gmtoff
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -0400423#endif
424)
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000425{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000426 PyObject *v = PyStructSequence_New(&StructTimeType);
427 if (v == NULL)
428 return NULL;
Tim Peters9ad4b682002-02-13 05:14:18 +0000429
Christian Heimes217cfd12007-12-02 14:31:20 +0000430#define SET(i,val) PyStructSequence_SET_ITEM(v, i, PyLong_FromLong((long) val))
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000431
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000432 SET(0, p->tm_year + 1900);
433 SET(1, p->tm_mon + 1); /* Want January == 1 */
434 SET(2, p->tm_mday);
435 SET(3, p->tm_hour);
436 SET(4, p->tm_min);
437 SET(5, p->tm_sec);
438 SET(6, (p->tm_wday + 6) % 7); /* Want Monday == 0 */
439 SET(7, p->tm_yday + 1); /* Want January, 1 == 1 */
440 SET(8, p->tm_isdst);
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400441#ifdef HAVE_STRUCT_TM_TM_ZONE
442 PyStructSequence_SET_ITEM(v, 9,
Victor Stinner7ed7aea2018-01-15 10:45:49 +0100443 PyUnicode_DecodeLocale(p->tm_zone, "surrogateescape"));
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400444 SET(10, p->tm_gmtoff);
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -0400445#else
446 PyStructSequence_SET_ITEM(v, 9,
Victor Stinner7ed7aea2018-01-15 10:45:49 +0100447 PyUnicode_DecodeLocale(zone, "surrogateescape"));
Victor Stinner0d659e52017-04-25 01:22:42 +0200448 PyStructSequence_SET_ITEM(v, 10, _PyLong_FromTime_t(gmtoff));
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400449#endif /* HAVE_STRUCT_TM_TM_ZONE */
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000450#undef SET
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000451 if (PyErr_Occurred()) {
452 Py_XDECREF(v);
453 return NULL;
454 }
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000455
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000456 return v;
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000457}
458
Fred Drakef901abd2004-08-03 17:58:55 +0000459/* Parse arg tuple that can contain an optional float-or-None value;
460 format needs to be "|O:name".
461 Returns non-zero on success (parallels PyArg_ParseTuple).
462*/
463static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +0200464parse_time_t_args(PyObject *args, const char *format, time_t *pwhen)
Fred Drakef901abd2004-08-03 17:58:55 +0000465{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000466 PyObject *ot = NULL;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100467 time_t whent;
Fred Drakef901abd2004-08-03 17:58:55 +0000468
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000469 if (!PyArg_ParseTuple(args, format, &ot))
470 return 0;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100471 if (ot == NULL || ot == Py_None) {
472 whent = time(NULL);
473 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000474 else {
Victor Stinner02937aa2015-03-28 05:02:39 +0100475 if (_PyTime_ObjectToTime_t(ot, &whent, _PyTime_ROUND_FLOOR) == -1)
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100476 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000477 }
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100478 *pwhen = whent;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000479 return 1;
Fred Drakef901abd2004-08-03 17:58:55 +0000480}
481
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000482static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000483time_gmtime(PyObject *self, PyObject *args)
Guido van Rossum234f9421993-06-17 12:35:49 +0000484{
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100485 time_t when;
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -0400486 struct tm buf;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100487
488 if (!parse_time_t_args(args, "|O:gmtime", &when))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000489 return NULL;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100490
491 errno = 0;
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -0400492 if (_PyTime_gmtime(when, &buf) != 0)
493 return NULL;
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -0400494#ifdef HAVE_STRUCT_TM_TM_ZONE
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100495 return tmtotuple(&buf);
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -0400496#else
497 return tmtotuple(&buf, "UTC", 0);
498#endif
Guido van Rossum234f9421993-06-17 12:35:49 +0000499}
500
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -0400501#ifndef HAVE_TIMEGM
502static time_t
503timegm(struct tm *p)
504{
505 /* XXX: the following implementation will not work for tm_year < 1970.
506 but it is likely that platforms that don't have timegm do not support
507 negative timestamps anyways. */
508 return p->tm_sec + p->tm_min*60 + p->tm_hour*3600 + p->tm_yday*86400 +
509 (p->tm_year-70)*31536000 + ((p->tm_year-69)/4)*86400 -
510 ((p->tm_year-1)/100)*86400 + ((p->tm_year+299)/400)*86400;
511}
512#endif
513
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000514PyDoc_STRVAR(gmtime_doc,
Christian Heimes9a371592007-12-28 14:08:13 +0000515"gmtime([seconds]) -> (tm_year, tm_mon, tm_mday, tm_hour, tm_min,\n\
Fred Drake193a3f62002-03-12 21:38:49 +0000516 tm_sec, tm_wday, tm_yday, tm_isdst)\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000517\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000518Convert seconds since the Epoch to a time tuple expressing UTC (a.k.a.\n\
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400519GMT). When 'seconds' is not passed in, convert the current time instead.\n\
520\n\
521If the platform supports the tm_gmtoff and tm_zone, they are available as\n\
522attributes only.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000523
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000524static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000525time_localtime(PyObject *self, PyObject *args)
Guido van Rossum234f9421993-06-17 12:35:49 +0000526{
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100527 time_t when;
528 struct tm buf;
529
530 if (!parse_time_t_args(args, "|O:localtime", &when))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000531 return NULL;
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -0400532 if (_PyTime_localtime(when, &buf) != 0)
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100533 return NULL;
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -0400534#ifdef HAVE_STRUCT_TM_TM_ZONE
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100535 return tmtotuple(&buf);
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -0400536#else
537 {
538 struct tm local = buf;
539 char zone[100];
Victor Stinner0d659e52017-04-25 01:22:42 +0200540 time_t gmtoff;
Steve Dowerc3c6f712016-12-14 11:22:05 -0800541 strftime(zone, sizeof(zone), "%Z", &buf);
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -0400542 gmtoff = timegm(&buf) - when;
543 return tmtotuple(&local, zone, gmtoff);
544 }
545#endif
Guido van Rossum234f9421993-06-17 12:35:49 +0000546}
547
Benjamin Peterson5633c4f2018-09-14 09:09:04 -0700548#if defined(__linux__) && !defined(__GLIBC__)
549static const char *utc_string = NULL;
550#endif
551
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000552PyDoc_STRVAR(localtime_doc,
Christian Heimes9a371592007-12-28 14:08:13 +0000553"localtime([seconds]) -> (tm_year,tm_mon,tm_mday,tm_hour,tm_min,\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000554 tm_sec,tm_wday,tm_yday,tm_isdst)\n\
Martin v. Löwisb3cfc1d2001-12-02 12:27:43 +0000555\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000556Convert seconds since the Epoch to a time tuple expressing local time.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000557When 'seconds' is not passed in, convert the current time instead.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000558
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000559/* Convert 9-item tuple to tm structure. Return 1 on success, set
560 * an exception and return 0 on error.
561 */
Guido van Rossum9e90a671993-06-24 11:10:19 +0000562static int
Oren Milman1d1d3e92017-08-20 18:35:36 +0300563gettmarg(PyObject *args, struct tm *p, const char *format)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000564{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000565 int y;
Guido van Rossumcfbaecc1998-08-25 14:51:12 +0000566
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000567 memset((void *) p, '\0', sizeof(struct tm));
Guido van Rossumb9081262007-08-25 03:14:09 +0000568
Alexander Belopolsky610e5442011-01-06 21:57:06 +0000569 if (!PyTuple_Check(args)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000570 PyErr_SetString(PyExc_TypeError,
571 "Tuple or struct_time argument required");
572 return 0;
573 }
Skip Montanaro41cfce92007-08-24 21:11:00 +0000574
Oren Milman1d1d3e92017-08-20 18:35:36 +0300575 if (!PyArg_ParseTuple(args, format,
Alexander Belopolsky610e5442011-01-06 21:57:06 +0000576 &y, &p->tm_mon, &p->tm_mday,
577 &p->tm_hour, &p->tm_min, &p->tm_sec,
578 &p->tm_wday, &p->tm_yday, &p->tm_isdst))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000579 return 0;
Gregory P. Smith76be0ff2018-08-24 18:08:50 -0700580
581 if (y < INT_MIN + 1900) {
582 PyErr_SetString(PyExc_OverflowError, "year out of range");
583 return 0;
584 }
585
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000586 p->tm_year = y - 1900;
587 p->tm_mon--;
588 p->tm_wday = (p->tm_wday + 1) % 7;
589 p->tm_yday--;
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400590#ifdef HAVE_STRUCT_TM_TM_ZONE
591 if (Py_TYPE(args) == &StructTimeType) {
592 PyObject *item;
Victor Stinner1cdfcfc2018-11-28 15:19:51 +0100593 item = PyStructSequence_GET_ITEM(args, 9);
Benjamin Peterson5633c4f2018-09-14 09:09:04 -0700594 if (item != Py_None) {
Xiang Zhang163eca32018-10-28 23:58:42 +0800595 p->tm_zone = (char *)PyUnicode_AsUTF8(item);
Benjamin Peterson5633c4f2018-09-14 09:09:04 -0700596 if (p->tm_zone == NULL) {
597 return 0;
598 }
599#if defined(__linux__) && !defined(__GLIBC__)
600 // Make an attempt to return the C library's own timezone strings to
601 // it. musl refuses to process a tm_zone field unless it produced
602 // it. See issue #34672.
603 if (utc_string && strcmp(p->tm_zone, utc_string) == 0) {
604 p->tm_zone = utc_string;
605 }
606 else if (tzname[0] && strcmp(p->tm_zone, tzname[0]) == 0) {
607 p->tm_zone = tzname[0];
608 }
609 else if (tzname[1] && strcmp(p->tm_zone, tzname[1]) == 0) {
610 p->tm_zone = tzname[1];
611 }
612#endif
613 }
Victor Stinner1cdfcfc2018-11-28 15:19:51 +0100614 item = PyStructSequence_GET_ITEM(args, 10);
Benjamin Peterson5633c4f2018-09-14 09:09:04 -0700615 if (item != Py_None) {
616 p->tm_gmtoff = PyLong_AsLong(item);
617 if (PyErr_Occurred())
618 return 0;
619 }
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400620 }
621#endif /* HAVE_STRUCT_TM_TM_ZONE */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000622 return 1;
Guido van Rossum9e90a671993-06-24 11:10:19 +0000623}
624
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000625/* Check values of the struct tm fields before it is passed to strftime() and
626 * asctime(). Return 1 if all values are valid, otherwise set an exception
627 * and returns 0.
628 */
Victor Stinneref128102010-10-07 01:00:52 +0000629static int
630checktm(struct tm* buf)
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000631{
Victor Stinneref128102010-10-07 01:00:52 +0000632 /* Checks added to make sure strftime() and asctime() does not crash Python by
633 indexing blindly into some array for a textual representation
634 by some bad index (fixes bug #897625 and #6608).
635
636 Also support values of zero from Python code for arguments in which
637 that is out of range by forcing that value to the lowest value that
638 is valid (fixed bug #1520914).
639
640 Valid ranges based on what is allowed in struct tm:
641
642 - tm_year: [0, max(int)] (1)
643 - tm_mon: [0, 11] (2)
644 - tm_mday: [1, 31]
645 - tm_hour: [0, 23]
646 - tm_min: [0, 59]
647 - tm_sec: [0, 60]
648 - tm_wday: [0, 6] (1)
649 - tm_yday: [0, 365] (2)
650 - tm_isdst: [-max(int), max(int)]
651
652 (1) gettmarg() handles bounds-checking.
653 (2) Python's acceptable range is one greater than the range in C,
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000654 thus need to check against automatic decrement by gettmarg().
655 */
656 if (buf->tm_mon == -1)
657 buf->tm_mon = 0;
658 else if (buf->tm_mon < 0 || buf->tm_mon > 11) {
659 PyErr_SetString(PyExc_ValueError, "month out of range");
660 return 0;
661 }
662 if (buf->tm_mday == 0)
663 buf->tm_mday = 1;
664 else if (buf->tm_mday < 0 || buf->tm_mday > 31) {
665 PyErr_SetString(PyExc_ValueError, "day of month out of range");
666 return 0;
667 }
668 if (buf->tm_hour < 0 || buf->tm_hour > 23) {
669 PyErr_SetString(PyExc_ValueError, "hour out of range");
670 return 0;
671 }
672 if (buf->tm_min < 0 || buf->tm_min > 59) {
673 PyErr_SetString(PyExc_ValueError, "minute out of range");
674 return 0;
675 }
676 if (buf->tm_sec < 0 || buf->tm_sec > 61) {
677 PyErr_SetString(PyExc_ValueError, "seconds out of range");
678 return 0;
679 }
680 /* tm_wday does not need checking of its upper-bound since taking
681 ``% 7`` in gettmarg() automatically restricts the range. */
682 if (buf->tm_wday < 0) {
683 PyErr_SetString(PyExc_ValueError, "day of week out of range");
684 return 0;
685 }
686 if (buf->tm_yday == -1)
687 buf->tm_yday = 0;
688 else if (buf->tm_yday < 0 || buf->tm_yday > 365) {
689 PyErr_SetString(PyExc_ValueError, "day of year out of range");
690 return 0;
691 }
692 return 1;
693}
694
Victor Stinnerc1f32ca2011-10-14 02:36:13 +0200695#ifdef MS_WINDOWS
696 /* wcsftime() doesn't format correctly time zones, see issue #10653 */
697# undef HAVE_WCSFTIME
698#endif
Alexander Belopolskycf774542012-10-02 18:39:16 -0400699#define STRFTIME_FORMAT_CODES \
700"Commonly used format codes:\n\
701\n\
702%Y Year with century as a decimal number.\n\
703%m Month as a decimal number [01,12].\n\
704%d Day of the month as a decimal number [01,31].\n\
705%H Hour (24-hour clock) as a decimal number [00,23].\n\
706%M Minute as a decimal number [00,59].\n\
707%S Second as a decimal number [00,61].\n\
708%z Time zone offset from UTC.\n\
709%a Locale's abbreviated weekday name.\n\
710%A Locale's full weekday name.\n\
711%b Locale's abbreviated month name.\n\
712%B Locale's full month name.\n\
713%c Locale's appropriate date and time representation.\n\
714%I Hour (12-hour clock) as a decimal number [01,12].\n\
715%p Locale's equivalent of either AM or PM.\n\
716\n\
717Other codes may be available on your platform. See documentation for\n\
718the C library strftime function.\n"
Victor Stinnerc1f32ca2011-10-14 02:36:13 +0200719
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000720#ifdef HAVE_STRFTIME
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000721#ifdef HAVE_WCSFTIME
722#define time_char wchar_t
723#define format_time wcsftime
724#define time_strlen wcslen
725#else
726#define time_char char
727#define format_time strftime
728#define time_strlen strlen
729#endif
730
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000731static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000732time_strftime(PyObject *self, PyObject *args)
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000733{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000734 PyObject *tup = NULL;
735 struct tm buf;
736 const time_char *fmt;
Victor Stinnerb2904782010-09-29 10:34:19 +0000737#ifdef HAVE_WCSFTIME
738 wchar_t *format;
739#else
740 PyObject *format;
741#endif
Victor Stinneref128102010-10-07 01:00:52 +0000742 PyObject *format_arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000743 size_t fmtlen, buflen;
Victor Stinnerb2904782010-09-29 10:34:19 +0000744 time_char *outbuf = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000745 size_t i;
Victor Stinnerb2904782010-09-29 10:34:19 +0000746 PyObject *ret = NULL;
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000747
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000748 memset((void *) &buf, '\0', sizeof(buf));
Guido van Rossum1f41f841998-04-27 19:04:26 +0000749
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000750 /* Will always expect a unicode string to be passed as format.
751 Given that there's no str type anymore in py3k this seems safe.
752 */
Victor Stinneref128102010-10-07 01:00:52 +0000753 if (!PyArg_ParseTuple(args, "U|O:strftime", &format_arg, &tup))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000754 return NULL;
Thomas Woutersfe385252001-01-19 23:16:56 +0000755
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000756 if (tup == NULL) {
757 time_t tt = time(NULL);
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -0400758 if (_PyTime_localtime(tt, &buf) != 0)
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100759 return NULL;
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000760 }
Oren Milman1d1d3e92017-08-20 18:35:36 +0300761 else if (!gettmarg(tup, &buf,
762 "iiiiiiiii;strftime(): illegal time tuple argument") ||
763 !checktm(&buf))
764 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000765 return NULL;
Oren Milman1d1d3e92017-08-20 18:35:36 +0300766 }
Guido van Rossum10b164a2001-09-25 13:59:01 +0000767
pxinwrf1464f42019-04-15 17:06:21 +0800768#if defined(_MSC_VER) || (defined(__sun) && defined(__SVR4)) || defined(_AIX) || defined(__VXWORKS__)
Victor Stinner73ea29c2011-01-08 01:56:31 +0000769 if (buf.tm_year + 1900 < 1 || 9999 < buf.tm_year + 1900) {
Victor Stinner6f0e4f92011-03-21 02:14:53 +0100770 PyErr_SetString(PyExc_ValueError,
771 "strftime() requires year in [1; 9999]");
Alexander Belopolsky0dd06f42011-01-08 01:23:02 +0000772 return NULL;
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000773 }
Victor Stinner73ea29c2011-01-08 01:56:31 +0000774#endif
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000775
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000776 /* Normalize tm_isdst just in case someone foolishly implements %Z
777 based on the assumption that tm_isdst falls within the range of
778 [-1, 1] */
779 if (buf.tm_isdst < -1)
780 buf.tm_isdst = -1;
781 else if (buf.tm_isdst > 1)
782 buf.tm_isdst = 1;
Brett Cannond1080a32004-03-02 04:38:10 +0000783
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000784#ifdef HAVE_WCSFTIME
Victor Stinnerbeb4135b2010-10-07 01:02:42 +0000785 format = PyUnicode_AsWideCharString(format_arg, NULL);
Victor Stinnerb2904782010-09-29 10:34:19 +0000786 if (format == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000787 return NULL;
Victor Stinnerb2904782010-09-29 10:34:19 +0000788 fmt = format;
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000789#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000790 /* Convert the unicode string to an ascii one */
Victor Stinner1b579672011-12-17 05:47:23 +0100791 format = PyUnicode_EncodeLocale(format_arg, "surrogateescape");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000792 if (format == NULL)
793 return NULL;
794 fmt = PyBytes_AS_STRING(format);
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000795#endif
Amaury Forgeot d'Arcb5be6d42009-03-02 23:52:57 +0000796
Stefan Krah4aea7d32012-02-27 16:30:26 +0100797#if defined(MS_WINDOWS) && !defined(HAVE_WCSFTIME)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000798 /* check that the format string contains only valid directives */
Steve Dowere5b58952015-09-06 19:20:51 -0700799 for (outbuf = strchr(fmt, '%');
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000800 outbuf != NULL;
Victor Stinner5a3ff792011-10-16 19:08:23 +0200801 outbuf = strchr(outbuf+2, '%'))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000802 {
Steve Dowere5b58952015-09-06 19:20:51 -0700803 if (outbuf[1] == '#')
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000804 ++outbuf; /* not documented by python, */
Steve Dowere5b58952015-09-06 19:20:51 -0700805 if (outbuf[1] == '\0')
806 break;
807 if ((outbuf[1] == 'y') && buf.tm_year < 0) {
Tim Golden6e51b8f2013-11-12 12:36:54 +0000808 PyErr_SetString(PyExc_ValueError,
809 "format %y requires year >= 1900 on Windows");
810 Py_DECREF(format);
811 return NULL;
812 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000813 }
Jakub Kulík6f9bc722018-12-31 03:16:40 +0100814#elif (defined(_AIX) || (defined(__sun) && defined(__SVR4))) && defined(HAVE_WCSFTIME)
Steve Dowere5b58952015-09-06 19:20:51 -0700815 for (outbuf = wcschr(fmt, '%');
Victor Stinner55329f82013-11-17 23:39:21 +0100816 outbuf != NULL;
817 outbuf = wcschr(outbuf+2, '%'))
818 {
Steve Dowere5b58952015-09-06 19:20:51 -0700819 if (outbuf[1] == L'\0')
820 break;
Victor Stinner55329f82013-11-17 23:39:21 +0100821 /* Issue #19634: On AIX, wcsftime("y", (1899, 1, 1, 0, 0, 0, 0, 0, 0))
822 returns "0/" instead of "99" */
823 if (outbuf[1] == L'y' && buf.tm_year < 0) {
824 PyErr_SetString(PyExc_ValueError,
825 "format %y requires year >= 1900 on AIX");
Zackery Spytz91e6c872018-09-21 00:09:48 -0600826 PyMem_Free(format);
Victor Stinner55329f82013-11-17 23:39:21 +0100827 return NULL;
828 }
829 }
Amaury Forgeot d'Arcb5be6d42009-03-02 23:52:57 +0000830#endif
831
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000832 fmtlen = time_strlen(fmt);
Guido van Rossumc222ec21999-02-23 00:00:10 +0000833
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000834 /* I hate these functions that presume you know how big the output
835 * will be ahead of time...
836 */
837 for (i = 1024; ; i += i) {
838 outbuf = (time_char *)PyMem_Malloc(i*sizeof(time_char));
839 if (outbuf == NULL) {
Victor Stinnerb2904782010-09-29 10:34:19 +0000840 PyErr_NoMemory();
841 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000842 }
Steve Dower57ab1cd2015-09-22 14:51:42 -0700843#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
844 errno = 0;
845#endif
Steve Dowerd9ef74e2015-05-22 15:08:34 -0700846 _Py_BEGIN_SUPPRESS_IPH
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000847 buflen = format_time(outbuf, i, fmt, &buf);
Steve Dowerd9ef74e2015-05-22 15:08:34 -0700848 _Py_END_SUPPRESS_IPH
Victor Stinner136ea492011-12-17 22:37:18 +0100849#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
Steve Dower97cded92015-09-08 19:12:51 -0700850 /* VisualStudio .NET 2005 does this properly */
851 if (buflen == 0 && errno == EINVAL) {
852 PyErr_SetString(PyExc_ValueError, "Invalid format string");
853 PyMem_Free(outbuf);
854 break;
855 }
Victor Stinner136ea492011-12-17 22:37:18 +0100856#endif
Steve Dower97cded92015-09-08 19:12:51 -0700857 if (buflen > 0 || i >= 256 * fmtlen) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000858 /* If the buffer is 256 times as long as the format,
859 it's probably not failing for lack of room!
860 More likely, the format yields an empty result,
861 e.g. an empty format, or %Z when the timezone
862 is unknown. */
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000863#ifdef HAVE_WCSFTIME
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000864 ret = PyUnicode_FromWideChar(outbuf, buflen);
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000865#else
Victor Stinner7ed7aea2018-01-15 10:45:49 +0100866 ret = PyUnicode_DecodeLocaleAndSize(outbuf, buflen, "surrogateescape");
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000867#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000868 PyMem_Free(outbuf);
Victor Stinnerb2904782010-09-29 10:34:19 +0000869 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000870 }
871 PyMem_Free(outbuf);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000872 }
Victor Stinnerb2904782010-09-29 10:34:19 +0000873#ifdef HAVE_WCSFTIME
874 PyMem_Free(format);
875#else
876 Py_DECREF(format);
877#endif
878 return ret;
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000879}
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000880
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000881#undef time_char
882#undef format_time
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000883PyDoc_STRVAR(strftime_doc,
Thomas Woutersfe385252001-01-19 23:16:56 +0000884"strftime(format[, tuple]) -> string\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000885\n\
886Convert a time tuple to a string according to a format specification.\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000887See the library reference manual for formatting codes. When the time tuple\n\
Alexander Belopolskycf774542012-10-02 18:39:16 -0400888is not present, current time as returned by localtime() is used.\n\
889\n" STRFTIME_FORMAT_CODES);
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000890#endif /* HAVE_STRFTIME */
891
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000892static PyObject *
893time_strptime(PyObject *self, PyObject *args)
894{
Victor Stinnerdbe28d22016-12-09 00:38:53 +0100895 PyObject *module, *func, *result;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200896 _Py_IDENTIFIER(_strptime_time);
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000897
Victor Stinnerdbe28d22016-12-09 00:38:53 +0100898 module = PyImport_ImportModuleNoBlock("_strptime");
899 if (!module)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000900 return NULL;
Victor Stinnerdbe28d22016-12-09 00:38:53 +0100901
902 func = _PyObject_GetAttrId(module, &PyId__strptime_time);
903 Py_DECREF(module);
904 if (!func) {
905 return NULL;
906 }
907
908 result = PyObject_Call(func, args, NULL);
909 Py_DECREF(func);
910 return result;
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000911}
912
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000913
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000914PyDoc_STRVAR(strptime_doc,
Brett Cannon20def8b2003-07-01 05:16:08 +0000915"strptime(string, format) -> struct_time\n\
Martin v. Löwisb3cfc1d2001-12-02 12:27:43 +0000916\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000917Parse a string to a time tuple according to a format specification.\n\
Alexander Belopolskycf774542012-10-02 18:39:16 -0400918See the library reference manual for formatting codes (same as\n\
919strftime()).\n\
920\n" STRFTIME_FORMAT_CODES);
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000921
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000922static PyObject *
923_asctime(struct tm *timeptr)
924{
925 /* Inspired by Open Group reference implementation available at
926 * http://pubs.opengroup.org/onlinepubs/009695399/functions/asctime.html */
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200927 static const char wday_name[7][4] = {
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000928 "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
929 };
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200930 static const char mon_name[12][4] = {
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000931 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
932 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
933 };
Victor Stinner499dfcf2011-03-21 13:26:24 +0100934 return PyUnicode_FromFormat(
935 "%s %s%3d %.2d:%.2d:%.2d %d",
936 wday_name[timeptr->tm_wday],
937 mon_name[timeptr->tm_mon],
938 timeptr->tm_mday, timeptr->tm_hour,
939 timeptr->tm_min, timeptr->tm_sec,
940 1900 + timeptr->tm_year);
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000941}
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000942
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000943static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000944time_asctime(PyObject *self, PyObject *args)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000945{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000946 PyObject *tup = NULL;
947 struct tm buf;
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000948
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000949 if (!PyArg_UnpackTuple(args, "asctime", 0, 1, &tup))
950 return NULL;
951 if (tup == NULL) {
952 time_t tt = time(NULL);
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -0400953 if (_PyTime_localtime(tt, &buf) != 0)
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100954 return NULL;
Oren Milman1d1d3e92017-08-20 18:35:36 +0300955 }
956 else if (!gettmarg(tup, &buf,
957 "iiiiiiiii;asctime(): illegal time tuple argument") ||
958 !checktm(&buf))
959 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000960 return NULL;
Oren Milman1d1d3e92017-08-20 18:35:36 +0300961 }
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000962 return _asctime(&buf);
Guido van Rossum9e90a671993-06-24 11:10:19 +0000963}
964
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000965PyDoc_STRVAR(asctime_doc,
Thomas Woutersfe385252001-01-19 23:16:56 +0000966"asctime([tuple]) -> string\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000967\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000968Convert a time tuple to a string, e.g. 'Sat Jun 06 16:26:11 1998'.\n\
969When the time tuple is not present, current time as returned by localtime()\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000970is used.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000971
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000972static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000973time_ctime(PyObject *self, PyObject *args)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000974{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000975 time_t tt;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100976 struct tm buf;
977 if (!parse_time_t_args(args, "|O:ctime", &tt))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000978 return NULL;
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -0400979 if (_PyTime_localtime(tt, &buf) != 0)
Alexander Belopolsky5da468f2011-01-04 17:15:52 +0000980 return NULL;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100981 return _asctime(&buf);
Guido van Rossum9e90a671993-06-24 11:10:19 +0000982}
983
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000984PyDoc_STRVAR(ctime_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000985"ctime(seconds) -> string\n\
986\n\
987Convert a time in seconds since the Epoch to a string in local time.\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000988This is equivalent to asctime(localtime(seconds)). When the time tuple is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000989not present, current time as returned by localtime() is used.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000990
Guido van Rossum60cd8131998-03-06 17:16:21 +0000991#ifdef HAVE_MKTIME
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000992static PyObject *
Victor Stinner87094902019-04-09 19:12:26 +0200993time_mktime(PyObject *self, PyObject *tm_tuple)
Guido van Rossum234f9421993-06-17 12:35:49 +0000994{
Victor Stinner87094902019-04-09 19:12:26 +0200995 struct tm tm;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000996 time_t tt;
Michael Felte2926b72018-12-28 14:57:37 +0100997
Victor Stinner87094902019-04-09 19:12:26 +0200998 if (!gettmarg(tm_tuple, &tm,
Oren Milman1d1d3e92017-08-20 18:35:36 +0300999 "iiiiiiiii;mktime(): illegal time tuple argument"))
1000 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001001 return NULL;
Oren Milman1d1d3e92017-08-20 18:35:36 +03001002 }
Victor Stinner87094902019-04-09 19:12:26 +02001003
pxinwrf1464f42019-04-15 17:06:21 +08001004#if defined(_AIX) || (defined(__VXWORKS__) && !defined(_WRS_CONFIG_LP64))
Victor Stinner87094902019-04-09 19:12:26 +02001005 /* bpo-19748: AIX mktime() valid range is 00:00:00 UTC, January 1, 1970
1006 to 03:14:07 UTC, January 19, 2038. Thanks to the workaround below,
1007 it is possible to support years in range [1902; 2037] */
1008 if (tm.tm_year < 2 || tm.tm_year > 137) {
1009 /* bpo-19748: On AIX, mktime() does not report overflow error
pxinwrf1464f42019-04-15 17:06:21 +08001010 for timestamp < -2^31 or timestamp > 2**31-1. VxWorks has the
1011 same issue when working in 32 bit mode. */
Victor Stinner1ac42612014-02-21 09:27:17 +01001012 PyErr_SetString(PyExc_OverflowError,
1013 "mktime argument out of range");
1014 return NULL;
1015 }
pxinwrf1464f42019-04-15 17:06:21 +08001016#endif
Victor Stinner87094902019-04-09 19:12:26 +02001017
pxinwrf1464f42019-04-15 17:06:21 +08001018#ifdef _AIX
Victor Stinner87094902019-04-09 19:12:26 +02001019 /* bpo-34373: AIX mktime() has an integer overflow for years in range
1020 [1902; 1969]. Workaround the issue by using a year greater or equal than
1021 1970 (tm_year >= 70): mktime() behaves correctly in that case
1022 (ex: properly report errors). tm_year and tm_wday are adjusted after
1023 mktime() call. */
1024 int orig_tm_year = tm.tm_year;
1025 int delta_days = 0;
1026 while (tm.tm_year < 70) {
1027 /* Use 4 years to account properly leap years */
1028 tm.tm_year += 4;
Michael Felte2926b72018-12-28 14:57:37 +01001029 delta_days -= (366 + (365 * 3));
1030 }
Victor Stinner1ac42612014-02-21 09:27:17 +01001031#endif
Victor Stinner87094902019-04-09 19:12:26 +02001032
1033 tm.tm_wday = -1; /* sentinel; original value ignored */
1034 tt = mktime(&tm);
1035
Alexander Belopolskyb7d40d12011-01-11 01:21:25 +00001036 /* Return value of -1 does not necessarily mean an error, but tm_wday
Ezio Melotti13925002011-03-16 11:05:33 +02001037 * cannot remain set to -1 if mktime succeeded. */
Victor Stinner93037492013-06-25 22:54:35 +02001038 if (tt == (time_t)(-1)
Victor Stinner93037492013-06-25 22:54:35 +02001039 /* Return value of -1 does not necessarily mean an error, but
1040 * tm_wday cannot remain set to -1 if mktime succeeded. */
Victor Stinner87094902019-04-09 19:12:26 +02001041 && tm.tm_wday == -1)
Victor Stinner93037492013-06-25 22:54:35 +02001042 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001043 PyErr_SetString(PyExc_OverflowError,
1044 "mktime argument out of range");
1045 return NULL;
1046 }
Victor Stinner87094902019-04-09 19:12:26 +02001047
1048#ifdef _AIX
1049 if (delta_days != 0) {
1050 tm.tm_year = orig_tm_year;
1051 if (tm.tm_wday != -1) {
1052 tm.tm_wday = (tm.tm_wday + delta_days) % 7;
1053 }
1054 tt += delta_days * (24 * 3600);
1055 }
1056#endif
1057
Victor Stinner4195b5c2012-02-08 23:03:19 +01001058 return PyFloat_FromDouble((double)tt);
Guido van Rossum234f9421993-06-17 12:35:49 +00001059}
Guido van Rossum0ef577b1998-06-27 20:38:36 +00001060
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001061PyDoc_STRVAR(mktime_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +00001062"mktime(tuple) -> floating point number\n\
1063\n\
Alexander Belopolskyc142bba2012-06-13 22:15:26 -04001064Convert a time tuple in local time to seconds since the Epoch.\n\
1065Note that mktime(gmtime(0)) will not generally return zero for most\n\
1066time zones; instead the returned value will either be equal to that\n\
1067of the timezone or altzone attributes on the time module.");
Guido van Rossum60cd8131998-03-06 17:16:21 +00001068#endif /* HAVE_MKTIME */
Guido van Rossum234f9421993-06-17 12:35:49 +00001069
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001070#ifdef HAVE_WORKING_TZSET
Victor Stinner3bb150d2018-12-03 13:45:38 +01001071static int init_timezone(PyObject *module);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001072
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001073static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001074time_tzset(PyObject *self, PyObject *unused)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001075{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001076 PyObject* m;
Fred Drake9bb74322002-04-01 14:49:59 +00001077
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001078 m = PyImport_ImportModuleNoBlock("time");
1079 if (m == NULL) {
1080 return NULL;
1081 }
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001082
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001083 tzset();
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001084
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001085 /* Reset timezone, altzone, daylight and tzname */
Victor Stinner3bb150d2018-12-03 13:45:38 +01001086 if (init_timezone(m) < 0) {
Victor Stinner503ce5c2018-12-01 00:39:36 +01001087 return NULL;
1088 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001089 Py_DECREF(m);
Victor Stinner2ff51b82013-07-17 21:42:45 +02001090 if (PyErr_Occurred())
1091 return NULL;
Tim Peters1b6f7a92004-06-20 02:50:16 +00001092
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001093 Py_RETURN_NONE;
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001094}
1095
1096PyDoc_STRVAR(tzset_doc,
R. David Murray4d55bf92010-12-14 00:55:46 +00001097"tzset()\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001098\n\
1099Initialize, or reinitialize, the local timezone to the value stored in\n\
1100os.environ['TZ']. The TZ environment variable should be specified in\n\
Neal Norwitzdc8e1942004-07-20 22:34:37 +00001101standard Unix timezone format as documented in the tzset man page\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001102(eg. 'US/Eastern', 'Europe/Amsterdam'). Unknown timezones will silently\n\
1103fall back to UTC. If the TZ environment variable is not set, the local\n\
1104timezone is set to the systems best guess of wallclock time.\n\
1105Changing the TZ environment variable without calling tzset *may* change\n\
1106the local timezone used by methods such as localtime, but this behaviour\n\
1107should not be relied on.");
1108#endif /* HAVE_WORKING_TZSET */
1109
Victor Stinnerae586492014-09-02 23:18:25 +02001110static PyObject *
Victor Stinnerec895392012-04-29 02:41:27 +02001111time_monotonic(PyObject *self, PyObject *unused)
Victor Stinner071eca32012-03-15 01:17:09 +01001112{
Victor Stinnerc29b5852017-11-02 07:28:27 -07001113 _PyTime_t t = _PyTime_GetMonotonicClock();
1114 return _PyFloat_FromPyTime(t);
Victor Stinner071eca32012-03-15 01:17:09 +01001115}
1116
Victor Stinnerec895392012-04-29 02:41:27 +02001117PyDoc_STRVAR(monotonic_doc,
1118"monotonic() -> float\n\
Victor Stinner8b302012012-02-07 23:29:46 +01001119\n\
Victor Stinnerec895392012-04-29 02:41:27 +02001120Monotonic clock, cannot go backward.");
Victor Stinnerec919cc2012-03-15 00:58:32 +01001121
Victor Stinnerec895392012-04-29 02:41:27 +02001122static PyObject *
Victor Stinnerc29b5852017-11-02 07:28:27 -07001123time_monotonic_ns(PyObject *self, PyObject *unused)
1124{
1125 _PyTime_t t = _PyTime_GetMonotonicClock();
1126 return _PyTime_AsNanosecondsObject(t);
1127}
1128
1129PyDoc_STRVAR(monotonic_ns_doc,
1130"monotonic_ns() -> int\n\
1131\n\
1132Monotonic clock, cannot go backward, as nanoseconds.");
1133
1134static PyObject *
Victor Stinnerec895392012-04-29 02:41:27 +02001135time_perf_counter(PyObject *self, PyObject *unused)
1136{
1137 return perf_counter(NULL);
1138}
1139
1140PyDoc_STRVAR(perf_counter_doc,
1141"perf_counter() -> float\n\
1142\n\
1143Performance counter for benchmarking.");
1144
Victor Stinnerc29b5852017-11-02 07:28:27 -07001145static PyObject *
1146time_perf_counter_ns(PyObject *self, PyObject *unused)
1147{
1148 _PyTime_t t = _PyTime_GetPerfCounter();
1149 return _PyTime_AsNanosecondsObject(t);
1150}
1151
1152PyDoc_STRVAR(perf_counter_ns_doc,
1153"perf_counter_ns() -> int\n\
1154\n\
1155Performance counter for benchmarking as nanoseconds.");
1156
1157static int
1158_PyTime_GetProcessTimeWithInfo(_PyTime_t *tp, _Py_clock_info_t *info)
Victor Stinnerec895392012-04-29 02:41:27 +02001159{
1160#if defined(MS_WINDOWS)
1161 HANDLE process;
1162 FILETIME creation_time, exit_time, kernel_time, user_time;
1163 ULARGE_INTEGER large;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001164 _PyTime_t ktime, utime, t;
Victor Stinnerec895392012-04-29 02:41:27 +02001165 BOOL ok;
1166
1167 process = GetCurrentProcess();
Victor Stinnerc29b5852017-11-02 07:28:27 -07001168 ok = GetProcessTimes(process, &creation_time, &exit_time,
1169 &kernel_time, &user_time);
1170 if (!ok) {
1171 PyErr_SetFromWindowsErr(0);
1172 return -1;
1173 }
Victor Stinnerec895392012-04-29 02:41:27 +02001174
Victor Stinnerec895392012-04-29 02:41:27 +02001175 if (info) {
1176 info->implementation = "GetProcessTimes()";
1177 info->resolution = 1e-7;
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001178 info->monotonic = 1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001179 info->adjustable = 0;
Victor Stinnerec895392012-04-29 02:41:27 +02001180 }
Victor Stinnerc29b5852017-11-02 07:28:27 -07001181
1182 large.u.LowPart = kernel_time.dwLowDateTime;
1183 large.u.HighPart = kernel_time.dwHighDateTime;
1184 ktime = large.QuadPart;
1185
1186 large.u.LowPart = user_time.dwLowDateTime;
1187 large.u.HighPart = user_time.dwHighDateTime;
1188 utime = large.QuadPart;
1189
1190 /* ktime and utime have a resolution of 100 nanoseconds */
1191 t = _PyTime_FromNanoseconds((ktime + utime) * 100);
1192 *tp = t;
1193 return 0;
Victor Stinnerec895392012-04-29 02:41:27 +02001194#else
1195
Victor Stinnerc29b5852017-11-02 07:28:27 -07001196 /* clock_gettime */
Victor Stinnerec895392012-04-29 02:41:27 +02001197#if defined(HAVE_CLOCK_GETTIME) \
1198 && (defined(CLOCK_PROCESS_CPUTIME_ID) || defined(CLOCK_PROF))
Victor Stinnerc29b5852017-11-02 07:28:27 -07001199 struct timespec ts;
Victor Stinnerec895392012-04-29 02:41:27 +02001200#ifdef CLOCK_PROF
1201 const clockid_t clk_id = CLOCK_PROF;
1202 const char *function = "clock_gettime(CLOCK_PROF)";
1203#else
1204 const clockid_t clk_id = CLOCK_PROCESS_CPUTIME_ID;
1205 const char *function = "clock_gettime(CLOCK_PROCESS_CPUTIME_ID)";
1206#endif
1207
Victor Stinnerc29b5852017-11-02 07:28:27 -07001208 if (clock_gettime(clk_id, &ts) == 0) {
Victor Stinnerec895392012-04-29 02:41:27 +02001209 if (info) {
1210 struct timespec res;
1211 info->implementation = function;
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001212 info->monotonic = 1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001213 info->adjustable = 0;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001214 if (clock_getres(clk_id, &res)) {
1215 PyErr_SetFromErrno(PyExc_OSError);
1216 return -1;
1217 }
1218 info->resolution = res.tv_sec + res.tv_nsec * 1e-9;
Victor Stinnerec895392012-04-29 02:41:27 +02001219 }
Victor Stinnerc29b5852017-11-02 07:28:27 -07001220
1221 if (_PyTime_FromTimespec(tp, &ts) < 0) {
1222 return -1;
1223 }
1224 return 0;
Victor Stinnerec895392012-04-29 02:41:27 +02001225 }
1226#endif
1227
Victor Stinnerc29b5852017-11-02 07:28:27 -07001228 /* getrusage(RUSAGE_SELF) */
Victor Stinnerec895392012-04-29 02:41:27 +02001229#if defined(HAVE_SYS_RESOURCE_H)
Victor Stinnerc29b5852017-11-02 07:28:27 -07001230 struct rusage ru;
1231
Victor Stinnerec895392012-04-29 02:41:27 +02001232 if (getrusage(RUSAGE_SELF, &ru) == 0) {
Victor Stinnerc29b5852017-11-02 07:28:27 -07001233 _PyTime_t utime, stime;
1234
Victor Stinnerec895392012-04-29 02:41:27 +02001235 if (info) {
1236 info->implementation = "getrusage(RUSAGE_SELF)";
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001237 info->monotonic = 1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001238 info->adjustable = 0;
Victor Stinnerec895392012-04-29 02:41:27 +02001239 info->resolution = 1e-6;
1240 }
Victor Stinnerc29b5852017-11-02 07:28:27 -07001241
1242 if (_PyTime_FromTimeval(&utime, &ru.ru_utime) < 0) {
1243 return -1;
1244 }
1245 if (_PyTime_FromTimeval(&stime, &ru.ru_stime) < 0) {
1246 return -1;
1247 }
1248
1249 _PyTime_t total = utime + utime;
1250 *tp = total;
1251 return 0;
Victor Stinnerec895392012-04-29 02:41:27 +02001252 }
1253#endif
1254
Victor Stinnerc29b5852017-11-02 07:28:27 -07001255 /* times() */
Victor Stinnerec895392012-04-29 02:41:27 +02001256#ifdef HAVE_TIMES
Victor Stinnerc29b5852017-11-02 07:28:27 -07001257 struct tms t;
1258
Victor Stinnerec895392012-04-29 02:41:27 +02001259 if (times(&t) != (clock_t)-1) {
Victor Stinnerc29b5852017-11-02 07:28:27 -07001260 static long ticks_per_second = -1;
Victor Stinnerec895392012-04-29 02:41:27 +02001261
1262 if (ticks_per_second == -1) {
Victor Stinnerc29b5852017-11-02 07:28:27 -07001263 long freq;
Victor Stinnerec895392012-04-29 02:41:27 +02001264#if defined(HAVE_SYSCONF) && defined(_SC_CLK_TCK)
Victor Stinnerc29b5852017-11-02 07:28:27 -07001265 freq = sysconf(_SC_CLK_TCK);
1266 if (freq < 1) {
1267 freq = -1;
1268 }
Victor Stinnerec895392012-04-29 02:41:27 +02001269#elif defined(HZ)
Victor Stinnerc29b5852017-11-02 07:28:27 -07001270 freq = HZ;
Victor Stinnerec895392012-04-29 02:41:27 +02001271#else
Victor Stinnerc29b5852017-11-02 07:28:27 -07001272 freq = 60; /* magic fallback value; may be bogus */
Victor Stinnerec895392012-04-29 02:41:27 +02001273#endif
Victor Stinnerc29b5852017-11-02 07:28:27 -07001274
1275 if (freq != -1) {
1276 /* check that _PyTime_MulDiv(t, SEC_TO_NS, ticks_per_second)
1277 cannot overflow below */
Serhiy Storchakabfe4fd52018-02-09 17:31:26 +02001278#if LONG_MAX > _PyTime_MAX / SEC_TO_NS
Victor Stinnerc29b5852017-11-02 07:28:27 -07001279 if ((_PyTime_t)freq > _PyTime_MAX / SEC_TO_NS) {
1280 PyErr_SetString(PyExc_OverflowError,
1281 "_SC_CLK_TCK is too large");
1282 return -1;
1283 }
Serhiy Storchakabfe4fd52018-02-09 17:31:26 +02001284#endif
Victor Stinnerc29b5852017-11-02 07:28:27 -07001285
1286 ticks_per_second = freq;
1287 }
Victor Stinnerec895392012-04-29 02:41:27 +02001288 }
1289
1290 if (ticks_per_second != -1) {
Victor Stinnerec895392012-04-29 02:41:27 +02001291 if (info) {
1292 info->implementation = "times()";
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001293 info->monotonic = 1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001294 info->adjustable = 0;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001295 info->resolution = 1.0 / (double)ticks_per_second;
Victor Stinnerec895392012-04-29 02:41:27 +02001296 }
Victor Stinnerc29b5852017-11-02 07:28:27 -07001297
1298 _PyTime_t total;
1299 total = _PyTime_MulDiv(t.tms_utime, SEC_TO_NS, ticks_per_second);
1300 total += _PyTime_MulDiv(t.tms_stime, SEC_TO_NS, ticks_per_second);
1301 *tp = total;
1302 return 0;
Victor Stinnerec895392012-04-29 02:41:27 +02001303 }
1304 }
1305#endif
1306
Victor Stinnerc29b5852017-11-02 07:28:27 -07001307 /* clock */
Victor Stinner53e22bf2016-07-08 17:55:01 +02001308 /* Currently, Python 3 requires clock() to build: see issue #22624 */
Victor Stinnerc29b5852017-11-02 07:28:27 -07001309 return _PyTime_GetClockWithInfo(tp, info);
Victor Stinnerec895392012-04-29 02:41:27 +02001310#endif
1311}
1312
1313static PyObject *
1314time_process_time(PyObject *self, PyObject *unused)
1315{
Victor Stinnerc29b5852017-11-02 07:28:27 -07001316 _PyTime_t t;
1317 if (_PyTime_GetProcessTimeWithInfo(&t, NULL) < 0) {
1318 return NULL;
1319 }
1320 return _PyFloat_FromPyTime(t);
Victor Stinnerec895392012-04-29 02:41:27 +02001321}
1322
1323PyDoc_STRVAR(process_time_doc,
1324"process_time() -> float\n\
1325\n\
1326Process time for profiling: sum of the kernel and user-space CPU time.");
1327
Victor Stinnerc29b5852017-11-02 07:28:27 -07001328static PyObject *
1329time_process_time_ns(PyObject *self, PyObject *unused)
1330{
1331 _PyTime_t t;
1332 if (_PyTime_GetProcessTimeWithInfo(&t, NULL) < 0) {
1333 return NULL;
1334 }
1335 return _PyTime_AsNanosecondsObject(t);
1336}
1337
1338PyDoc_STRVAR(process_time_ns_doc,
1339"process_time() -> int\n\
1340\n\
1341Process time for profiling as nanoseconds:\n\
1342sum of the kernel and user-space CPU time.");
1343
Victor Stinnerec895392012-04-29 02:41:27 +02001344
Antoine Pitrou4bd41c92017-11-15 22:52:21 +01001345#if defined(MS_WINDOWS)
1346#define HAVE_THREAD_TIME
1347static int
1348_PyTime_GetThreadTimeWithInfo(_PyTime_t *tp, _Py_clock_info_t *info)
1349{
1350 HANDLE thread;
1351 FILETIME creation_time, exit_time, kernel_time, user_time;
1352 ULARGE_INTEGER large;
1353 _PyTime_t ktime, utime, t;
1354 BOOL ok;
1355
1356 thread = GetCurrentThread();
1357 ok = GetThreadTimes(thread, &creation_time, &exit_time,
1358 &kernel_time, &user_time);
1359 if (!ok) {
1360 PyErr_SetFromWindowsErr(0);
1361 return -1;
1362 }
1363
1364 if (info) {
1365 info->implementation = "GetThreadTimes()";
1366 info->resolution = 1e-7;
1367 info->monotonic = 1;
1368 info->adjustable = 0;
1369 }
1370
1371 large.u.LowPart = kernel_time.dwLowDateTime;
1372 large.u.HighPart = kernel_time.dwHighDateTime;
1373 ktime = large.QuadPart;
1374
1375 large.u.LowPart = user_time.dwLowDateTime;
1376 large.u.HighPart = user_time.dwHighDateTime;
1377 utime = large.QuadPart;
1378
1379 /* ktime and utime have a resolution of 100 nanoseconds */
1380 t = _PyTime_FromNanoseconds((ktime + utime) * 100);
1381 *tp = t;
1382 return 0;
1383}
1384
1385#elif defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_PROCESS_CPUTIME_ID)
1386#define HAVE_THREAD_TIME
1387static int
1388_PyTime_GetThreadTimeWithInfo(_PyTime_t *tp, _Py_clock_info_t *info)
1389{
1390 struct timespec ts;
1391 const clockid_t clk_id = CLOCK_THREAD_CPUTIME_ID;
1392 const char *function = "clock_gettime(CLOCK_THREAD_CPUTIME_ID)";
1393
1394 if (clock_gettime(clk_id, &ts)) {
1395 PyErr_SetFromErrno(PyExc_OSError);
1396 return -1;
1397 }
1398 if (info) {
1399 struct timespec res;
1400 info->implementation = function;
1401 info->monotonic = 1;
1402 info->adjustable = 0;
1403 if (clock_getres(clk_id, &res)) {
1404 PyErr_SetFromErrno(PyExc_OSError);
1405 return -1;
1406 }
1407 info->resolution = res.tv_sec + res.tv_nsec * 1e-9;
1408 }
1409
1410 if (_PyTime_FromTimespec(tp, &ts) < 0) {
1411 return -1;
1412 }
1413 return 0;
1414}
1415#endif
1416
1417#ifdef HAVE_THREAD_TIME
1418static PyObject *
1419time_thread_time(PyObject *self, PyObject *unused)
1420{
1421 _PyTime_t t;
1422 if (_PyTime_GetThreadTimeWithInfo(&t, NULL) < 0) {
1423 return NULL;
1424 }
1425 return _PyFloat_FromPyTime(t);
1426}
1427
1428PyDoc_STRVAR(thread_time_doc,
1429"thread_time() -> float\n\
1430\n\
1431Thread time for profiling: sum of the kernel and user-space CPU time.");
1432
1433static PyObject *
1434time_thread_time_ns(PyObject *self, PyObject *unused)
1435{
1436 _PyTime_t t;
1437 if (_PyTime_GetThreadTimeWithInfo(&t, NULL) < 0) {
1438 return NULL;
1439 }
1440 return _PyTime_AsNanosecondsObject(t);
1441}
1442
1443PyDoc_STRVAR(thread_time_ns_doc,
1444"thread_time() -> int\n\
1445\n\
1446Thread time for profiling as nanoseconds:\n\
1447sum of the kernel and user-space CPU time.");
1448#endif
1449
1450
Victor Stinnerec895392012-04-29 02:41:27 +02001451static PyObject *
1452time_get_clock_info(PyObject *self, PyObject *args)
1453{
1454 char *name;
Victor Stinnerec895392012-04-29 02:41:27 +02001455 _Py_clock_info_t info;
Victor Stinnerbda4b882012-06-12 22:11:44 +02001456 PyObject *obj = NULL, *dict, *ns;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001457 _PyTime_t t;
Victor Stinnerec895392012-04-29 02:41:27 +02001458
Victor Stinnerc29b5852017-11-02 07:28:27 -07001459 if (!PyArg_ParseTuple(args, "s:get_clock_info", &name)) {
Victor Stinnerec895392012-04-29 02:41:27 +02001460 return NULL;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001461 }
Victor Stinnerec895392012-04-29 02:41:27 +02001462
1463#ifdef Py_DEBUG
1464 info.implementation = NULL;
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001465 info.monotonic = -1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001466 info.adjustable = -1;
Victor Stinnerec895392012-04-29 02:41:27 +02001467 info.resolution = -1.0;
1468#else
1469 info.implementation = "";
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001470 info.monotonic = 0;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001471 info.adjustable = 0;
Victor Stinnerec895392012-04-29 02:41:27 +02001472 info.resolution = 1.0;
1473#endif
1474
Victor Stinnerc29b5852017-11-02 07:28:27 -07001475 if (strcmp(name, "time") == 0) {
1476 if (_PyTime_GetSystemClockWithInfo(&t, &info) < 0) {
1477 return NULL;
1478 }
1479 }
Victor Stinnerec895392012-04-29 02:41:27 +02001480#ifdef PYCLOCK
Victor Stinnerc29b5852017-11-02 07:28:27 -07001481 else if (strcmp(name, "clock") == 0) {
Victor Stinnerec895392012-04-29 02:41:27 +02001482 obj = pyclock(&info);
Victor Stinnerc29b5852017-11-02 07:28:27 -07001483 if (obj == NULL) {
1484 return NULL;
1485 }
1486 Py_DECREF(obj);
1487 }
Victor Stinnerec895392012-04-29 02:41:27 +02001488#endif
Victor Stinnerc29b5852017-11-02 07:28:27 -07001489 else if (strcmp(name, "monotonic") == 0) {
1490 if (_PyTime_GetMonotonicClockWithInfo(&t, &info) < 0) {
1491 return NULL;
1492 }
1493 }
1494 else if (strcmp(name, "perf_counter") == 0) {
1495 if (_PyTime_GetPerfCounterWithInfo(&t, &info) < 0) {
1496 return NULL;
1497 }
1498 }
1499 else if (strcmp(name, "process_time") == 0) {
1500 if (_PyTime_GetProcessTimeWithInfo(&t, &info) < 0) {
1501 return NULL;
1502 }
1503 }
Antoine Pitrou4bd41c92017-11-15 22:52:21 +01001504#ifdef HAVE_THREAD_TIME
1505 else if (strcmp(name, "thread_time") == 0) {
1506 if (_PyTime_GetThreadTimeWithInfo(&t, &info) < 0) {
1507 return NULL;
1508 }
1509 }
1510#endif
Victor Stinnerec895392012-04-29 02:41:27 +02001511 else {
1512 PyErr_SetString(PyExc_ValueError, "unknown clock");
1513 return NULL;
1514 }
Victor Stinnerec895392012-04-29 02:41:27 +02001515
Victor Stinnerbda4b882012-06-12 22:11:44 +02001516 dict = PyDict_New();
Victor Stinnerc29b5852017-11-02 07:28:27 -07001517 if (dict == NULL) {
Victor Stinnerec895392012-04-29 02:41:27 +02001518 return NULL;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001519 }
Victor Stinnerec895392012-04-29 02:41:27 +02001520
1521 assert(info.implementation != NULL);
1522 obj = PyUnicode_FromString(info.implementation);
Victor Stinnerc29b5852017-11-02 07:28:27 -07001523 if (obj == NULL) {
Victor Stinnerec895392012-04-29 02:41:27 +02001524 goto error;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001525 }
1526 if (PyDict_SetItemString(dict, "implementation", obj) == -1) {
Victor Stinnerbda4b882012-06-12 22:11:44 +02001527 goto error;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001528 }
Victor Stinnerbda4b882012-06-12 22:11:44 +02001529 Py_CLEAR(obj);
Victor Stinnerec895392012-04-29 02:41:27 +02001530
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001531 assert(info.monotonic != -1);
1532 obj = PyBool_FromLong(info.monotonic);
Victor Stinnerc29b5852017-11-02 07:28:27 -07001533 if (obj == NULL) {
Victor Stinnerec895392012-04-29 02:41:27 +02001534 goto error;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001535 }
1536 if (PyDict_SetItemString(dict, "monotonic", obj) == -1) {
Victor Stinnerbda4b882012-06-12 22:11:44 +02001537 goto error;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001538 }
Victor Stinnerbda4b882012-06-12 22:11:44 +02001539 Py_CLEAR(obj);
Victor Stinnerec895392012-04-29 02:41:27 +02001540
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001541 assert(info.adjustable != -1);
1542 obj = PyBool_FromLong(info.adjustable);
Victor Stinnerc29b5852017-11-02 07:28:27 -07001543 if (obj == NULL) {
Victor Stinnerec895392012-04-29 02:41:27 +02001544 goto error;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001545 }
1546 if (PyDict_SetItemString(dict, "adjustable", obj) == -1) {
Victor Stinnerbda4b882012-06-12 22:11:44 +02001547 goto error;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001548 }
Victor Stinnerbda4b882012-06-12 22:11:44 +02001549 Py_CLEAR(obj);
Victor Stinnerec895392012-04-29 02:41:27 +02001550
1551 assert(info.resolution > 0.0);
1552 assert(info.resolution <= 1.0);
1553 obj = PyFloat_FromDouble(info.resolution);
Victor Stinnerc29b5852017-11-02 07:28:27 -07001554 if (obj == NULL) {
Victor Stinnerec895392012-04-29 02:41:27 +02001555 goto error;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001556 }
1557 if (PyDict_SetItemString(dict, "resolution", obj) == -1) {
Victor Stinnerbda4b882012-06-12 22:11:44 +02001558 goto error;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001559 }
Victor Stinnerbda4b882012-06-12 22:11:44 +02001560 Py_CLEAR(obj);
Victor Stinnerec895392012-04-29 02:41:27 +02001561
Victor Stinnerbda4b882012-06-12 22:11:44 +02001562 ns = _PyNamespace_New(dict);
1563 Py_DECREF(dict);
1564 return ns;
Victor Stinnerec895392012-04-29 02:41:27 +02001565
1566error:
Victor Stinnerbda4b882012-06-12 22:11:44 +02001567 Py_DECREF(dict);
1568 Py_XDECREF(obj);
Victor Stinnerec895392012-04-29 02:41:27 +02001569 return NULL;
1570}
1571
1572PyDoc_STRVAR(get_clock_info_doc,
1573"get_clock_info(name: str) -> dict\n\
1574\n\
1575Get information of the specified clock.");
Victor Stinner8b302012012-02-07 23:29:46 +01001576
Benjamin Petersonc510c6b2018-09-20 19:52:18 -07001577#ifndef HAVE_DECL_TZNAME
Victor Stinner1fb399b2018-09-17 13:56:17 -07001578static void
1579get_zone(char *zone, int n, struct tm *p)
1580{
1581#ifdef HAVE_STRUCT_TM_TM_ZONE
1582 strncpy(zone, p->tm_zone ? p->tm_zone : " ", n);
1583#else
1584 tzset();
1585 strftime(zone, n, "%Z", p);
1586#endif
1587}
1588
Victor Stinner503ce5c2018-12-01 00:39:36 +01001589static time_t
Victor Stinner1fb399b2018-09-17 13:56:17 -07001590get_gmtoff(time_t t, struct tm *p)
1591{
1592#ifdef HAVE_STRUCT_TM_TM_ZONE
1593 return p->tm_gmtoff;
1594#else
1595 return timegm(p) - t;
1596#endif
1597}
Benjamin Petersonc510c6b2018-09-20 19:52:18 -07001598#endif // !HAVE_DECL_TZNAME
Victor Stinner1fb399b2018-09-17 13:56:17 -07001599
Victor Stinner503ce5c2018-12-01 00:39:36 +01001600static int
Victor Stinner3bb150d2018-12-03 13:45:38 +01001601init_timezone(PyObject *m)
Victor Stinner503ce5c2018-12-01 00:39:36 +01001602{
1603 assert(!PyErr_Occurred());
1604
Martin v. Löwis1a214512008-06-11 05:26:20 +00001605 /* This code moved from PyInit_time wholesale to allow calling it from
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001606 time_tzset. In the future, some parts of it can be moved back
1607 (for platforms that don't HAVE_WORKING_TZSET, when we know what they
1608 are), and the extraneous calls to tzset(3) should be removed.
1609 I haven't done this yet, as I don't want to change this code as
1610 little as possible when introducing the time.tzset and time.tzsetwall
1611 methods. This should simply be a method of doing the following once,
1612 at the top of this function and removing the call to tzset() from
1613 time_tzset():
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001614
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001615 #ifdef HAVE_TZSET
1616 tzset()
1617 #endif
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001619 And I'm lazy and hate C so nyer.
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001620 */
Benjamin Petersonc510c6b2018-09-20 19:52:18 -07001621#ifdef HAVE_DECL_TZNAME
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001622 PyObject *otz0, *otz1;
1623 tzset();
Zackery Spytz6673dec2019-02-25 16:56:44 -07001624 PyModule_AddIntConstant(m, "timezone", _Py_timezone);
Guido van Rossumb6775db1994-08-01 11:34:53 +00001625#ifdef HAVE_ALTZONE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001626 PyModule_AddIntConstant(m, "altzone", altzone);
Guido van Rossumb6775db1994-08-01 11:34:53 +00001627#else
Zackery Spytz6673dec2019-02-25 16:56:44 -07001628 PyModule_AddIntConstant(m, "altzone", _Py_timezone-3600);
Guido van Rossumb6775db1994-08-01 11:34:53 +00001629#endif
Zackery Spytz6673dec2019-02-25 16:56:44 -07001630 PyModule_AddIntConstant(m, "daylight", _Py_daylight);
1631 otz0 = PyUnicode_DecodeLocale(_Py_tzname[0], "surrogateescape");
Benjamin Petersonc510c6b2018-09-20 19:52:18 -07001632 if (otz0 == NULL) {
Victor Stinnerab661492018-12-03 12:02:43 +01001633 return -1;
Victor Stinner1fb399b2018-09-17 13:56:17 -07001634 }
Zackery Spytz6673dec2019-02-25 16:56:44 -07001635 otz1 = PyUnicode_DecodeLocale(_Py_tzname[1], "surrogateescape");
Benjamin Petersonc510c6b2018-09-20 19:52:18 -07001636 if (otz1 == NULL) {
1637 Py_DECREF(otz0);
Victor Stinnerab661492018-12-03 12:02:43 +01001638 return -1;
Benjamin Petersonc510c6b2018-09-20 19:52:18 -07001639 }
1640 PyObject *tzname_obj = Py_BuildValue("(NN)", otz0, otz1);
Victor Stinnerab661492018-12-03 12:02:43 +01001641 if (tzname_obj == NULL) {
1642 return -1;
1643 }
Benjamin Petersonc510c6b2018-09-20 19:52:18 -07001644 PyModule_AddObject(m, "tzname", tzname_obj);
1645#else // !HAVE_DECL_TZNAME
1646 static const time_t YEAR = (365 * 24 + 6) * 3600;
1647 time_t t;
1648 struct tm p;
Victor Stinner503ce5c2018-12-01 00:39:36 +01001649 time_t janzone_t, julyzone_t;
Benjamin Petersonc510c6b2018-09-20 19:52:18 -07001650 char janname[10], julyname[10];
1651 t = (time((time_t *)0) / YEAR) * YEAR;
1652 _PyTime_localtime(t, &p);
1653 get_zone(janname, 9, &p);
Victor Stinner503ce5c2018-12-01 00:39:36 +01001654 janzone_t = -get_gmtoff(t, &p);
Benjamin Petersonc510c6b2018-09-20 19:52:18 -07001655 janname[9] = '\0';
1656 t += YEAR/2;
1657 _PyTime_localtime(t, &p);
1658 get_zone(julyname, 9, &p);
Victor Stinner503ce5c2018-12-01 00:39:36 +01001659 julyzone_t = -get_gmtoff(t, &p);
Benjamin Petersonc510c6b2018-09-20 19:52:18 -07001660 julyname[9] = '\0';
1661
Victor Stinner503ce5c2018-12-01 00:39:36 +01001662 /* Sanity check, don't check for the validity of timezones.
1663 In practice, it should be more in range -12 hours .. +14 hours. */
1664#define MAX_TIMEZONE (48 * 3600)
1665 if (janzone_t < -MAX_TIMEZONE || janzone_t > MAX_TIMEZONE
1666 || julyzone_t < -MAX_TIMEZONE || julyzone_t > MAX_TIMEZONE)
1667 {
1668 PyErr_SetString(PyExc_RuntimeError, "invalid GMT offset");
1669 return -1;
1670 }
1671 int janzone = (int)janzone_t;
1672 int julyzone = (int)julyzone_t;
1673
Benjamin Petersonc510c6b2018-09-20 19:52:18 -07001674 PyObject *tzname_obj;
1675 if (janzone < julyzone) {
1676 /* DST is reversed in the southern hemisphere */
1677 PyModule_AddIntConstant(m, "timezone", julyzone);
1678 PyModule_AddIntConstant(m, "altzone", janzone);
1679 PyModule_AddIntConstant(m, "daylight", janzone != julyzone);
1680 tzname_obj = Py_BuildValue("(zz)", julyname, janname);
1681 } else {
1682 PyModule_AddIntConstant(m, "timezone", janzone);
1683 PyModule_AddIntConstant(m, "altzone", julyzone);
1684 PyModule_AddIntConstant(m, "daylight", janzone != julyzone);
1685 tzname_obj = Py_BuildValue("(zz)", janname, julyname);
1686 }
Victor Stinner503ce5c2018-12-01 00:39:36 +01001687 if (tzname_obj == NULL) {
1688 return -1;
1689 }
Benjamin Petersonc510c6b2018-09-20 19:52:18 -07001690 PyModule_AddObject(m, "tzname", tzname_obj);
1691#endif // !HAVE_DECL_TZNAME
Victor Stinner503ce5c2018-12-01 00:39:36 +01001692
1693 if (PyErr_Occurred()) {
1694 return -1;
1695 }
1696 return 0;
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001697}
1698
1699
1700static PyMethodDef time_methods[] = {
Victor Stinner4195b5c2012-02-08 23:03:19 +01001701 {"time", time_time, METH_NOARGS, time_doc},
Victor Stinnerc29b5852017-11-02 07:28:27 -07001702 {"time_ns", time_time_ns, METH_NOARGS, time_ns_doc},
Victor Stinnerec895392012-04-29 02:41:27 +02001703#ifdef PYCLOCK
Victor Stinner4195b5c2012-02-08 23:03:19 +01001704 {"clock", time_clock, METH_NOARGS, clock_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001705#endif
Victor Stinnere0be4232011-10-25 13:06:09 +02001706#ifdef HAVE_CLOCK_GETTIME
Victor Stinner4195b5c2012-02-08 23:03:19 +01001707 {"clock_gettime", time_clock_gettime, METH_VARARGS, clock_gettime_doc},
Victor Stinnerc29b5852017-11-02 07:28:27 -07001708 {"clock_gettime_ns",time_clock_gettime_ns, METH_VARARGS, clock_gettime_ns_doc},
Benjamin Peterson37098cd2016-09-13 22:55:09 -07001709#endif
1710#ifdef HAVE_CLOCK_SETTIME
Victor Stinner30d79472012-04-03 00:45:07 +02001711 {"clock_settime", time_clock_settime, METH_VARARGS, clock_settime_doc},
Victor Stinnerc29b5852017-11-02 07:28:27 -07001712 {"clock_settime_ns",time_clock_settime_ns, METH_VARARGS, clock_settime_ns_doc},
Benjamin Peterson37098cd2016-09-13 22:55:09 -07001713#endif
1714#ifdef HAVE_CLOCK_GETRES
Victor Stinner4195b5c2012-02-08 23:03:19 +01001715 {"clock_getres", time_clock_getres, METH_VARARGS, clock_getres_doc},
Victor Stinnere0be4232011-10-25 13:06:09 +02001716#endif
pdoxe14679c2017-10-05 00:01:56 -07001717#ifdef HAVE_PTHREAD_GETCPUCLOCKID
1718 {"pthread_getcpuclockid", time_pthread_getcpuclockid, METH_VARARGS, pthread_getcpuclockid_doc},
1719#endif
Victor Stinnercb29f012015-03-27 13:31:18 +01001720 {"sleep", time_sleep, METH_O, sleep_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001721 {"gmtime", time_gmtime, METH_VARARGS, gmtime_doc},
1722 {"localtime", time_localtime, METH_VARARGS, localtime_doc},
1723 {"asctime", time_asctime, METH_VARARGS, asctime_doc},
1724 {"ctime", time_ctime, METH_VARARGS, ctime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001725#ifdef HAVE_MKTIME
Victor Stinner4195b5c2012-02-08 23:03:19 +01001726 {"mktime", time_mktime, METH_O, mktime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001727#endif
1728#ifdef HAVE_STRFTIME
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001729 {"strftime", time_strftime, METH_VARARGS, strftime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001730#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001731 {"strptime", time_strptime, METH_VARARGS, strptime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001732#ifdef HAVE_WORKING_TZSET
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001733 {"tzset", time_tzset, METH_NOARGS, tzset_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001734#endif
Victor Stinnerec895392012-04-29 02:41:27 +02001735 {"monotonic", time_monotonic, METH_NOARGS, monotonic_doc},
Victor Stinnerc29b5852017-11-02 07:28:27 -07001736 {"monotonic_ns", time_monotonic_ns, METH_NOARGS, monotonic_ns_doc},
Victor Stinnerec895392012-04-29 02:41:27 +02001737 {"process_time", time_process_time, METH_NOARGS, process_time_doc},
Victor Stinnerc29b5852017-11-02 07:28:27 -07001738 {"process_time_ns", time_process_time_ns, METH_NOARGS, process_time_ns_doc},
Antoine Pitrou4bd41c92017-11-15 22:52:21 +01001739#ifdef HAVE_THREAD_TIME
1740 {"thread_time", time_thread_time, METH_NOARGS, thread_time_doc},
1741 {"thread_time_ns", time_thread_time_ns, METH_NOARGS, thread_time_ns_doc},
1742#endif
Victor Stinnerec895392012-04-29 02:41:27 +02001743 {"perf_counter", time_perf_counter, METH_NOARGS, perf_counter_doc},
Victor Stinnerc29b5852017-11-02 07:28:27 -07001744 {"perf_counter_ns", time_perf_counter_ns, METH_NOARGS, perf_counter_ns_doc},
Victor Stinnerec895392012-04-29 02:41:27 +02001745 {"get_clock_info", time_get_clock_info, METH_VARARGS, get_clock_info_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001746 {NULL, NULL} /* sentinel */
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001747};
1748
1749
1750PyDoc_STRVAR(module_doc,
1751"This module provides various functions to manipulate time values.\n\
1752\n\
1753There are two standard representations of time. One is the number\n\
1754of seconds since the Epoch, in UTC (a.k.a. GMT). It may be an integer\n\
1755or a floating point number (to represent fractions of seconds).\n\
1756The Epoch is system-defined; on Unix, it is generally January 1st, 1970.\n\
1757The actual value can be retrieved by calling gmtime(0).\n\
1758\n\
1759The other representation is a tuple of 9 integers giving local time.\n\
1760The tuple items are:\n\
Alexander Belopolsky03163ac2011-05-02 12:20:52 -04001761 year (including century, e.g. 1998)\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001762 month (1-12)\n\
1763 day (1-31)\n\
1764 hours (0-23)\n\
1765 minutes (0-59)\n\
1766 seconds (0-59)\n\
1767 weekday (0-6, Monday is 0)\n\
1768 Julian day (day in the year, 1-366)\n\
1769 DST (Daylight Savings Time) flag (-1, 0 or 1)\n\
1770If the DST flag is 0, the time is given in the regular time zone;\n\
1771if it is 1, the time is given in the DST time zone;\n\
Cheryl Sabella703ff382017-10-11 09:29:14 -04001772if it is -1, mktime() should guess based on the date and time.\n");
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001773
1774
Martin v. Löwis1a214512008-06-11 05:26:20 +00001775
1776static struct PyModuleDef timemodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001777 PyModuleDef_HEAD_INIT,
1778 "time",
1779 module_doc,
1780 -1,
1781 time_methods,
1782 NULL,
1783 NULL,
1784 NULL,
1785 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00001786};
1787
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001788PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00001789PyInit_time(void)
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001790{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001791 PyObject *m;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001792 m = PyModule_Create(&timemodule);
1793 if (m == NULL)
1794 return NULL;
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001795
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001796 /* Set, or reset, module variables like time.timezone */
Victor Stinner3bb150d2018-12-03 13:45:38 +01001797 if (init_timezone(m) < 0) {
Victor Stinner503ce5c2018-12-01 00:39:36 +01001798 return NULL;
1799 }
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001800
Max Bélanger94451182018-10-20 17:07:54 -07001801#if defined(HAVE_CLOCK_GETTIME) || defined(HAVE_CLOCK_SETTIME) || defined(HAVE_CLOCK_GETRES)
1802
Benjamin Peterson37098cd2016-09-13 22:55:09 -07001803#ifdef CLOCK_REALTIME
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -04001804 PyModule_AddIntMacro(m, CLOCK_REALTIME);
Benjamin Peterson37098cd2016-09-13 22:55:09 -07001805#endif
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -04001806#ifdef CLOCK_MONOTONIC
1807 PyModule_AddIntMacro(m, CLOCK_MONOTONIC);
1808#endif
1809#ifdef CLOCK_MONOTONIC_RAW
1810 PyModule_AddIntMacro(m, CLOCK_MONOTONIC_RAW);
1811#endif
1812#ifdef CLOCK_HIGHRES
1813 PyModule_AddIntMacro(m, CLOCK_HIGHRES);
1814#endif
1815#ifdef CLOCK_PROCESS_CPUTIME_ID
1816 PyModule_AddIntMacro(m, CLOCK_PROCESS_CPUTIME_ID);
1817#endif
1818#ifdef CLOCK_THREAD_CPUTIME_ID
1819 PyModule_AddIntMacro(m, CLOCK_THREAD_CPUTIME_ID);
1820#endif
Victor Stinnera64ce972017-11-02 04:19:19 -07001821#ifdef CLOCK_PROF
1822 PyModule_AddIntMacro(m, CLOCK_PROF);
1823#endif
1824#ifdef CLOCK_BOOTTIME
1825 PyModule_AddIntMacro(m, CLOCK_BOOTTIME);
1826#endif
1827#ifdef CLOCK_UPTIME
1828 PyModule_AddIntMacro(m, CLOCK_UPTIME);
1829#endif
Joannah Nanjekye572168a2019-01-10 19:56:38 +03001830#ifdef CLOCK_UPTIME_RAW
1831 PyModule_AddIntMacro(m, CLOCK_UPTIME_RAW);
1832#endif
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -04001833
Max Bélanger94451182018-10-20 17:07:54 -07001834#endif /* defined(HAVE_CLOCK_GETTIME) || defined(HAVE_CLOCK_SETTIME) || defined(HAVE_CLOCK_GETRES) */
1835
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001836 if (!initialized) {
Victor Stinner1c8f0592013-07-22 22:24:54 +02001837 if (PyStructSequence_InitType2(&StructTimeType,
1838 &struct_time_type_desc) < 0)
1839 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001840 }
1841 Py_INCREF(&StructTimeType);
Alexander Belopolskyc142bba2012-06-13 22:15:26 -04001842 PyModule_AddIntConstant(m, "_STRUCT_TM_ITEMS", 11);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001843 PyModule_AddObject(m, "struct_time", (PyObject*) &StructTimeType);
1844 initialized = 1;
Benjamin Peterson5633c4f2018-09-14 09:09:04 -07001845
1846#if defined(__linux__) && !defined(__GLIBC__)
1847 struct tm tm;
Benjamin Petersonb93062b2018-09-14 10:39:13 -07001848 const time_t zero = 0;
1849 if (gmtime_r(&zero, &tm) != NULL)
Benjamin Peterson5633c4f2018-09-14 09:09:04 -07001850 utc_string = tm.tm_zone;
1851#endif
1852
Victor Stinner3bb150d2018-12-03 13:45:38 +01001853 if (PyErr_Occurred()) {
1854 return NULL;
1855 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001856 return m;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001857}
1858
Victor Stinnercb29f012015-03-27 13:31:18 +01001859/* Implement pysleep() for various platforms.
Guido van Rossumb6775db1994-08-01 11:34:53 +00001860 When interrupted (or when another error occurs), return -1 and
1861 set an exception; else return 0. */
1862
1863static int
Victor Stinnercb29f012015-03-27 13:31:18 +01001864pysleep(_PyTime_t secs)
Guido van Rossum426035c1991-02-19 12:27:35 +00001865{
Victor Stinnercb29f012015-03-27 13:31:18 +01001866 _PyTime_t deadline, monotonic;
Victor Stinner79d68f92015-03-19 21:54:09 +01001867#ifndef MS_WINDOWS
1868 struct timeval timeout;
Victor Stinner79d68f92015-03-19 21:54:09 +01001869 int err = 0;
1870#else
Victor Stinnercb29f012015-03-27 13:31:18 +01001871 _PyTime_t millisecs;
Victor Stinner79d68f92015-03-19 21:54:09 +01001872 unsigned long ul_millis;
1873 DWORD rc;
1874 HANDLE hInterruptEvent;
Victor Stinner0c2fd892015-03-17 10:49:17 +01001875#endif
Victor Stinner79d68f92015-03-19 21:54:09 +01001876
Victor Stinnercb29f012015-03-27 13:31:18 +01001877 deadline = _PyTime_GetMonotonicClock() + secs;
Victor Stinner79d68f92015-03-19 21:54:09 +01001878
1879 do {
1880#ifndef MS_WINDOWS
Victor Stinner869e1772015-03-30 03:49:14 +02001881 if (_PyTime_AsTimeval(secs, &timeout, _PyTime_ROUND_CEILING) < 0)
Victor Stinnercb29f012015-03-27 13:31:18 +01001882 return -1;
Victor Stinner79d68f92015-03-19 21:54:09 +01001883
1884 Py_BEGIN_ALLOW_THREADS
1885 err = select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &timeout);
1886 Py_END_ALLOW_THREADS
1887
1888 if (err == 0)
1889 break;
1890
1891 if (errno != EINTR) {
Victor Stinner0c2fd892015-03-17 10:49:17 +01001892 PyErr_SetFromErrno(PyExc_OSError);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001893 return -1;
1894 }
Victor Stinner79d68f92015-03-19 21:54:09 +01001895#else
Victor Stinner869e1772015-03-30 03:49:14 +02001896 millisecs = _PyTime_AsMilliseconds(secs, _PyTime_ROUND_CEILING);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001897 if (millisecs > (double)ULONG_MAX) {
1898 PyErr_SetString(PyExc_OverflowError,
1899 "sleep length is too large");
1900 return -1;
1901 }
Victor Stinner79d68f92015-03-19 21:54:09 +01001902
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001903 /* Allow sleep(0) to maintain win32 semantics, and as decreed
1904 * by Guido, only the main thread can be interrupted.
1905 */
1906 ul_millis = (unsigned long)millisecs;
Victor Stinner79d68f92015-03-19 21:54:09 +01001907 if (ul_millis == 0 || !_PyOS_IsMainThread()) {
1908 Py_BEGIN_ALLOW_THREADS
Victor Stinner0eac1302015-03-20 03:06:12 +01001909 Sleep(ul_millis);
Victor Stinner79d68f92015-03-19 21:54:09 +01001910 Py_END_ALLOW_THREADS
1911 break;
Victor Stinner945c82e2015-03-12 16:19:01 +01001912 }
Victor Stinner79d68f92015-03-19 21:54:09 +01001913
1914 hInterruptEvent = _PyOS_SigintEvent();
1915 ResetEvent(hInterruptEvent);
1916
1917 Py_BEGIN_ALLOW_THREADS
1918 rc = WaitForSingleObjectEx(hInterruptEvent, ul_millis, FALSE);
Victor Stinner0c2fd892015-03-17 10:49:17 +01001919 Py_END_ALLOW_THREADS
Victor Stinner79d68f92015-03-19 21:54:09 +01001920
1921 if (rc != WAIT_OBJECT_0)
1922 break;
Victor Stinner945c82e2015-03-12 16:19:01 +01001923#endif
Victor Stinner0c2fd892015-03-17 10:49:17 +01001924
Victor Stinner79d68f92015-03-19 21:54:09 +01001925 /* sleep was interrupted by SIGINT */
1926 if (PyErr_CheckSignals())
1927 return -1;
1928
Victor Stinnercb29f012015-03-27 13:31:18 +01001929 monotonic = _PyTime_GetMonotonicClock();
1930 secs = deadline - monotonic;
Victor Stinner6aa446c2015-03-30 21:33:51 +02001931 if (secs < 0)
Victor Stinner79d68f92015-03-19 21:54:09 +01001932 break;
1933 /* retry with the recomputed delay */
1934 } while (1);
1935
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001936 return 0;
Guido van Rossum80c9d881991-04-16 08:47:51 +00001937}