blob: 7c01cefa4d3cd0f446da05be5d73849c4542881f [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
Victor Stinnera997c7b2017-10-10 02:51:50 -0700148#if defined(MS_WINDOWS) || defined(HAVE_CLOCK)
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
Jakub Kulík6f9bc722018-12-31 03:16:40 +0100768#if defined(_MSC_VER) || (defined(__sun) && defined(__SVR4)) || defined(_AIX)
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 Stinner4195b5c2012-02-08 23:03:19 +0100993time_mktime(PyObject *self, PyObject *tup)
Guido van Rossum234f9421993-06-17 12:35:49 +0000994{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000995 struct tm buf;
996 time_t tt;
Michael Felte2926b72018-12-28 14:57:37 +0100997#ifdef _AIX
998 time_t clk;
999 int year = buf.tm_year;
1000 int delta_days = 0;
1001#endif
1002
Oren Milman1d1d3e92017-08-20 18:35:36 +03001003 if (!gettmarg(tup, &buf,
1004 "iiiiiiiii;mktime(): illegal time tuple argument"))
1005 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001006 return NULL;
Oren Milman1d1d3e92017-08-20 18:35:36 +03001007 }
Michael Felte2926b72018-12-28 14:57:37 +01001008#ifndef _AIX
1009 buf.tm_wday = -1; /* sentinel; original value ignored */
1010 tt = mktime(&buf);
1011#else
Victor Stinner1ac42612014-02-21 09:27:17 +01001012 /* year < 1902 or year > 2037 */
Michael Felte2926b72018-12-28 14:57:37 +01001013 if ((buf.tm_year < 2) || (buf.tm_year > 137)) {
Victor Stinner1ac42612014-02-21 09:27:17 +01001014 /* Issue #19748: On AIX, mktime() doesn't report overflow error for
1015 * timestamp < -2^31 or timestamp > 2**31-1. */
1016 PyErr_SetString(PyExc_OverflowError,
1017 "mktime argument out of range");
1018 return NULL;
1019 }
Michael Felte2926b72018-12-28 14:57:37 +01001020 year = buf.tm_year;
1021 /* year < 1970 - adjust buf.tm_year into legal range */
1022 while (buf.tm_year < 70) {
1023 buf.tm_year += 4;
1024 delta_days -= (366 + (365 * 3));
1025 }
1026
1027 buf.tm_wday = -1;
1028 clk = mktime(&buf);
1029 buf.tm_year = year;
1030
1031 if ((buf.tm_wday != -1) && delta_days)
1032 buf.tm_wday = (buf.tm_wday + delta_days) % 7;
1033
1034 tt = clk + (delta_days * (24 * 3600));
Victor Stinner1ac42612014-02-21 09:27:17 +01001035#endif
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. */
Michael Felte2926b72018-12-28 14:57:37 +01001041 && buf.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 Stinner4195b5c2012-02-08 23:03:19 +01001047 return PyFloat_FromDouble((double)tt);
Guido van Rossum234f9421993-06-17 12:35:49 +00001048}
Guido van Rossum0ef577b1998-06-27 20:38:36 +00001049
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001050PyDoc_STRVAR(mktime_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +00001051"mktime(tuple) -> floating point number\n\
1052\n\
Alexander Belopolskyc142bba2012-06-13 22:15:26 -04001053Convert a time tuple in local time to seconds since the Epoch.\n\
1054Note that mktime(gmtime(0)) will not generally return zero for most\n\
1055time zones; instead the returned value will either be equal to that\n\
1056of the timezone or altzone attributes on the time module.");
Guido van Rossum60cd8131998-03-06 17:16:21 +00001057#endif /* HAVE_MKTIME */
Guido van Rossum234f9421993-06-17 12:35:49 +00001058
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001059#ifdef HAVE_WORKING_TZSET
Victor Stinner3bb150d2018-12-03 13:45:38 +01001060static int init_timezone(PyObject *module);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001061
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001062static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001063time_tzset(PyObject *self, PyObject *unused)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001064{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001065 PyObject* m;
Fred Drake9bb74322002-04-01 14:49:59 +00001066
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001067 m = PyImport_ImportModuleNoBlock("time");
1068 if (m == NULL) {
1069 return NULL;
1070 }
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001071
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001072 tzset();
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001073
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001074 /* Reset timezone, altzone, daylight and tzname */
Victor Stinner3bb150d2018-12-03 13:45:38 +01001075 if (init_timezone(m) < 0) {
Victor Stinner503ce5c2018-12-01 00:39:36 +01001076 return NULL;
1077 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001078 Py_DECREF(m);
Victor Stinner2ff51b82013-07-17 21:42:45 +02001079 if (PyErr_Occurred())
1080 return NULL;
Tim Peters1b6f7a92004-06-20 02:50:16 +00001081
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001082 Py_RETURN_NONE;
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001083}
1084
1085PyDoc_STRVAR(tzset_doc,
R. David Murray4d55bf92010-12-14 00:55:46 +00001086"tzset()\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001087\n\
1088Initialize, or reinitialize, the local timezone to the value stored in\n\
1089os.environ['TZ']. The TZ environment variable should be specified in\n\
Neal Norwitzdc8e1942004-07-20 22:34:37 +00001090standard Unix timezone format as documented in the tzset man page\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001091(eg. 'US/Eastern', 'Europe/Amsterdam'). Unknown timezones will silently\n\
1092fall back to UTC. If the TZ environment variable is not set, the local\n\
1093timezone is set to the systems best guess of wallclock time.\n\
1094Changing the TZ environment variable without calling tzset *may* change\n\
1095the local timezone used by methods such as localtime, but this behaviour\n\
1096should not be relied on.");
1097#endif /* HAVE_WORKING_TZSET */
1098
Victor Stinnerae586492014-09-02 23:18:25 +02001099static PyObject *
Victor Stinnerec895392012-04-29 02:41:27 +02001100time_monotonic(PyObject *self, PyObject *unused)
Victor Stinner071eca32012-03-15 01:17:09 +01001101{
Victor Stinnerc29b5852017-11-02 07:28:27 -07001102 _PyTime_t t = _PyTime_GetMonotonicClock();
1103 return _PyFloat_FromPyTime(t);
Victor Stinner071eca32012-03-15 01:17:09 +01001104}
1105
Victor Stinnerec895392012-04-29 02:41:27 +02001106PyDoc_STRVAR(monotonic_doc,
1107"monotonic() -> float\n\
Victor Stinner8b302012012-02-07 23:29:46 +01001108\n\
Victor Stinnerec895392012-04-29 02:41:27 +02001109Monotonic clock, cannot go backward.");
Victor Stinnerec919cc2012-03-15 00:58:32 +01001110
Victor Stinnerec895392012-04-29 02:41:27 +02001111static PyObject *
Victor Stinnerc29b5852017-11-02 07:28:27 -07001112time_monotonic_ns(PyObject *self, PyObject *unused)
1113{
1114 _PyTime_t t = _PyTime_GetMonotonicClock();
1115 return _PyTime_AsNanosecondsObject(t);
1116}
1117
1118PyDoc_STRVAR(monotonic_ns_doc,
1119"monotonic_ns() -> int\n\
1120\n\
1121Monotonic clock, cannot go backward, as nanoseconds.");
1122
1123static PyObject *
Victor Stinnerec895392012-04-29 02:41:27 +02001124time_perf_counter(PyObject *self, PyObject *unused)
1125{
1126 return perf_counter(NULL);
1127}
1128
1129PyDoc_STRVAR(perf_counter_doc,
1130"perf_counter() -> float\n\
1131\n\
1132Performance counter for benchmarking.");
1133
Victor Stinnerc29b5852017-11-02 07:28:27 -07001134static PyObject *
1135time_perf_counter_ns(PyObject *self, PyObject *unused)
1136{
1137 _PyTime_t t = _PyTime_GetPerfCounter();
1138 return _PyTime_AsNanosecondsObject(t);
1139}
1140
1141PyDoc_STRVAR(perf_counter_ns_doc,
1142"perf_counter_ns() -> int\n\
1143\n\
1144Performance counter for benchmarking as nanoseconds.");
1145
1146static int
1147_PyTime_GetProcessTimeWithInfo(_PyTime_t *tp, _Py_clock_info_t *info)
Victor Stinnerec895392012-04-29 02:41:27 +02001148{
1149#if defined(MS_WINDOWS)
1150 HANDLE process;
1151 FILETIME creation_time, exit_time, kernel_time, user_time;
1152 ULARGE_INTEGER large;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001153 _PyTime_t ktime, utime, t;
Victor Stinnerec895392012-04-29 02:41:27 +02001154 BOOL ok;
1155
1156 process = GetCurrentProcess();
Victor Stinnerc29b5852017-11-02 07:28:27 -07001157 ok = GetProcessTimes(process, &creation_time, &exit_time,
1158 &kernel_time, &user_time);
1159 if (!ok) {
1160 PyErr_SetFromWindowsErr(0);
1161 return -1;
1162 }
Victor Stinnerec895392012-04-29 02:41:27 +02001163
Victor Stinnerec895392012-04-29 02:41:27 +02001164 if (info) {
1165 info->implementation = "GetProcessTimes()";
1166 info->resolution = 1e-7;
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001167 info->monotonic = 1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001168 info->adjustable = 0;
Victor Stinnerec895392012-04-29 02:41:27 +02001169 }
Victor Stinnerc29b5852017-11-02 07:28:27 -07001170
1171 large.u.LowPart = kernel_time.dwLowDateTime;
1172 large.u.HighPart = kernel_time.dwHighDateTime;
1173 ktime = large.QuadPart;
1174
1175 large.u.LowPart = user_time.dwLowDateTime;
1176 large.u.HighPart = user_time.dwHighDateTime;
1177 utime = large.QuadPart;
1178
1179 /* ktime and utime have a resolution of 100 nanoseconds */
1180 t = _PyTime_FromNanoseconds((ktime + utime) * 100);
1181 *tp = t;
1182 return 0;
Victor Stinnerec895392012-04-29 02:41:27 +02001183#else
1184
Victor Stinnerc29b5852017-11-02 07:28:27 -07001185 /* clock_gettime */
Victor Stinnerec895392012-04-29 02:41:27 +02001186#if defined(HAVE_CLOCK_GETTIME) \
1187 && (defined(CLOCK_PROCESS_CPUTIME_ID) || defined(CLOCK_PROF))
Victor Stinnerc29b5852017-11-02 07:28:27 -07001188 struct timespec ts;
Victor Stinnerec895392012-04-29 02:41:27 +02001189#ifdef CLOCK_PROF
1190 const clockid_t clk_id = CLOCK_PROF;
1191 const char *function = "clock_gettime(CLOCK_PROF)";
1192#else
1193 const clockid_t clk_id = CLOCK_PROCESS_CPUTIME_ID;
1194 const char *function = "clock_gettime(CLOCK_PROCESS_CPUTIME_ID)";
1195#endif
1196
Victor Stinnerc29b5852017-11-02 07:28:27 -07001197 if (clock_gettime(clk_id, &ts) == 0) {
Victor Stinnerec895392012-04-29 02:41:27 +02001198 if (info) {
1199 struct timespec res;
1200 info->implementation = function;
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001201 info->monotonic = 1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001202 info->adjustable = 0;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001203 if (clock_getres(clk_id, &res)) {
1204 PyErr_SetFromErrno(PyExc_OSError);
1205 return -1;
1206 }
1207 info->resolution = res.tv_sec + res.tv_nsec * 1e-9;
Victor Stinnerec895392012-04-29 02:41:27 +02001208 }
Victor Stinnerc29b5852017-11-02 07:28:27 -07001209
1210 if (_PyTime_FromTimespec(tp, &ts) < 0) {
1211 return -1;
1212 }
1213 return 0;
Victor Stinnerec895392012-04-29 02:41:27 +02001214 }
1215#endif
1216
Victor Stinnerc29b5852017-11-02 07:28:27 -07001217 /* getrusage(RUSAGE_SELF) */
Victor Stinnerec895392012-04-29 02:41:27 +02001218#if defined(HAVE_SYS_RESOURCE_H)
Victor Stinnerc29b5852017-11-02 07:28:27 -07001219 struct rusage ru;
1220
Victor Stinnerec895392012-04-29 02:41:27 +02001221 if (getrusage(RUSAGE_SELF, &ru) == 0) {
Victor Stinnerc29b5852017-11-02 07:28:27 -07001222 _PyTime_t utime, stime;
1223
Victor Stinnerec895392012-04-29 02:41:27 +02001224 if (info) {
1225 info->implementation = "getrusage(RUSAGE_SELF)";
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001226 info->monotonic = 1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001227 info->adjustable = 0;
Victor Stinnerec895392012-04-29 02:41:27 +02001228 info->resolution = 1e-6;
1229 }
Victor Stinnerc29b5852017-11-02 07:28:27 -07001230
1231 if (_PyTime_FromTimeval(&utime, &ru.ru_utime) < 0) {
1232 return -1;
1233 }
1234 if (_PyTime_FromTimeval(&stime, &ru.ru_stime) < 0) {
1235 return -1;
1236 }
1237
1238 _PyTime_t total = utime + utime;
1239 *tp = total;
1240 return 0;
Victor Stinnerec895392012-04-29 02:41:27 +02001241 }
1242#endif
1243
Victor Stinnerc29b5852017-11-02 07:28:27 -07001244 /* times() */
Victor Stinnerec895392012-04-29 02:41:27 +02001245#ifdef HAVE_TIMES
Victor Stinnerc29b5852017-11-02 07:28:27 -07001246 struct tms t;
1247
Victor Stinnerec895392012-04-29 02:41:27 +02001248 if (times(&t) != (clock_t)-1) {
Victor Stinnerc29b5852017-11-02 07:28:27 -07001249 static long ticks_per_second = -1;
Victor Stinnerec895392012-04-29 02:41:27 +02001250
1251 if (ticks_per_second == -1) {
Victor Stinnerc29b5852017-11-02 07:28:27 -07001252 long freq;
Victor Stinnerec895392012-04-29 02:41:27 +02001253#if defined(HAVE_SYSCONF) && defined(_SC_CLK_TCK)
Victor Stinnerc29b5852017-11-02 07:28:27 -07001254 freq = sysconf(_SC_CLK_TCK);
1255 if (freq < 1) {
1256 freq = -1;
1257 }
Victor Stinnerec895392012-04-29 02:41:27 +02001258#elif defined(HZ)
Victor Stinnerc29b5852017-11-02 07:28:27 -07001259 freq = HZ;
Victor Stinnerec895392012-04-29 02:41:27 +02001260#else
Victor Stinnerc29b5852017-11-02 07:28:27 -07001261 freq = 60; /* magic fallback value; may be bogus */
Victor Stinnerec895392012-04-29 02:41:27 +02001262#endif
Victor Stinnerc29b5852017-11-02 07:28:27 -07001263
1264 if (freq != -1) {
1265 /* check that _PyTime_MulDiv(t, SEC_TO_NS, ticks_per_second)
1266 cannot overflow below */
Serhiy Storchakabfe4fd52018-02-09 17:31:26 +02001267#if LONG_MAX > _PyTime_MAX / SEC_TO_NS
Victor Stinnerc29b5852017-11-02 07:28:27 -07001268 if ((_PyTime_t)freq > _PyTime_MAX / SEC_TO_NS) {
1269 PyErr_SetString(PyExc_OverflowError,
1270 "_SC_CLK_TCK is too large");
1271 return -1;
1272 }
Serhiy Storchakabfe4fd52018-02-09 17:31:26 +02001273#endif
Victor Stinnerc29b5852017-11-02 07:28:27 -07001274
1275 ticks_per_second = freq;
1276 }
Victor Stinnerec895392012-04-29 02:41:27 +02001277 }
1278
1279 if (ticks_per_second != -1) {
Victor Stinnerec895392012-04-29 02:41:27 +02001280 if (info) {
1281 info->implementation = "times()";
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001282 info->monotonic = 1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001283 info->adjustable = 0;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001284 info->resolution = 1.0 / (double)ticks_per_second;
Victor Stinnerec895392012-04-29 02:41:27 +02001285 }
Victor Stinnerc29b5852017-11-02 07:28:27 -07001286
1287 _PyTime_t total;
1288 total = _PyTime_MulDiv(t.tms_utime, SEC_TO_NS, ticks_per_second);
1289 total += _PyTime_MulDiv(t.tms_stime, SEC_TO_NS, ticks_per_second);
1290 *tp = total;
1291 return 0;
Victor Stinnerec895392012-04-29 02:41:27 +02001292 }
1293 }
1294#endif
1295
Victor Stinnerc29b5852017-11-02 07:28:27 -07001296 /* clock */
Victor Stinner53e22bf2016-07-08 17:55:01 +02001297 /* Currently, Python 3 requires clock() to build: see issue #22624 */
Victor Stinnerc29b5852017-11-02 07:28:27 -07001298 return _PyTime_GetClockWithInfo(tp, info);
Victor Stinnerec895392012-04-29 02:41:27 +02001299#endif
1300}
1301
1302static PyObject *
1303time_process_time(PyObject *self, PyObject *unused)
1304{
Victor Stinnerc29b5852017-11-02 07:28:27 -07001305 _PyTime_t t;
1306 if (_PyTime_GetProcessTimeWithInfo(&t, NULL) < 0) {
1307 return NULL;
1308 }
1309 return _PyFloat_FromPyTime(t);
Victor Stinnerec895392012-04-29 02:41:27 +02001310}
1311
1312PyDoc_STRVAR(process_time_doc,
1313"process_time() -> float\n\
1314\n\
1315Process time for profiling: sum of the kernel and user-space CPU time.");
1316
Victor Stinnerc29b5852017-11-02 07:28:27 -07001317static PyObject *
1318time_process_time_ns(PyObject *self, PyObject *unused)
1319{
1320 _PyTime_t t;
1321 if (_PyTime_GetProcessTimeWithInfo(&t, NULL) < 0) {
1322 return NULL;
1323 }
1324 return _PyTime_AsNanosecondsObject(t);
1325}
1326
1327PyDoc_STRVAR(process_time_ns_doc,
1328"process_time() -> int\n\
1329\n\
1330Process time for profiling as nanoseconds:\n\
1331sum of the kernel and user-space CPU time.");
1332
Victor Stinnerec895392012-04-29 02:41:27 +02001333
Antoine Pitrou4bd41c92017-11-15 22:52:21 +01001334#if defined(MS_WINDOWS)
1335#define HAVE_THREAD_TIME
1336static int
1337_PyTime_GetThreadTimeWithInfo(_PyTime_t *tp, _Py_clock_info_t *info)
1338{
1339 HANDLE thread;
1340 FILETIME creation_time, exit_time, kernel_time, user_time;
1341 ULARGE_INTEGER large;
1342 _PyTime_t ktime, utime, t;
1343 BOOL ok;
1344
1345 thread = GetCurrentThread();
1346 ok = GetThreadTimes(thread, &creation_time, &exit_time,
1347 &kernel_time, &user_time);
1348 if (!ok) {
1349 PyErr_SetFromWindowsErr(0);
1350 return -1;
1351 }
1352
1353 if (info) {
1354 info->implementation = "GetThreadTimes()";
1355 info->resolution = 1e-7;
1356 info->monotonic = 1;
1357 info->adjustable = 0;
1358 }
1359
1360 large.u.LowPart = kernel_time.dwLowDateTime;
1361 large.u.HighPart = kernel_time.dwHighDateTime;
1362 ktime = large.QuadPart;
1363
1364 large.u.LowPart = user_time.dwLowDateTime;
1365 large.u.HighPart = user_time.dwHighDateTime;
1366 utime = large.QuadPart;
1367
1368 /* ktime and utime have a resolution of 100 nanoseconds */
1369 t = _PyTime_FromNanoseconds((ktime + utime) * 100);
1370 *tp = t;
1371 return 0;
1372}
1373
1374#elif defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_PROCESS_CPUTIME_ID)
1375#define HAVE_THREAD_TIME
1376static int
1377_PyTime_GetThreadTimeWithInfo(_PyTime_t *tp, _Py_clock_info_t *info)
1378{
1379 struct timespec ts;
1380 const clockid_t clk_id = CLOCK_THREAD_CPUTIME_ID;
1381 const char *function = "clock_gettime(CLOCK_THREAD_CPUTIME_ID)";
1382
1383 if (clock_gettime(clk_id, &ts)) {
1384 PyErr_SetFromErrno(PyExc_OSError);
1385 return -1;
1386 }
1387 if (info) {
1388 struct timespec res;
1389 info->implementation = function;
1390 info->monotonic = 1;
1391 info->adjustable = 0;
1392 if (clock_getres(clk_id, &res)) {
1393 PyErr_SetFromErrno(PyExc_OSError);
1394 return -1;
1395 }
1396 info->resolution = res.tv_sec + res.tv_nsec * 1e-9;
1397 }
1398
1399 if (_PyTime_FromTimespec(tp, &ts) < 0) {
1400 return -1;
1401 }
1402 return 0;
1403}
1404#endif
1405
1406#ifdef HAVE_THREAD_TIME
1407static PyObject *
1408time_thread_time(PyObject *self, PyObject *unused)
1409{
1410 _PyTime_t t;
1411 if (_PyTime_GetThreadTimeWithInfo(&t, NULL) < 0) {
1412 return NULL;
1413 }
1414 return _PyFloat_FromPyTime(t);
1415}
1416
1417PyDoc_STRVAR(thread_time_doc,
1418"thread_time() -> float\n\
1419\n\
1420Thread time for profiling: sum of the kernel and user-space CPU time.");
1421
1422static PyObject *
1423time_thread_time_ns(PyObject *self, PyObject *unused)
1424{
1425 _PyTime_t t;
1426 if (_PyTime_GetThreadTimeWithInfo(&t, NULL) < 0) {
1427 return NULL;
1428 }
1429 return _PyTime_AsNanosecondsObject(t);
1430}
1431
1432PyDoc_STRVAR(thread_time_ns_doc,
1433"thread_time() -> int\n\
1434\n\
1435Thread time for profiling as nanoseconds:\n\
1436sum of the kernel and user-space CPU time.");
1437#endif
1438
1439
Victor Stinnerec895392012-04-29 02:41:27 +02001440static PyObject *
1441time_get_clock_info(PyObject *self, PyObject *args)
1442{
1443 char *name;
Victor Stinnerec895392012-04-29 02:41:27 +02001444 _Py_clock_info_t info;
Victor Stinnerbda4b882012-06-12 22:11:44 +02001445 PyObject *obj = NULL, *dict, *ns;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001446 _PyTime_t t;
Victor Stinnerec895392012-04-29 02:41:27 +02001447
Victor Stinnerc29b5852017-11-02 07:28:27 -07001448 if (!PyArg_ParseTuple(args, "s:get_clock_info", &name)) {
Victor Stinnerec895392012-04-29 02:41:27 +02001449 return NULL;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001450 }
Victor Stinnerec895392012-04-29 02:41:27 +02001451
1452#ifdef Py_DEBUG
1453 info.implementation = NULL;
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001454 info.monotonic = -1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001455 info.adjustable = -1;
Victor Stinnerec895392012-04-29 02:41:27 +02001456 info.resolution = -1.0;
1457#else
1458 info.implementation = "";
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001459 info.monotonic = 0;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001460 info.adjustable = 0;
Victor Stinnerec895392012-04-29 02:41:27 +02001461 info.resolution = 1.0;
1462#endif
1463
Victor Stinnerc29b5852017-11-02 07:28:27 -07001464 if (strcmp(name, "time") == 0) {
1465 if (_PyTime_GetSystemClockWithInfo(&t, &info) < 0) {
1466 return NULL;
1467 }
1468 }
Victor Stinnerec895392012-04-29 02:41:27 +02001469#ifdef PYCLOCK
Victor Stinnerc29b5852017-11-02 07:28:27 -07001470 else if (strcmp(name, "clock") == 0) {
Victor Stinnerec895392012-04-29 02:41:27 +02001471 obj = pyclock(&info);
Victor Stinnerc29b5852017-11-02 07:28:27 -07001472 if (obj == NULL) {
1473 return NULL;
1474 }
1475 Py_DECREF(obj);
1476 }
Victor Stinnerec895392012-04-29 02:41:27 +02001477#endif
Victor Stinnerc29b5852017-11-02 07:28:27 -07001478 else if (strcmp(name, "monotonic") == 0) {
1479 if (_PyTime_GetMonotonicClockWithInfo(&t, &info) < 0) {
1480 return NULL;
1481 }
1482 }
1483 else if (strcmp(name, "perf_counter") == 0) {
1484 if (_PyTime_GetPerfCounterWithInfo(&t, &info) < 0) {
1485 return NULL;
1486 }
1487 }
1488 else if (strcmp(name, "process_time") == 0) {
1489 if (_PyTime_GetProcessTimeWithInfo(&t, &info) < 0) {
1490 return NULL;
1491 }
1492 }
Antoine Pitrou4bd41c92017-11-15 22:52:21 +01001493#ifdef HAVE_THREAD_TIME
1494 else if (strcmp(name, "thread_time") == 0) {
1495 if (_PyTime_GetThreadTimeWithInfo(&t, &info) < 0) {
1496 return NULL;
1497 }
1498 }
1499#endif
Victor Stinnerec895392012-04-29 02:41:27 +02001500 else {
1501 PyErr_SetString(PyExc_ValueError, "unknown clock");
1502 return NULL;
1503 }
Victor Stinnerec895392012-04-29 02:41:27 +02001504
Victor Stinnerbda4b882012-06-12 22:11:44 +02001505 dict = PyDict_New();
Victor Stinnerc29b5852017-11-02 07:28:27 -07001506 if (dict == NULL) {
Victor Stinnerec895392012-04-29 02:41:27 +02001507 return NULL;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001508 }
Victor Stinnerec895392012-04-29 02:41:27 +02001509
1510 assert(info.implementation != NULL);
1511 obj = PyUnicode_FromString(info.implementation);
Victor Stinnerc29b5852017-11-02 07:28:27 -07001512 if (obj == NULL) {
Victor Stinnerec895392012-04-29 02:41:27 +02001513 goto error;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001514 }
1515 if (PyDict_SetItemString(dict, "implementation", obj) == -1) {
Victor Stinnerbda4b882012-06-12 22:11:44 +02001516 goto error;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001517 }
Victor Stinnerbda4b882012-06-12 22:11:44 +02001518 Py_CLEAR(obj);
Victor Stinnerec895392012-04-29 02:41:27 +02001519
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001520 assert(info.monotonic != -1);
1521 obj = PyBool_FromLong(info.monotonic);
Victor Stinnerc29b5852017-11-02 07:28:27 -07001522 if (obj == NULL) {
Victor Stinnerec895392012-04-29 02:41:27 +02001523 goto error;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001524 }
1525 if (PyDict_SetItemString(dict, "monotonic", obj) == -1) {
Victor Stinnerbda4b882012-06-12 22:11:44 +02001526 goto error;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001527 }
Victor Stinnerbda4b882012-06-12 22:11:44 +02001528 Py_CLEAR(obj);
Victor Stinnerec895392012-04-29 02:41:27 +02001529
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001530 assert(info.adjustable != -1);
1531 obj = PyBool_FromLong(info.adjustable);
Victor Stinnerc29b5852017-11-02 07:28:27 -07001532 if (obj == NULL) {
Victor Stinnerec895392012-04-29 02:41:27 +02001533 goto error;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001534 }
1535 if (PyDict_SetItemString(dict, "adjustable", obj) == -1) {
Victor Stinnerbda4b882012-06-12 22:11:44 +02001536 goto error;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001537 }
Victor Stinnerbda4b882012-06-12 22:11:44 +02001538 Py_CLEAR(obj);
Victor Stinnerec895392012-04-29 02:41:27 +02001539
1540 assert(info.resolution > 0.0);
1541 assert(info.resolution <= 1.0);
1542 obj = PyFloat_FromDouble(info.resolution);
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, "resolution", 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
Victor Stinnerbda4b882012-06-12 22:11:44 +02001551 ns = _PyNamespace_New(dict);
1552 Py_DECREF(dict);
1553 return ns;
Victor Stinnerec895392012-04-29 02:41:27 +02001554
1555error:
Victor Stinnerbda4b882012-06-12 22:11:44 +02001556 Py_DECREF(dict);
1557 Py_XDECREF(obj);
Victor Stinnerec895392012-04-29 02:41:27 +02001558 return NULL;
1559}
1560
1561PyDoc_STRVAR(get_clock_info_doc,
1562"get_clock_info(name: str) -> dict\n\
1563\n\
1564Get information of the specified clock.");
Victor Stinner8b302012012-02-07 23:29:46 +01001565
Benjamin Petersonc510c6b2018-09-20 19:52:18 -07001566#ifndef HAVE_DECL_TZNAME
Victor Stinner1fb399b2018-09-17 13:56:17 -07001567static void
1568get_zone(char *zone, int n, struct tm *p)
1569{
1570#ifdef HAVE_STRUCT_TM_TM_ZONE
1571 strncpy(zone, p->tm_zone ? p->tm_zone : " ", n);
1572#else
1573 tzset();
1574 strftime(zone, n, "%Z", p);
1575#endif
1576}
1577
Victor Stinner503ce5c2018-12-01 00:39:36 +01001578static time_t
Victor Stinner1fb399b2018-09-17 13:56:17 -07001579get_gmtoff(time_t t, struct tm *p)
1580{
1581#ifdef HAVE_STRUCT_TM_TM_ZONE
1582 return p->tm_gmtoff;
1583#else
1584 return timegm(p) - t;
1585#endif
1586}
Benjamin Petersonc510c6b2018-09-20 19:52:18 -07001587#endif // !HAVE_DECL_TZNAME
Victor Stinner1fb399b2018-09-17 13:56:17 -07001588
Victor Stinner503ce5c2018-12-01 00:39:36 +01001589static int
Victor Stinner3bb150d2018-12-03 13:45:38 +01001590init_timezone(PyObject *m)
Victor Stinner503ce5c2018-12-01 00:39:36 +01001591{
1592 assert(!PyErr_Occurred());
1593
Martin v. Löwis1a214512008-06-11 05:26:20 +00001594 /* This code moved from PyInit_time wholesale to allow calling it from
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001595 time_tzset. In the future, some parts of it can be moved back
1596 (for platforms that don't HAVE_WORKING_TZSET, when we know what they
1597 are), and the extraneous calls to tzset(3) should be removed.
1598 I haven't done this yet, as I don't want to change this code as
1599 little as possible when introducing the time.tzset and time.tzsetwall
1600 methods. This should simply be a method of doing the following once,
1601 at the top of this function and removing the call to tzset() from
1602 time_tzset():
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001603
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001604 #ifdef HAVE_TZSET
1605 tzset()
1606 #endif
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001607
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001608 And I'm lazy and hate C so nyer.
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001609 */
Benjamin Petersonc510c6b2018-09-20 19:52:18 -07001610#ifdef HAVE_DECL_TZNAME
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001611 PyObject *otz0, *otz1;
1612 tzset();
Zackery Spytz6673dec2019-02-25 16:56:44 -07001613 PyModule_AddIntConstant(m, "timezone", _Py_timezone);
Guido van Rossumb6775db1994-08-01 11:34:53 +00001614#ifdef HAVE_ALTZONE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001615 PyModule_AddIntConstant(m, "altzone", altzone);
Guido van Rossumb6775db1994-08-01 11:34:53 +00001616#else
Zackery Spytz6673dec2019-02-25 16:56:44 -07001617 PyModule_AddIntConstant(m, "altzone", _Py_timezone-3600);
Guido van Rossumb6775db1994-08-01 11:34:53 +00001618#endif
Zackery Spytz6673dec2019-02-25 16:56:44 -07001619 PyModule_AddIntConstant(m, "daylight", _Py_daylight);
1620 otz0 = PyUnicode_DecodeLocale(_Py_tzname[0], "surrogateescape");
Benjamin Petersonc510c6b2018-09-20 19:52:18 -07001621 if (otz0 == NULL) {
Victor Stinnerab661492018-12-03 12:02:43 +01001622 return -1;
Victor Stinner1fb399b2018-09-17 13:56:17 -07001623 }
Zackery Spytz6673dec2019-02-25 16:56:44 -07001624 otz1 = PyUnicode_DecodeLocale(_Py_tzname[1], "surrogateescape");
Benjamin Petersonc510c6b2018-09-20 19:52:18 -07001625 if (otz1 == NULL) {
1626 Py_DECREF(otz0);
Victor Stinnerab661492018-12-03 12:02:43 +01001627 return -1;
Benjamin Petersonc510c6b2018-09-20 19:52:18 -07001628 }
1629 PyObject *tzname_obj = Py_BuildValue("(NN)", otz0, otz1);
Victor Stinnerab661492018-12-03 12:02:43 +01001630 if (tzname_obj == NULL) {
1631 return -1;
1632 }
Benjamin Petersonc510c6b2018-09-20 19:52:18 -07001633 PyModule_AddObject(m, "tzname", tzname_obj);
1634#else // !HAVE_DECL_TZNAME
1635 static const time_t YEAR = (365 * 24 + 6) * 3600;
1636 time_t t;
1637 struct tm p;
Victor Stinner503ce5c2018-12-01 00:39:36 +01001638 time_t janzone_t, julyzone_t;
Benjamin Petersonc510c6b2018-09-20 19:52:18 -07001639 char janname[10], julyname[10];
1640 t = (time((time_t *)0) / YEAR) * YEAR;
1641 _PyTime_localtime(t, &p);
1642 get_zone(janname, 9, &p);
Victor Stinner503ce5c2018-12-01 00:39:36 +01001643 janzone_t = -get_gmtoff(t, &p);
Benjamin Petersonc510c6b2018-09-20 19:52:18 -07001644 janname[9] = '\0';
1645 t += YEAR/2;
1646 _PyTime_localtime(t, &p);
1647 get_zone(julyname, 9, &p);
Victor Stinner503ce5c2018-12-01 00:39:36 +01001648 julyzone_t = -get_gmtoff(t, &p);
Benjamin Petersonc510c6b2018-09-20 19:52:18 -07001649 julyname[9] = '\0';
1650
Victor Stinner503ce5c2018-12-01 00:39:36 +01001651 /* Sanity check, don't check for the validity of timezones.
1652 In practice, it should be more in range -12 hours .. +14 hours. */
1653#define MAX_TIMEZONE (48 * 3600)
1654 if (janzone_t < -MAX_TIMEZONE || janzone_t > MAX_TIMEZONE
1655 || julyzone_t < -MAX_TIMEZONE || julyzone_t > MAX_TIMEZONE)
1656 {
1657 PyErr_SetString(PyExc_RuntimeError, "invalid GMT offset");
1658 return -1;
1659 }
1660 int janzone = (int)janzone_t;
1661 int julyzone = (int)julyzone_t;
1662
Benjamin Petersonc510c6b2018-09-20 19:52:18 -07001663 PyObject *tzname_obj;
1664 if (janzone < julyzone) {
1665 /* DST is reversed in the southern hemisphere */
1666 PyModule_AddIntConstant(m, "timezone", julyzone);
1667 PyModule_AddIntConstant(m, "altzone", janzone);
1668 PyModule_AddIntConstant(m, "daylight", janzone != julyzone);
1669 tzname_obj = Py_BuildValue("(zz)", julyname, janname);
1670 } else {
1671 PyModule_AddIntConstant(m, "timezone", janzone);
1672 PyModule_AddIntConstant(m, "altzone", julyzone);
1673 PyModule_AddIntConstant(m, "daylight", janzone != julyzone);
1674 tzname_obj = Py_BuildValue("(zz)", janname, julyname);
1675 }
Victor Stinner503ce5c2018-12-01 00:39:36 +01001676 if (tzname_obj == NULL) {
1677 return -1;
1678 }
Benjamin Petersonc510c6b2018-09-20 19:52:18 -07001679 PyModule_AddObject(m, "tzname", tzname_obj);
1680#endif // !HAVE_DECL_TZNAME
Victor Stinner503ce5c2018-12-01 00:39:36 +01001681
1682 if (PyErr_Occurred()) {
1683 return -1;
1684 }
1685 return 0;
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001686}
1687
1688
1689static PyMethodDef time_methods[] = {
Victor Stinner4195b5c2012-02-08 23:03:19 +01001690 {"time", time_time, METH_NOARGS, time_doc},
Victor Stinnerc29b5852017-11-02 07:28:27 -07001691 {"time_ns", time_time_ns, METH_NOARGS, time_ns_doc},
Victor Stinnerec895392012-04-29 02:41:27 +02001692#ifdef PYCLOCK
Victor Stinner4195b5c2012-02-08 23:03:19 +01001693 {"clock", time_clock, METH_NOARGS, clock_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001694#endif
Victor Stinnere0be4232011-10-25 13:06:09 +02001695#ifdef HAVE_CLOCK_GETTIME
Victor Stinner4195b5c2012-02-08 23:03:19 +01001696 {"clock_gettime", time_clock_gettime, METH_VARARGS, clock_gettime_doc},
Victor Stinnerc29b5852017-11-02 07:28:27 -07001697 {"clock_gettime_ns",time_clock_gettime_ns, METH_VARARGS, clock_gettime_ns_doc},
Benjamin Peterson37098cd2016-09-13 22:55:09 -07001698#endif
1699#ifdef HAVE_CLOCK_SETTIME
Victor Stinner30d79472012-04-03 00:45:07 +02001700 {"clock_settime", time_clock_settime, METH_VARARGS, clock_settime_doc},
Victor Stinnerc29b5852017-11-02 07:28:27 -07001701 {"clock_settime_ns",time_clock_settime_ns, METH_VARARGS, clock_settime_ns_doc},
Benjamin Peterson37098cd2016-09-13 22:55:09 -07001702#endif
1703#ifdef HAVE_CLOCK_GETRES
Victor Stinner4195b5c2012-02-08 23:03:19 +01001704 {"clock_getres", time_clock_getres, METH_VARARGS, clock_getres_doc},
Victor Stinnere0be4232011-10-25 13:06:09 +02001705#endif
pdoxe14679c2017-10-05 00:01:56 -07001706#ifdef HAVE_PTHREAD_GETCPUCLOCKID
1707 {"pthread_getcpuclockid", time_pthread_getcpuclockid, METH_VARARGS, pthread_getcpuclockid_doc},
1708#endif
Victor Stinnercb29f012015-03-27 13:31:18 +01001709 {"sleep", time_sleep, METH_O, sleep_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001710 {"gmtime", time_gmtime, METH_VARARGS, gmtime_doc},
1711 {"localtime", time_localtime, METH_VARARGS, localtime_doc},
1712 {"asctime", time_asctime, METH_VARARGS, asctime_doc},
1713 {"ctime", time_ctime, METH_VARARGS, ctime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001714#ifdef HAVE_MKTIME
Victor Stinner4195b5c2012-02-08 23:03:19 +01001715 {"mktime", time_mktime, METH_O, mktime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001716#endif
1717#ifdef HAVE_STRFTIME
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001718 {"strftime", time_strftime, METH_VARARGS, strftime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001719#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001720 {"strptime", time_strptime, METH_VARARGS, strptime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001721#ifdef HAVE_WORKING_TZSET
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001722 {"tzset", time_tzset, METH_NOARGS, tzset_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001723#endif
Victor Stinnerec895392012-04-29 02:41:27 +02001724 {"monotonic", time_monotonic, METH_NOARGS, monotonic_doc},
Victor Stinnerc29b5852017-11-02 07:28:27 -07001725 {"monotonic_ns", time_monotonic_ns, METH_NOARGS, monotonic_ns_doc},
Victor Stinnerec895392012-04-29 02:41:27 +02001726 {"process_time", time_process_time, METH_NOARGS, process_time_doc},
Victor Stinnerc29b5852017-11-02 07:28:27 -07001727 {"process_time_ns", time_process_time_ns, METH_NOARGS, process_time_ns_doc},
Antoine Pitrou4bd41c92017-11-15 22:52:21 +01001728#ifdef HAVE_THREAD_TIME
1729 {"thread_time", time_thread_time, METH_NOARGS, thread_time_doc},
1730 {"thread_time_ns", time_thread_time_ns, METH_NOARGS, thread_time_ns_doc},
1731#endif
Victor Stinnerec895392012-04-29 02:41:27 +02001732 {"perf_counter", time_perf_counter, METH_NOARGS, perf_counter_doc},
Victor Stinnerc29b5852017-11-02 07:28:27 -07001733 {"perf_counter_ns", time_perf_counter_ns, METH_NOARGS, perf_counter_ns_doc},
Victor Stinnerec895392012-04-29 02:41:27 +02001734 {"get_clock_info", time_get_clock_info, METH_VARARGS, get_clock_info_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001735 {NULL, NULL} /* sentinel */
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001736};
1737
1738
1739PyDoc_STRVAR(module_doc,
1740"This module provides various functions to manipulate time values.\n\
1741\n\
1742There are two standard representations of time. One is the number\n\
1743of seconds since the Epoch, in UTC (a.k.a. GMT). It may be an integer\n\
1744or a floating point number (to represent fractions of seconds).\n\
1745The Epoch is system-defined; on Unix, it is generally January 1st, 1970.\n\
1746The actual value can be retrieved by calling gmtime(0).\n\
1747\n\
1748The other representation is a tuple of 9 integers giving local time.\n\
1749The tuple items are:\n\
Alexander Belopolsky03163ac2011-05-02 12:20:52 -04001750 year (including century, e.g. 1998)\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001751 month (1-12)\n\
1752 day (1-31)\n\
1753 hours (0-23)\n\
1754 minutes (0-59)\n\
1755 seconds (0-59)\n\
1756 weekday (0-6, Monday is 0)\n\
1757 Julian day (day in the year, 1-366)\n\
1758 DST (Daylight Savings Time) flag (-1, 0 or 1)\n\
1759If the DST flag is 0, the time is given in the regular time zone;\n\
1760if it is 1, the time is given in the DST time zone;\n\
Cheryl Sabella703ff382017-10-11 09:29:14 -04001761if it is -1, mktime() should guess based on the date and time.\n");
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001762
1763
Martin v. Löwis1a214512008-06-11 05:26:20 +00001764
1765static struct PyModuleDef timemodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001766 PyModuleDef_HEAD_INIT,
1767 "time",
1768 module_doc,
1769 -1,
1770 time_methods,
1771 NULL,
1772 NULL,
1773 NULL,
1774 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00001775};
1776
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001777PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00001778PyInit_time(void)
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001779{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001780 PyObject *m;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001781 m = PyModule_Create(&timemodule);
1782 if (m == NULL)
1783 return NULL;
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001784
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001785 /* Set, or reset, module variables like time.timezone */
Victor Stinner3bb150d2018-12-03 13:45:38 +01001786 if (init_timezone(m) < 0) {
Victor Stinner503ce5c2018-12-01 00:39:36 +01001787 return NULL;
1788 }
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001789
Max Bélanger94451182018-10-20 17:07:54 -07001790#if defined(HAVE_CLOCK_GETTIME) || defined(HAVE_CLOCK_SETTIME) || defined(HAVE_CLOCK_GETRES)
1791
Benjamin Peterson37098cd2016-09-13 22:55:09 -07001792#ifdef CLOCK_REALTIME
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -04001793 PyModule_AddIntMacro(m, CLOCK_REALTIME);
Benjamin Peterson37098cd2016-09-13 22:55:09 -07001794#endif
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -04001795#ifdef CLOCK_MONOTONIC
1796 PyModule_AddIntMacro(m, CLOCK_MONOTONIC);
1797#endif
1798#ifdef CLOCK_MONOTONIC_RAW
1799 PyModule_AddIntMacro(m, CLOCK_MONOTONIC_RAW);
1800#endif
1801#ifdef CLOCK_HIGHRES
1802 PyModule_AddIntMacro(m, CLOCK_HIGHRES);
1803#endif
1804#ifdef CLOCK_PROCESS_CPUTIME_ID
1805 PyModule_AddIntMacro(m, CLOCK_PROCESS_CPUTIME_ID);
1806#endif
1807#ifdef CLOCK_THREAD_CPUTIME_ID
1808 PyModule_AddIntMacro(m, CLOCK_THREAD_CPUTIME_ID);
1809#endif
Victor Stinnera64ce972017-11-02 04:19:19 -07001810#ifdef CLOCK_PROF
1811 PyModule_AddIntMacro(m, CLOCK_PROF);
1812#endif
1813#ifdef CLOCK_BOOTTIME
1814 PyModule_AddIntMacro(m, CLOCK_BOOTTIME);
1815#endif
1816#ifdef CLOCK_UPTIME
1817 PyModule_AddIntMacro(m, CLOCK_UPTIME);
1818#endif
Joannah Nanjekye572168a2019-01-10 19:56:38 +03001819#ifdef CLOCK_UPTIME_RAW
1820 PyModule_AddIntMacro(m, CLOCK_UPTIME_RAW);
1821#endif
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -04001822
Max Bélanger94451182018-10-20 17:07:54 -07001823#endif /* defined(HAVE_CLOCK_GETTIME) || defined(HAVE_CLOCK_SETTIME) || defined(HAVE_CLOCK_GETRES) */
1824
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001825 if (!initialized) {
Victor Stinner1c8f0592013-07-22 22:24:54 +02001826 if (PyStructSequence_InitType2(&StructTimeType,
1827 &struct_time_type_desc) < 0)
1828 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001829 }
1830 Py_INCREF(&StructTimeType);
Alexander Belopolskyc142bba2012-06-13 22:15:26 -04001831 PyModule_AddIntConstant(m, "_STRUCT_TM_ITEMS", 11);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001832 PyModule_AddObject(m, "struct_time", (PyObject*) &StructTimeType);
1833 initialized = 1;
Benjamin Peterson5633c4f2018-09-14 09:09:04 -07001834
1835#if defined(__linux__) && !defined(__GLIBC__)
1836 struct tm tm;
Benjamin Petersonb93062b2018-09-14 10:39:13 -07001837 const time_t zero = 0;
1838 if (gmtime_r(&zero, &tm) != NULL)
Benjamin Peterson5633c4f2018-09-14 09:09:04 -07001839 utc_string = tm.tm_zone;
1840#endif
1841
Victor Stinner3bb150d2018-12-03 13:45:38 +01001842 if (PyErr_Occurred()) {
1843 return NULL;
1844 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001845 return m;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001846}
1847
Victor Stinnercb29f012015-03-27 13:31:18 +01001848/* Implement pysleep() for various platforms.
Guido van Rossumb6775db1994-08-01 11:34:53 +00001849 When interrupted (or when another error occurs), return -1 and
1850 set an exception; else return 0. */
1851
1852static int
Victor Stinnercb29f012015-03-27 13:31:18 +01001853pysleep(_PyTime_t secs)
Guido van Rossum426035c1991-02-19 12:27:35 +00001854{
Victor Stinnercb29f012015-03-27 13:31:18 +01001855 _PyTime_t deadline, monotonic;
Victor Stinner79d68f92015-03-19 21:54:09 +01001856#ifndef MS_WINDOWS
1857 struct timeval timeout;
Victor Stinner79d68f92015-03-19 21:54:09 +01001858 int err = 0;
1859#else
Victor Stinnercb29f012015-03-27 13:31:18 +01001860 _PyTime_t millisecs;
Victor Stinner79d68f92015-03-19 21:54:09 +01001861 unsigned long ul_millis;
1862 DWORD rc;
1863 HANDLE hInterruptEvent;
Victor Stinner0c2fd892015-03-17 10:49:17 +01001864#endif
Victor Stinner79d68f92015-03-19 21:54:09 +01001865
Victor Stinnercb29f012015-03-27 13:31:18 +01001866 deadline = _PyTime_GetMonotonicClock() + secs;
Victor Stinner79d68f92015-03-19 21:54:09 +01001867
1868 do {
1869#ifndef MS_WINDOWS
Victor Stinner869e1772015-03-30 03:49:14 +02001870 if (_PyTime_AsTimeval(secs, &timeout, _PyTime_ROUND_CEILING) < 0)
Victor Stinnercb29f012015-03-27 13:31:18 +01001871 return -1;
Victor Stinner79d68f92015-03-19 21:54:09 +01001872
1873 Py_BEGIN_ALLOW_THREADS
1874 err = select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &timeout);
1875 Py_END_ALLOW_THREADS
1876
1877 if (err == 0)
1878 break;
1879
1880 if (errno != EINTR) {
Victor Stinner0c2fd892015-03-17 10:49:17 +01001881 PyErr_SetFromErrno(PyExc_OSError);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001882 return -1;
1883 }
Victor Stinner79d68f92015-03-19 21:54:09 +01001884#else
Victor Stinner869e1772015-03-30 03:49:14 +02001885 millisecs = _PyTime_AsMilliseconds(secs, _PyTime_ROUND_CEILING);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001886 if (millisecs > (double)ULONG_MAX) {
1887 PyErr_SetString(PyExc_OverflowError,
1888 "sleep length is too large");
1889 return -1;
1890 }
Victor Stinner79d68f92015-03-19 21:54:09 +01001891
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001892 /* Allow sleep(0) to maintain win32 semantics, and as decreed
1893 * by Guido, only the main thread can be interrupted.
1894 */
1895 ul_millis = (unsigned long)millisecs;
Victor Stinner79d68f92015-03-19 21:54:09 +01001896 if (ul_millis == 0 || !_PyOS_IsMainThread()) {
1897 Py_BEGIN_ALLOW_THREADS
Victor Stinner0eac1302015-03-20 03:06:12 +01001898 Sleep(ul_millis);
Victor Stinner79d68f92015-03-19 21:54:09 +01001899 Py_END_ALLOW_THREADS
1900 break;
Victor Stinner945c82e2015-03-12 16:19:01 +01001901 }
Victor Stinner79d68f92015-03-19 21:54:09 +01001902
1903 hInterruptEvent = _PyOS_SigintEvent();
1904 ResetEvent(hInterruptEvent);
1905
1906 Py_BEGIN_ALLOW_THREADS
1907 rc = WaitForSingleObjectEx(hInterruptEvent, ul_millis, FALSE);
Victor Stinner0c2fd892015-03-17 10:49:17 +01001908 Py_END_ALLOW_THREADS
Victor Stinner79d68f92015-03-19 21:54:09 +01001909
1910 if (rc != WAIT_OBJECT_0)
1911 break;
Victor Stinner945c82e2015-03-12 16:19:01 +01001912#endif
Victor Stinner0c2fd892015-03-17 10:49:17 +01001913
Victor Stinner79d68f92015-03-19 21:54:09 +01001914 /* sleep was interrupted by SIGINT */
1915 if (PyErr_CheckSignals())
1916 return -1;
1917
Victor Stinnercb29f012015-03-27 13:31:18 +01001918 monotonic = _PyTime_GetMonotonicClock();
1919 secs = deadline - monotonic;
Victor Stinner6aa446c2015-03-30 21:33:51 +02001920 if (secs < 0)
Victor Stinner79d68f92015-03-19 21:54:09 +01001921 break;
1922 /* retry with the recomputed delay */
1923 } while (1);
1924
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001925 return 0;
Guido van Rossum80c9d881991-04-16 08:47:51 +00001926}