blob: ae7de5b2c7664086c0782b925e7341bc9ada9618 [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
Miss Islington (bot)01b96642018-12-30 17:59:19 -080037#ifdef _Py_MEMORY_SANITIZER
38# include <sanitizer/msan_interface.h>
39#endif
40
Miss Islington (bot)0b3019a2019-02-25 16:15:04 -080041#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 Stinnerb8d01692012-04-13 23:44:05 +0200191 int clk_id;
Victor Stinnere0be4232011-10-25 13:06:09 +0200192 struct timespec tp;
193
Victor Stinnerc29b5852017-11-02 07:28:27 -0700194 if (!PyArg_ParseTuple(args, "i:clock_gettime", &clk_id)) {
Victor Stinnere0be4232011-10-25 13:06:09 +0200195 return NULL;
Victor Stinnerc29b5852017-11-02 07:28:27 -0700196 }
Victor Stinnere0be4232011-10-25 13:06:09 +0200197
198 ret = clock_gettime((clockid_t)clk_id, &tp);
Antoine Pitrou2c085602012-01-18 01:41:44 +0100199 if (ret != 0) {
Victor Stinnera734af32014-07-31 13:07:17 +0200200 PyErr_SetFromErrno(PyExc_OSError);
Antoine Pitrou2c085602012-01-18 01:41:44 +0100201 return NULL;
202 }
Victor Stinner4195b5c2012-02-08 23:03:19 +0100203 return PyFloat_FromDouble(tp.tv_sec + tp.tv_nsec * 1e-9);
Victor Stinnere0be4232011-10-25 13:06:09 +0200204}
205
206PyDoc_STRVAR(clock_gettime_doc,
Victor Stinnerc29b5852017-11-02 07:28:27 -0700207"clock_gettime(clk_id) -> float\n\
Victor Stinnere0be4232011-10-25 13:06:09 +0200208\n\
209Return the time of the specified clock clk_id.");
Victor Stinnerc29b5852017-11-02 07:28:27 -0700210
211static PyObject *
212time_clock_gettime_ns(PyObject *self, PyObject *args)
213{
214 int ret;
215 int clk_id;
216 struct timespec ts;
217 _PyTime_t t;
218
219 if (!PyArg_ParseTuple(args, "i:clock_gettime", &clk_id)) {
220 return NULL;
221 }
222
223 ret = clock_gettime((clockid_t)clk_id, &ts);
224 if (ret != 0) {
225 PyErr_SetFromErrno(PyExc_OSError);
226 return NULL;
227 }
228 if (_PyTime_FromTimespec(&t, &ts) < 0) {
229 return NULL;
230 }
231 return _PyTime_AsNanosecondsObject(t);
232}
233
234PyDoc_STRVAR(clock_gettime_ns_doc,
235"clock_gettime_ns(clk_id) -> int\n\
236\n\
237Return the time of the specified clock clk_id as nanoseconds.");
Benjamin Peterson37098cd2016-09-13 22:55:09 -0700238#endif /* HAVE_CLOCK_GETTIME */
Victor Stinner30d79472012-04-03 00:45:07 +0200239
Benjamin Peterson37098cd2016-09-13 22:55:09 -0700240#ifdef HAVE_CLOCK_SETTIME
Victor Stinner30d79472012-04-03 00:45:07 +0200241static PyObject *
242time_clock_settime(PyObject *self, PyObject *args)
243{
Victor Stinnerb8d01692012-04-13 23:44:05 +0200244 int clk_id;
Victor Stinner30d79472012-04-03 00:45:07 +0200245 PyObject *obj;
Victor Stinnerb3b45442015-03-28 04:09:41 +0100246 _PyTime_t t;
Victor Stinner30d79472012-04-03 00:45:07 +0200247 struct timespec tp;
248 int ret;
249
250 if (!PyArg_ParseTuple(args, "iO:clock_settime", &clk_id, &obj))
251 return NULL;
252
Victor Stinner02937aa2015-03-28 05:02:39 +0100253 if (_PyTime_FromSecondsObject(&t, obj, _PyTime_ROUND_FLOOR) < 0)
Victor Stinner30d79472012-04-03 00:45:07 +0200254 return NULL;
Victor Stinnerb3b45442015-03-28 04:09:41 +0100255
256 if (_PyTime_AsTimespec(t, &tp) == -1)
257 return NULL;
Victor Stinner30d79472012-04-03 00:45:07 +0200258
259 ret = clock_settime((clockid_t)clk_id, &tp);
260 if (ret != 0) {
Victor Stinnera734af32014-07-31 13:07:17 +0200261 PyErr_SetFromErrno(PyExc_OSError);
Victor Stinner30d79472012-04-03 00:45:07 +0200262 return NULL;
263 }
264 Py_RETURN_NONE;
265}
266
267PyDoc_STRVAR(clock_settime_doc,
268"clock_settime(clk_id, time)\n\
269\n\
270Set the time of the specified clock clk_id.");
Victor Stinnerc29b5852017-11-02 07:28:27 -0700271
272static PyObject *
273time_clock_settime_ns(PyObject *self, PyObject *args)
274{
275 int clk_id;
276 PyObject *obj;
277 _PyTime_t t;
278 struct timespec ts;
279 int ret;
280
281 if (!PyArg_ParseTuple(args, "iO:clock_settime", &clk_id, &obj)) {
282 return NULL;
283 }
284
285 if (_PyTime_FromNanosecondsObject(&t, obj) < 0) {
286 return NULL;
287 }
288 if (_PyTime_AsTimespec(t, &ts) == -1) {
289 return NULL;
290 }
291
292 ret = clock_settime((clockid_t)clk_id, &ts);
293 if (ret != 0) {
294 PyErr_SetFromErrno(PyExc_OSError);
295 return NULL;
296 }
297 Py_RETURN_NONE;
298}
299
300PyDoc_STRVAR(clock_settime_ns_doc,
301"clock_settime_ns(clk_id, time)\n\
302\n\
303Set the time of the specified clock clk_id with nanoseconds.");
Benjamin Peterson37098cd2016-09-13 22:55:09 -0700304#endif /* HAVE_CLOCK_SETTIME */
Victor Stinnere0be4232011-10-25 13:06:09 +0200305
Benjamin Peterson37098cd2016-09-13 22:55:09 -0700306#ifdef HAVE_CLOCK_GETRES
Victor Stinnere0be4232011-10-25 13:06:09 +0200307static PyObject *
Victor Stinner4195b5c2012-02-08 23:03:19 +0100308time_clock_getres(PyObject *self, PyObject *args)
Victor Stinnere0be4232011-10-25 13:06:09 +0200309{
310 int ret;
Victor Stinnerb8d01692012-04-13 23:44:05 +0200311 int clk_id;
Victor Stinnere0be4232011-10-25 13:06:09 +0200312 struct timespec tp;
313
Victor Stinner4195b5c2012-02-08 23:03:19 +0100314 if (!PyArg_ParseTuple(args, "i:clock_getres", &clk_id))
Victor Stinnere0be4232011-10-25 13:06:09 +0200315 return NULL;
316
317 ret = clock_getres((clockid_t)clk_id, &tp);
Antoine Pitrou2c085602012-01-18 01:41:44 +0100318 if (ret != 0) {
Victor Stinnera734af32014-07-31 13:07:17 +0200319 PyErr_SetFromErrno(PyExc_OSError);
Antoine Pitrou2c085602012-01-18 01:41:44 +0100320 return NULL;
321 }
Victor Stinner4195b5c2012-02-08 23:03:19 +0100322
323 return PyFloat_FromDouble(tp.tv_sec + tp.tv_nsec * 1e-9);
Victor Stinnere0be4232011-10-25 13:06:09 +0200324}
325
326PyDoc_STRVAR(clock_getres_doc,
Victor Stinner4195b5c2012-02-08 23:03:19 +0100327"clock_getres(clk_id) -> floating point number\n\
Victor Stinnere0be4232011-10-25 13:06:09 +0200328\n\
329Return the resolution (precision) of the specified clock clk_id.");
Benjamin Peterson37098cd2016-09-13 22:55:09 -0700330#endif /* HAVE_CLOCK_GETRES */
Victor Stinnere0be4232011-10-25 13:06:09 +0200331
pdoxe14679c2017-10-05 00:01:56 -0700332#ifdef HAVE_PTHREAD_GETCPUCLOCKID
333static PyObject *
334time_pthread_getcpuclockid(PyObject *self, PyObject *args)
335{
336 unsigned long thread_id;
337 int err;
338 clockid_t clk_id;
339 if (!PyArg_ParseTuple(args, "k:pthread_getcpuclockid", &thread_id)) {
340 return NULL;
341 }
342 err = pthread_getcpuclockid((pthread_t)thread_id, &clk_id);
343 if (err) {
344 errno = err;
345 PyErr_SetFromErrno(PyExc_OSError);
346 return NULL;
347 }
Miss Islington (bot)01b96642018-12-30 17:59:19 -0800348#ifdef _Py_MEMORY_SANITIZER
349 __msan_unpoison(&clk_id, sizeof(clk_id));
350#endif
pdoxe14679c2017-10-05 00:01:56 -0700351 return PyLong_FromLong(clk_id);
352}
353
354PyDoc_STRVAR(pthread_getcpuclockid_doc,
355"pthread_getcpuclockid(thread_id) -> int\n\
356\n\
357Return the clk_id of a thread's CPU time clock.");
358#endif /* HAVE_PTHREAD_GETCPUCLOCKID */
359
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000360static PyObject *
Victor Stinnercb29f012015-03-27 13:31:18 +0100361time_sleep(PyObject *self, PyObject *obj)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000362{
Victor Stinnercb29f012015-03-27 13:31:18 +0100363 _PyTime_t secs;
Pablo Galindo59af94f2017-10-18 08:13:09 +0100364 if (_PyTime_FromSecondsObject(&secs, obj, _PyTime_ROUND_TIMEOUT))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000365 return NULL;
Victor Stinner7f53a502011-07-05 22:00:25 +0200366 if (secs < 0) {
367 PyErr_SetString(PyExc_ValueError,
368 "sleep length must be non-negative");
369 return NULL;
370 }
Victor Stinnercb29f012015-03-27 13:31:18 +0100371 if (pysleep(secs) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000372 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200373 Py_RETURN_NONE;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000374}
375
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000376PyDoc_STRVAR(sleep_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000377"sleep(seconds)\n\
378\n\
379Delay execution for a given number of seconds. The argument may be\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000380a floating point number for subsecond precision.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000381
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000382static PyStructSequence_Field struct_time_type_fields[] = {
Alexander Belopolsky69f3fd02010-06-05 15:04:51 +0000383 {"tm_year", "year, for example, 1993"},
384 {"tm_mon", "month of year, range [1, 12]"},
385 {"tm_mday", "day of month, range [1, 31]"},
386 {"tm_hour", "hours, range [0, 23]"},
387 {"tm_min", "minutes, range [0, 59]"},
388 {"tm_sec", "seconds, range [0, 61])"},
389 {"tm_wday", "day of week, range [0, 6], Monday is 0"},
390 {"tm_yday", "day of year, range [1, 366]"},
391 {"tm_isdst", "1 if summer time is in effect, 0 if not, and -1 if unknown"},
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400392 {"tm_zone", "abbreviation of timezone name"},
393 {"tm_gmtoff", "offset from UTC in seconds"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000394 {0}
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000395};
396
397static PyStructSequence_Desc struct_time_type_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000398 "time.struct_time",
Alexander Belopolsky69f3fd02010-06-05 15:04:51 +0000399 "The time value as returned by gmtime(), localtime(), and strptime(), and\n"
400 " accepted by asctime(), mktime() and strftime(). May be considered as a\n"
401 " sequence of 9 integers.\n\n"
402 " Note that several fields' values are not the same as those defined by\n"
403 " the C language standard for struct tm. For example, the value of the\n"
404 " field tm_year is the actual year, not year - 1900. See individual\n"
405 " fields' descriptions for details.",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000406 struct_time_type_fields,
407 9,
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000408};
Tim Peters9ad4b682002-02-13 05:14:18 +0000409
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000410static int initialized;
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000411static PyTypeObject StructTimeType;
412
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400413
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000414static PyObject *
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -0400415tmtotuple(struct tm *p
416#ifndef HAVE_STRUCT_TM_TM_ZONE
Victor Stinner0d659e52017-04-25 01:22:42 +0200417 , const char *zone, time_t gmtoff
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -0400418#endif
419)
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000420{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000421 PyObject *v = PyStructSequence_New(&StructTimeType);
422 if (v == NULL)
423 return NULL;
Tim Peters9ad4b682002-02-13 05:14:18 +0000424
Christian Heimes217cfd12007-12-02 14:31:20 +0000425#define SET(i,val) PyStructSequence_SET_ITEM(v, i, PyLong_FromLong((long) val))
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000426
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000427 SET(0, p->tm_year + 1900);
428 SET(1, p->tm_mon + 1); /* Want January == 1 */
429 SET(2, p->tm_mday);
430 SET(3, p->tm_hour);
431 SET(4, p->tm_min);
432 SET(5, p->tm_sec);
433 SET(6, (p->tm_wday + 6) % 7); /* Want Monday == 0 */
434 SET(7, p->tm_yday + 1); /* Want January, 1 == 1 */
435 SET(8, p->tm_isdst);
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400436#ifdef HAVE_STRUCT_TM_TM_ZONE
437 PyStructSequence_SET_ITEM(v, 9,
Victor Stinner7ed7aea2018-01-15 10:45:49 +0100438 PyUnicode_DecodeLocale(p->tm_zone, "surrogateescape"));
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400439 SET(10, p->tm_gmtoff);
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -0400440#else
441 PyStructSequence_SET_ITEM(v, 9,
Victor Stinner7ed7aea2018-01-15 10:45:49 +0100442 PyUnicode_DecodeLocale(zone, "surrogateescape"));
Victor Stinner0d659e52017-04-25 01:22:42 +0200443 PyStructSequence_SET_ITEM(v, 10, _PyLong_FromTime_t(gmtoff));
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400444#endif /* HAVE_STRUCT_TM_TM_ZONE */
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000445#undef SET
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000446 if (PyErr_Occurred()) {
447 Py_XDECREF(v);
448 return NULL;
449 }
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000450
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000451 return v;
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000452}
453
Fred Drakef901abd2004-08-03 17:58:55 +0000454/* Parse arg tuple that can contain an optional float-or-None value;
455 format needs to be "|O:name".
456 Returns non-zero on success (parallels PyArg_ParseTuple).
457*/
458static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +0200459parse_time_t_args(PyObject *args, const char *format, time_t *pwhen)
Fred Drakef901abd2004-08-03 17:58:55 +0000460{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000461 PyObject *ot = NULL;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100462 time_t whent;
Fred Drakef901abd2004-08-03 17:58:55 +0000463
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000464 if (!PyArg_ParseTuple(args, format, &ot))
465 return 0;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100466 if (ot == NULL || ot == Py_None) {
467 whent = time(NULL);
468 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000469 else {
Victor Stinner02937aa2015-03-28 05:02:39 +0100470 if (_PyTime_ObjectToTime_t(ot, &whent, _PyTime_ROUND_FLOOR) == -1)
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100471 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000472 }
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100473 *pwhen = whent;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000474 return 1;
Fred Drakef901abd2004-08-03 17:58:55 +0000475}
476
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000477static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000478time_gmtime(PyObject *self, PyObject *args)
Guido van Rossum234f9421993-06-17 12:35:49 +0000479{
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100480 time_t when;
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -0400481 struct tm buf;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100482
483 if (!parse_time_t_args(args, "|O:gmtime", &when))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000484 return NULL;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100485
486 errno = 0;
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -0400487 if (_PyTime_gmtime(when, &buf) != 0)
488 return NULL;
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -0400489#ifdef HAVE_STRUCT_TM_TM_ZONE
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100490 return tmtotuple(&buf);
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -0400491#else
492 return tmtotuple(&buf, "UTC", 0);
493#endif
Guido van Rossum234f9421993-06-17 12:35:49 +0000494}
495
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -0400496#ifndef HAVE_TIMEGM
497static time_t
498timegm(struct tm *p)
499{
500 /* XXX: the following implementation will not work for tm_year < 1970.
501 but it is likely that platforms that don't have timegm do not support
502 negative timestamps anyways. */
503 return p->tm_sec + p->tm_min*60 + p->tm_hour*3600 + p->tm_yday*86400 +
504 (p->tm_year-70)*31536000 + ((p->tm_year-69)/4)*86400 -
505 ((p->tm_year-1)/100)*86400 + ((p->tm_year+299)/400)*86400;
506}
507#endif
508
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000509PyDoc_STRVAR(gmtime_doc,
Christian Heimes9a371592007-12-28 14:08:13 +0000510"gmtime([seconds]) -> (tm_year, tm_mon, tm_mday, tm_hour, tm_min,\n\
Fred Drake193a3f62002-03-12 21:38:49 +0000511 tm_sec, tm_wday, tm_yday, tm_isdst)\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000512\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000513Convert seconds since the Epoch to a time tuple expressing UTC (a.k.a.\n\
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400514GMT). When 'seconds' is not passed in, convert the current time instead.\n\
515\n\
516If the platform supports the tm_gmtoff and tm_zone, they are available as\n\
517attributes only.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000518
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000519static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000520time_localtime(PyObject *self, PyObject *args)
Guido van Rossum234f9421993-06-17 12:35:49 +0000521{
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100522 time_t when;
523 struct tm buf;
524
525 if (!parse_time_t_args(args, "|O:localtime", &when))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000526 return NULL;
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -0400527 if (_PyTime_localtime(when, &buf) != 0)
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100528 return NULL;
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -0400529#ifdef HAVE_STRUCT_TM_TM_ZONE
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100530 return tmtotuple(&buf);
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -0400531#else
532 {
533 struct tm local = buf;
534 char zone[100];
Victor Stinner0d659e52017-04-25 01:22:42 +0200535 time_t gmtoff;
Steve Dowerc3c6f712016-12-14 11:22:05 -0800536 strftime(zone, sizeof(zone), "%Z", &buf);
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -0400537 gmtoff = timegm(&buf) - when;
538 return tmtotuple(&local, zone, gmtoff);
539 }
540#endif
Guido van Rossum234f9421993-06-17 12:35:49 +0000541}
542
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000543PyDoc_STRVAR(localtime_doc,
Christian Heimes9a371592007-12-28 14:08:13 +0000544"localtime([seconds]) -> (tm_year,tm_mon,tm_mday,tm_hour,tm_min,\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000545 tm_sec,tm_wday,tm_yday,tm_isdst)\n\
Martin v. Löwisb3cfc1d2001-12-02 12:27:43 +0000546\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000547Convert seconds since the Epoch to a time tuple expressing local time.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000548When 'seconds' is not passed in, convert the current time instead.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000549
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000550/* Convert 9-item tuple to tm structure. Return 1 on success, set
551 * an exception and return 0 on error.
552 */
Guido van Rossum9e90a671993-06-24 11:10:19 +0000553static int
Oren Milman1d1d3e92017-08-20 18:35:36 +0300554gettmarg(PyObject *args, struct tm *p, const char *format)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000555{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000556 int y;
Guido van Rossumcfbaecc1998-08-25 14:51:12 +0000557
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000558 memset((void *) p, '\0', sizeof(struct tm));
Guido van Rossumb9081262007-08-25 03:14:09 +0000559
Alexander Belopolsky610e5442011-01-06 21:57:06 +0000560 if (!PyTuple_Check(args)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000561 PyErr_SetString(PyExc_TypeError,
562 "Tuple or struct_time argument required");
563 return 0;
564 }
Skip Montanaro41cfce92007-08-24 21:11:00 +0000565
Oren Milman1d1d3e92017-08-20 18:35:36 +0300566 if (!PyArg_ParseTuple(args, format,
Alexander Belopolsky610e5442011-01-06 21:57:06 +0000567 &y, &p->tm_mon, &p->tm_mday,
568 &p->tm_hour, &p->tm_min, &p->tm_sec,
569 &p->tm_wday, &p->tm_yday, &p->tm_isdst))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000570 return 0;
Miss Islington (bot)d5f017b2018-08-25 01:53:00 -0400571
572 if (y < INT_MIN + 1900) {
573 PyErr_SetString(PyExc_OverflowError, "year out of range");
574 return 0;
575 }
576
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000577 p->tm_year = y - 1900;
578 p->tm_mon--;
579 p->tm_wday = (p->tm_wday + 1) % 7;
580 p->tm_yday--;
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400581#ifdef HAVE_STRUCT_TM_TM_ZONE
582 if (Py_TYPE(args) == &StructTimeType) {
583 PyObject *item;
584 item = PyTuple_GET_ITEM(args, 9);
Victor Stinner6e676952017-04-26 13:51:48 +0200585 p->tm_zone = item == Py_None ? NULL : (char*)PyUnicode_AsUTF8(item);
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400586 item = PyTuple_GET_ITEM(args, 10);
587 p->tm_gmtoff = item == Py_None ? 0 : PyLong_AsLong(item);
588 if (PyErr_Occurred())
589 return 0;
590 }
591#endif /* HAVE_STRUCT_TM_TM_ZONE */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000592 return 1;
Guido van Rossum9e90a671993-06-24 11:10:19 +0000593}
594
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000595/* Check values of the struct tm fields before it is passed to strftime() and
596 * asctime(). Return 1 if all values are valid, otherwise set an exception
597 * and returns 0.
598 */
Victor Stinneref128102010-10-07 01:00:52 +0000599static int
600checktm(struct tm* buf)
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000601{
Victor Stinneref128102010-10-07 01:00:52 +0000602 /* Checks added to make sure strftime() and asctime() does not crash Python by
603 indexing blindly into some array for a textual representation
604 by some bad index (fixes bug #897625 and #6608).
605
606 Also support values of zero from Python code for arguments in which
607 that is out of range by forcing that value to the lowest value that
608 is valid (fixed bug #1520914).
609
610 Valid ranges based on what is allowed in struct tm:
611
612 - tm_year: [0, max(int)] (1)
613 - tm_mon: [0, 11] (2)
614 - tm_mday: [1, 31]
615 - tm_hour: [0, 23]
616 - tm_min: [0, 59]
617 - tm_sec: [0, 60]
618 - tm_wday: [0, 6] (1)
619 - tm_yday: [0, 365] (2)
620 - tm_isdst: [-max(int), max(int)]
621
622 (1) gettmarg() handles bounds-checking.
623 (2) Python's acceptable range is one greater than the range in C,
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000624 thus need to check against automatic decrement by gettmarg().
625 */
626 if (buf->tm_mon == -1)
627 buf->tm_mon = 0;
628 else if (buf->tm_mon < 0 || buf->tm_mon > 11) {
629 PyErr_SetString(PyExc_ValueError, "month out of range");
630 return 0;
631 }
632 if (buf->tm_mday == 0)
633 buf->tm_mday = 1;
634 else if (buf->tm_mday < 0 || buf->tm_mday > 31) {
635 PyErr_SetString(PyExc_ValueError, "day of month out of range");
636 return 0;
637 }
638 if (buf->tm_hour < 0 || buf->tm_hour > 23) {
639 PyErr_SetString(PyExc_ValueError, "hour out of range");
640 return 0;
641 }
642 if (buf->tm_min < 0 || buf->tm_min > 59) {
643 PyErr_SetString(PyExc_ValueError, "minute out of range");
644 return 0;
645 }
646 if (buf->tm_sec < 0 || buf->tm_sec > 61) {
647 PyErr_SetString(PyExc_ValueError, "seconds out of range");
648 return 0;
649 }
650 /* tm_wday does not need checking of its upper-bound since taking
651 ``% 7`` in gettmarg() automatically restricts the range. */
652 if (buf->tm_wday < 0) {
653 PyErr_SetString(PyExc_ValueError, "day of week out of range");
654 return 0;
655 }
656 if (buf->tm_yday == -1)
657 buf->tm_yday = 0;
658 else if (buf->tm_yday < 0 || buf->tm_yday > 365) {
659 PyErr_SetString(PyExc_ValueError, "day of year out of range");
660 return 0;
661 }
662 return 1;
663}
664
Victor Stinnerc1f32ca2011-10-14 02:36:13 +0200665#ifdef MS_WINDOWS
666 /* wcsftime() doesn't format correctly time zones, see issue #10653 */
667# undef HAVE_WCSFTIME
668#endif
Alexander Belopolskycf774542012-10-02 18:39:16 -0400669#define STRFTIME_FORMAT_CODES \
670"Commonly used format codes:\n\
671\n\
672%Y Year with century as a decimal number.\n\
673%m Month as a decimal number [01,12].\n\
674%d Day of the month as a decimal number [01,31].\n\
675%H Hour (24-hour clock) as a decimal number [00,23].\n\
676%M Minute as a decimal number [00,59].\n\
677%S Second as a decimal number [00,61].\n\
678%z Time zone offset from UTC.\n\
679%a Locale's abbreviated weekday name.\n\
680%A Locale's full weekday name.\n\
681%b Locale's abbreviated month name.\n\
682%B Locale's full month name.\n\
683%c Locale's appropriate date and time representation.\n\
684%I Hour (12-hour clock) as a decimal number [01,12].\n\
685%p Locale's equivalent of either AM or PM.\n\
686\n\
687Other codes may be available on your platform. See documentation for\n\
688the C library strftime function.\n"
Victor Stinnerc1f32ca2011-10-14 02:36:13 +0200689
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000690#ifdef HAVE_STRFTIME
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000691#ifdef HAVE_WCSFTIME
692#define time_char wchar_t
693#define format_time wcsftime
694#define time_strlen wcslen
695#else
696#define time_char char
697#define format_time strftime
698#define time_strlen strlen
699#endif
700
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000701static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000702time_strftime(PyObject *self, PyObject *args)
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000703{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000704 PyObject *tup = NULL;
705 struct tm buf;
706 const time_char *fmt;
Victor Stinnerb2904782010-09-29 10:34:19 +0000707#ifdef HAVE_WCSFTIME
708 wchar_t *format;
709#else
710 PyObject *format;
711#endif
Victor Stinneref128102010-10-07 01:00:52 +0000712 PyObject *format_arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000713 size_t fmtlen, buflen;
Victor Stinnerb2904782010-09-29 10:34:19 +0000714 time_char *outbuf = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000715 size_t i;
Victor Stinnerb2904782010-09-29 10:34:19 +0000716 PyObject *ret = NULL;
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000717
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000718 memset((void *) &buf, '\0', sizeof(buf));
Guido van Rossum1f41f841998-04-27 19:04:26 +0000719
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000720 /* Will always expect a unicode string to be passed as format.
721 Given that there's no str type anymore in py3k this seems safe.
722 */
Victor Stinneref128102010-10-07 01:00:52 +0000723 if (!PyArg_ParseTuple(args, "U|O:strftime", &format_arg, &tup))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000724 return NULL;
Thomas Woutersfe385252001-01-19 23:16:56 +0000725
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000726 if (tup == NULL) {
727 time_t tt = time(NULL);
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -0400728 if (_PyTime_localtime(tt, &buf) != 0)
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100729 return NULL;
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000730 }
Oren Milman1d1d3e92017-08-20 18:35:36 +0300731 else if (!gettmarg(tup, &buf,
732 "iiiiiiiii;strftime(): illegal time tuple argument") ||
733 !checktm(&buf))
734 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000735 return NULL;
Oren Milman1d1d3e92017-08-20 18:35:36 +0300736 }
Guido van Rossum10b164a2001-09-25 13:59:01 +0000737
Miss Islington (bot)d8234432018-12-30 18:39:00 -0800738#if defined(_MSC_VER) || (defined(__sun) && defined(__SVR4)) || defined(_AIX)
Victor Stinner73ea29c2011-01-08 01:56:31 +0000739 if (buf.tm_year + 1900 < 1 || 9999 < buf.tm_year + 1900) {
Victor Stinner6f0e4f92011-03-21 02:14:53 +0100740 PyErr_SetString(PyExc_ValueError,
741 "strftime() requires year in [1; 9999]");
Alexander Belopolsky0dd06f42011-01-08 01:23:02 +0000742 return NULL;
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000743 }
Victor Stinner73ea29c2011-01-08 01:56:31 +0000744#endif
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000745
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000746 /* Normalize tm_isdst just in case someone foolishly implements %Z
747 based on the assumption that tm_isdst falls within the range of
748 [-1, 1] */
749 if (buf.tm_isdst < -1)
750 buf.tm_isdst = -1;
751 else if (buf.tm_isdst > 1)
752 buf.tm_isdst = 1;
Brett Cannond1080a32004-03-02 04:38:10 +0000753
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000754#ifdef HAVE_WCSFTIME
Victor Stinnerbeb4135b2010-10-07 01:02:42 +0000755 format = PyUnicode_AsWideCharString(format_arg, NULL);
Victor Stinnerb2904782010-09-29 10:34:19 +0000756 if (format == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000757 return NULL;
Victor Stinnerb2904782010-09-29 10:34:19 +0000758 fmt = format;
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000759#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000760 /* Convert the unicode string to an ascii one */
Victor Stinner1b579672011-12-17 05:47:23 +0100761 format = PyUnicode_EncodeLocale(format_arg, "surrogateescape");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000762 if (format == NULL)
763 return NULL;
764 fmt = PyBytes_AS_STRING(format);
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000765#endif
Amaury Forgeot d'Arcb5be6d42009-03-02 23:52:57 +0000766
Stefan Krah4aea7d32012-02-27 16:30:26 +0100767#if defined(MS_WINDOWS) && !defined(HAVE_WCSFTIME)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000768 /* check that the format string contains only valid directives */
Steve Dowere5b58952015-09-06 19:20:51 -0700769 for (outbuf = strchr(fmt, '%');
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000770 outbuf != NULL;
Victor Stinner5a3ff792011-10-16 19:08:23 +0200771 outbuf = strchr(outbuf+2, '%'))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000772 {
Steve Dowere5b58952015-09-06 19:20:51 -0700773 if (outbuf[1] == '#')
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000774 ++outbuf; /* not documented by python, */
Steve Dowere5b58952015-09-06 19:20:51 -0700775 if (outbuf[1] == '\0')
776 break;
777 if ((outbuf[1] == 'y') && buf.tm_year < 0) {
Tim Golden6e51b8f2013-11-12 12:36:54 +0000778 PyErr_SetString(PyExc_ValueError,
779 "format %y requires year >= 1900 on Windows");
780 Py_DECREF(format);
781 return NULL;
782 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000783 }
Miss Islington (bot)d8234432018-12-30 18:39:00 -0800784#elif (defined(_AIX) || (defined(__sun) && defined(__SVR4))) && defined(HAVE_WCSFTIME)
Steve Dowere5b58952015-09-06 19:20:51 -0700785 for (outbuf = wcschr(fmt, '%');
Victor Stinner55329f82013-11-17 23:39:21 +0100786 outbuf != NULL;
787 outbuf = wcschr(outbuf+2, '%'))
788 {
Steve Dowere5b58952015-09-06 19:20:51 -0700789 if (outbuf[1] == L'\0')
790 break;
Victor Stinner55329f82013-11-17 23:39:21 +0100791 /* Issue #19634: On AIX, wcsftime("y", (1899, 1, 1, 0, 0, 0, 0, 0, 0))
792 returns "0/" instead of "99" */
793 if (outbuf[1] == L'y' && buf.tm_year < 0) {
794 PyErr_SetString(PyExc_ValueError,
795 "format %y requires year >= 1900 on AIX");
Miss Islington (bot)975f3cb2018-09-21 00:41:50 -0700796 PyMem_Free(format);
Victor Stinner55329f82013-11-17 23:39:21 +0100797 return NULL;
798 }
799 }
Amaury Forgeot d'Arcb5be6d42009-03-02 23:52:57 +0000800#endif
801
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000802 fmtlen = time_strlen(fmt);
Guido van Rossumc222ec21999-02-23 00:00:10 +0000803
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000804 /* I hate these functions that presume you know how big the output
805 * will be ahead of time...
806 */
807 for (i = 1024; ; i += i) {
808 outbuf = (time_char *)PyMem_Malloc(i*sizeof(time_char));
809 if (outbuf == NULL) {
Victor Stinnerb2904782010-09-29 10:34:19 +0000810 PyErr_NoMemory();
811 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000812 }
Steve Dower57ab1cd2015-09-22 14:51:42 -0700813#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
814 errno = 0;
815#endif
Steve Dowerd9ef74e2015-05-22 15:08:34 -0700816 _Py_BEGIN_SUPPRESS_IPH
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000817 buflen = format_time(outbuf, i, fmt, &buf);
Steve Dowerd9ef74e2015-05-22 15:08:34 -0700818 _Py_END_SUPPRESS_IPH
Victor Stinner136ea492011-12-17 22:37:18 +0100819#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
Steve Dower97cded92015-09-08 19:12:51 -0700820 /* VisualStudio .NET 2005 does this properly */
821 if (buflen == 0 && errno == EINVAL) {
822 PyErr_SetString(PyExc_ValueError, "Invalid format string");
823 PyMem_Free(outbuf);
824 break;
825 }
Victor Stinner136ea492011-12-17 22:37:18 +0100826#endif
Steve Dower97cded92015-09-08 19:12:51 -0700827 if (buflen > 0 || i >= 256 * fmtlen) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000828 /* If the buffer is 256 times as long as the format,
829 it's probably not failing for lack of room!
830 More likely, the format yields an empty result,
831 e.g. an empty format, or %Z when the timezone
832 is unknown. */
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000833#ifdef HAVE_WCSFTIME
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000834 ret = PyUnicode_FromWideChar(outbuf, buflen);
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000835#else
Victor Stinner7ed7aea2018-01-15 10:45:49 +0100836 ret = PyUnicode_DecodeLocaleAndSize(outbuf, buflen, "surrogateescape");
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000837#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000838 PyMem_Free(outbuf);
Victor Stinnerb2904782010-09-29 10:34:19 +0000839 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000840 }
841 PyMem_Free(outbuf);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000842 }
Victor Stinnerb2904782010-09-29 10:34:19 +0000843#ifdef HAVE_WCSFTIME
844 PyMem_Free(format);
845#else
846 Py_DECREF(format);
847#endif
848 return ret;
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000849}
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000850
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000851#undef time_char
852#undef format_time
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000853PyDoc_STRVAR(strftime_doc,
Thomas Woutersfe385252001-01-19 23:16:56 +0000854"strftime(format[, tuple]) -> string\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000855\n\
856Convert a time tuple to a string according to a format specification.\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000857See the library reference manual for formatting codes. When the time tuple\n\
Alexander Belopolskycf774542012-10-02 18:39:16 -0400858is not present, current time as returned by localtime() is used.\n\
859\n" STRFTIME_FORMAT_CODES);
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000860#endif /* HAVE_STRFTIME */
861
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000862static PyObject *
863time_strptime(PyObject *self, PyObject *args)
864{
Victor Stinnerdbe28d22016-12-09 00:38:53 +0100865 PyObject *module, *func, *result;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200866 _Py_IDENTIFIER(_strptime_time);
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000867
Victor Stinnerdbe28d22016-12-09 00:38:53 +0100868 module = PyImport_ImportModuleNoBlock("_strptime");
869 if (!module)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000870 return NULL;
Victor Stinnerdbe28d22016-12-09 00:38:53 +0100871
872 func = _PyObject_GetAttrId(module, &PyId__strptime_time);
873 Py_DECREF(module);
874 if (!func) {
875 return NULL;
876 }
877
878 result = PyObject_Call(func, args, NULL);
879 Py_DECREF(func);
880 return result;
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000881}
882
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000883
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000884PyDoc_STRVAR(strptime_doc,
Brett Cannon20def8b2003-07-01 05:16:08 +0000885"strptime(string, format) -> struct_time\n\
Martin v. Löwisb3cfc1d2001-12-02 12:27:43 +0000886\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000887Parse a string to a time tuple according to a format specification.\n\
Alexander Belopolskycf774542012-10-02 18:39:16 -0400888See the library reference manual for formatting codes (same as\n\
889strftime()).\n\
890\n" STRFTIME_FORMAT_CODES);
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000891
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000892static PyObject *
893_asctime(struct tm *timeptr)
894{
895 /* Inspired by Open Group reference implementation available at
896 * http://pubs.opengroup.org/onlinepubs/009695399/functions/asctime.html */
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200897 static const char wday_name[7][4] = {
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000898 "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
899 };
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200900 static const char mon_name[12][4] = {
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000901 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
902 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
903 };
Victor Stinner499dfcf2011-03-21 13:26:24 +0100904 return PyUnicode_FromFormat(
905 "%s %s%3d %.2d:%.2d:%.2d %d",
906 wday_name[timeptr->tm_wday],
907 mon_name[timeptr->tm_mon],
908 timeptr->tm_mday, timeptr->tm_hour,
909 timeptr->tm_min, timeptr->tm_sec,
910 1900 + timeptr->tm_year);
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000911}
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000912
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000913static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000914time_asctime(PyObject *self, PyObject *args)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000915{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000916 PyObject *tup = NULL;
917 struct tm buf;
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000918
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000919 if (!PyArg_UnpackTuple(args, "asctime", 0, 1, &tup))
920 return NULL;
921 if (tup == NULL) {
922 time_t tt = time(NULL);
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -0400923 if (_PyTime_localtime(tt, &buf) != 0)
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100924 return NULL;
Oren Milman1d1d3e92017-08-20 18:35:36 +0300925 }
926 else if (!gettmarg(tup, &buf,
927 "iiiiiiiii;asctime(): illegal time tuple argument") ||
928 !checktm(&buf))
929 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000930 return NULL;
Oren Milman1d1d3e92017-08-20 18:35:36 +0300931 }
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000932 return _asctime(&buf);
Guido van Rossum9e90a671993-06-24 11:10:19 +0000933}
934
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000935PyDoc_STRVAR(asctime_doc,
Thomas Woutersfe385252001-01-19 23:16:56 +0000936"asctime([tuple]) -> string\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000937\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000938Convert a time tuple to a string, e.g. 'Sat Jun 06 16:26:11 1998'.\n\
939When the time tuple is not present, current time as returned by localtime()\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000940is used.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000941
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000942static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000943time_ctime(PyObject *self, PyObject *args)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000944{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000945 time_t tt;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100946 struct tm buf;
947 if (!parse_time_t_args(args, "|O:ctime", &tt))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000948 return NULL;
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -0400949 if (_PyTime_localtime(tt, &buf) != 0)
Alexander Belopolsky5da468f2011-01-04 17:15:52 +0000950 return NULL;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100951 return _asctime(&buf);
Guido van Rossum9e90a671993-06-24 11:10:19 +0000952}
953
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000954PyDoc_STRVAR(ctime_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000955"ctime(seconds) -> string\n\
956\n\
957Convert a time in seconds since the Epoch to a string in local time.\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000958This is equivalent to asctime(localtime(seconds)). When the time tuple is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000959not present, current time as returned by localtime() is used.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000960
Guido van Rossum60cd8131998-03-06 17:16:21 +0000961#ifdef HAVE_MKTIME
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000962static PyObject *
Victor Stinner4195b5c2012-02-08 23:03:19 +0100963time_mktime(PyObject *self, PyObject *tup)
Guido van Rossum234f9421993-06-17 12:35:49 +0000964{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000965 struct tm buf;
966 time_t tt;
Oren Milman1d1d3e92017-08-20 18:35:36 +0300967 if (!gettmarg(tup, &buf,
968 "iiiiiiiii;mktime(): illegal time tuple argument"))
969 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000970 return NULL;
Oren Milman1d1d3e92017-08-20 18:35:36 +0300971 }
Victor Stinner1ac42612014-02-21 09:27:17 +0100972#ifdef _AIX
973 /* year < 1902 or year > 2037 */
974 if (buf.tm_year < 2 || buf.tm_year > 137) {
975 /* Issue #19748: On AIX, mktime() doesn't report overflow error for
976 * timestamp < -2^31 or timestamp > 2**31-1. */
977 PyErr_SetString(PyExc_OverflowError,
978 "mktime argument out of range");
979 return NULL;
980 }
981#else
Alexander Belopolskyb7d40d12011-01-11 01:21:25 +0000982 buf.tm_wday = -1; /* sentinel; original value ignored */
Victor Stinner1ac42612014-02-21 09:27:17 +0100983#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000984 tt = mktime(&buf);
Alexander Belopolskyb7d40d12011-01-11 01:21:25 +0000985 /* Return value of -1 does not necessarily mean an error, but tm_wday
Ezio Melotti13925002011-03-16 11:05:33 +0200986 * cannot remain set to -1 if mktime succeeded. */
Victor Stinner93037492013-06-25 22:54:35 +0200987 if (tt == (time_t)(-1)
988#ifndef _AIX
989 /* Return value of -1 does not necessarily mean an error, but
990 * tm_wday cannot remain set to -1 if mktime succeeded. */
991 && buf.tm_wday == -1
992#else
993 /* on AIX, tm_wday is always sets, even on error */
994#endif
995 )
996 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000997 PyErr_SetString(PyExc_OverflowError,
998 "mktime argument out of range");
999 return NULL;
1000 }
Victor Stinner4195b5c2012-02-08 23:03:19 +01001001 return PyFloat_FromDouble((double)tt);
Guido van Rossum234f9421993-06-17 12:35:49 +00001002}
Guido van Rossum0ef577b1998-06-27 20:38:36 +00001003
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001004PyDoc_STRVAR(mktime_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +00001005"mktime(tuple) -> floating point number\n\
1006\n\
Alexander Belopolskyc142bba2012-06-13 22:15:26 -04001007Convert a time tuple in local time to seconds since the Epoch.\n\
1008Note that mktime(gmtime(0)) will not generally return zero for most\n\
1009time zones; instead the returned value will either be equal to that\n\
1010of the timezone or altzone attributes on the time module.");
Guido van Rossum60cd8131998-03-06 17:16:21 +00001011#endif /* HAVE_MKTIME */
Guido van Rossum234f9421993-06-17 12:35:49 +00001012
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001013#ifdef HAVE_WORKING_TZSET
Victor Stinner5eb78c72018-12-04 00:09:02 +01001014static int init_timezone(PyObject *module);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001015
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001016static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001017time_tzset(PyObject *self, PyObject *unused)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001018{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001019 PyObject* m;
Fred Drake9bb74322002-04-01 14:49:59 +00001020
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001021 m = PyImport_ImportModuleNoBlock("time");
1022 if (m == NULL) {
1023 return NULL;
1024 }
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001025
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001026 tzset();
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 /* Reset timezone, altzone, daylight and tzname */
Victor Stinner5eb78c72018-12-04 00:09:02 +01001029 if (init_timezone(m) < 0) {
Victor Stinner38c06d92018-12-01 01:24:21 +01001030 return NULL;
1031 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001032 Py_DECREF(m);
Victor Stinner2ff51b82013-07-17 21:42:45 +02001033 if (PyErr_Occurred())
1034 return NULL;
Tim Peters1b6f7a92004-06-20 02:50:16 +00001035
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001036 Py_RETURN_NONE;
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001037}
1038
1039PyDoc_STRVAR(tzset_doc,
R. David Murray4d55bf92010-12-14 00:55:46 +00001040"tzset()\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001041\n\
1042Initialize, or reinitialize, the local timezone to the value stored in\n\
1043os.environ['TZ']. The TZ environment variable should be specified in\n\
Neal Norwitzdc8e1942004-07-20 22:34:37 +00001044standard Unix timezone format as documented in the tzset man page\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001045(eg. 'US/Eastern', 'Europe/Amsterdam'). Unknown timezones will silently\n\
1046fall back to UTC. If the TZ environment variable is not set, the local\n\
1047timezone is set to the systems best guess of wallclock time.\n\
1048Changing the TZ environment variable without calling tzset *may* change\n\
1049the local timezone used by methods such as localtime, but this behaviour\n\
1050should not be relied on.");
1051#endif /* HAVE_WORKING_TZSET */
1052
Victor Stinnerae586492014-09-02 23:18:25 +02001053static PyObject *
Victor Stinnerec895392012-04-29 02:41:27 +02001054time_monotonic(PyObject *self, PyObject *unused)
Victor Stinner071eca32012-03-15 01:17:09 +01001055{
Victor Stinnerc29b5852017-11-02 07:28:27 -07001056 _PyTime_t t = _PyTime_GetMonotonicClock();
1057 return _PyFloat_FromPyTime(t);
Victor Stinner071eca32012-03-15 01:17:09 +01001058}
1059
Victor Stinnerec895392012-04-29 02:41:27 +02001060PyDoc_STRVAR(monotonic_doc,
1061"monotonic() -> float\n\
Victor Stinner8b302012012-02-07 23:29:46 +01001062\n\
Victor Stinnerec895392012-04-29 02:41:27 +02001063Monotonic clock, cannot go backward.");
Victor Stinnerec919cc2012-03-15 00:58:32 +01001064
Victor Stinnerec895392012-04-29 02:41:27 +02001065static PyObject *
Victor Stinnerc29b5852017-11-02 07:28:27 -07001066time_monotonic_ns(PyObject *self, PyObject *unused)
1067{
1068 _PyTime_t t = _PyTime_GetMonotonicClock();
1069 return _PyTime_AsNanosecondsObject(t);
1070}
1071
1072PyDoc_STRVAR(monotonic_ns_doc,
1073"monotonic_ns() -> int\n\
1074\n\
1075Monotonic clock, cannot go backward, as nanoseconds.");
1076
1077static PyObject *
Victor Stinnerec895392012-04-29 02:41:27 +02001078time_perf_counter(PyObject *self, PyObject *unused)
1079{
1080 return perf_counter(NULL);
1081}
1082
1083PyDoc_STRVAR(perf_counter_doc,
1084"perf_counter() -> float\n\
1085\n\
1086Performance counter for benchmarking.");
1087
Victor Stinnerc29b5852017-11-02 07:28:27 -07001088static PyObject *
1089time_perf_counter_ns(PyObject *self, PyObject *unused)
1090{
1091 _PyTime_t t = _PyTime_GetPerfCounter();
1092 return _PyTime_AsNanosecondsObject(t);
1093}
1094
1095PyDoc_STRVAR(perf_counter_ns_doc,
1096"perf_counter_ns() -> int\n\
1097\n\
1098Performance counter for benchmarking as nanoseconds.");
1099
1100static int
1101_PyTime_GetProcessTimeWithInfo(_PyTime_t *tp, _Py_clock_info_t *info)
Victor Stinnerec895392012-04-29 02:41:27 +02001102{
1103#if defined(MS_WINDOWS)
1104 HANDLE process;
1105 FILETIME creation_time, exit_time, kernel_time, user_time;
1106 ULARGE_INTEGER large;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001107 _PyTime_t ktime, utime, t;
Victor Stinnerec895392012-04-29 02:41:27 +02001108 BOOL ok;
1109
1110 process = GetCurrentProcess();
Victor Stinnerc29b5852017-11-02 07:28:27 -07001111 ok = GetProcessTimes(process, &creation_time, &exit_time,
1112 &kernel_time, &user_time);
1113 if (!ok) {
1114 PyErr_SetFromWindowsErr(0);
1115 return -1;
1116 }
Victor Stinnerec895392012-04-29 02:41:27 +02001117
Victor Stinnerec895392012-04-29 02:41:27 +02001118 if (info) {
1119 info->implementation = "GetProcessTimes()";
1120 info->resolution = 1e-7;
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001121 info->monotonic = 1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001122 info->adjustable = 0;
Victor Stinnerec895392012-04-29 02:41:27 +02001123 }
Victor Stinnerc29b5852017-11-02 07:28:27 -07001124
1125 large.u.LowPart = kernel_time.dwLowDateTime;
1126 large.u.HighPart = kernel_time.dwHighDateTime;
1127 ktime = large.QuadPart;
1128
1129 large.u.LowPart = user_time.dwLowDateTime;
1130 large.u.HighPart = user_time.dwHighDateTime;
1131 utime = large.QuadPart;
1132
1133 /* ktime and utime have a resolution of 100 nanoseconds */
1134 t = _PyTime_FromNanoseconds((ktime + utime) * 100);
1135 *tp = t;
1136 return 0;
Victor Stinnerec895392012-04-29 02:41:27 +02001137#else
1138
Victor Stinnerc29b5852017-11-02 07:28:27 -07001139 /* clock_gettime */
Victor Stinnerec895392012-04-29 02:41:27 +02001140#if defined(HAVE_CLOCK_GETTIME) \
1141 && (defined(CLOCK_PROCESS_CPUTIME_ID) || defined(CLOCK_PROF))
Victor Stinnerc29b5852017-11-02 07:28:27 -07001142 struct timespec ts;
Victor Stinnerec895392012-04-29 02:41:27 +02001143#ifdef CLOCK_PROF
1144 const clockid_t clk_id = CLOCK_PROF;
1145 const char *function = "clock_gettime(CLOCK_PROF)";
1146#else
1147 const clockid_t clk_id = CLOCK_PROCESS_CPUTIME_ID;
1148 const char *function = "clock_gettime(CLOCK_PROCESS_CPUTIME_ID)";
1149#endif
1150
Victor Stinnerc29b5852017-11-02 07:28:27 -07001151 if (clock_gettime(clk_id, &ts) == 0) {
Victor Stinnerec895392012-04-29 02:41:27 +02001152 if (info) {
1153 struct timespec res;
1154 info->implementation = function;
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001155 info->monotonic = 1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001156 info->adjustable = 0;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001157 if (clock_getres(clk_id, &res)) {
1158 PyErr_SetFromErrno(PyExc_OSError);
1159 return -1;
1160 }
1161 info->resolution = res.tv_sec + res.tv_nsec * 1e-9;
Victor Stinnerec895392012-04-29 02:41:27 +02001162 }
Victor Stinnerc29b5852017-11-02 07:28:27 -07001163
1164 if (_PyTime_FromTimespec(tp, &ts) < 0) {
1165 return -1;
1166 }
1167 return 0;
Victor Stinnerec895392012-04-29 02:41:27 +02001168 }
1169#endif
1170
Victor Stinnerc29b5852017-11-02 07:28:27 -07001171 /* getrusage(RUSAGE_SELF) */
Victor Stinnerec895392012-04-29 02:41:27 +02001172#if defined(HAVE_SYS_RESOURCE_H)
Victor Stinnerc29b5852017-11-02 07:28:27 -07001173 struct rusage ru;
1174
Victor Stinnerec895392012-04-29 02:41:27 +02001175 if (getrusage(RUSAGE_SELF, &ru) == 0) {
Victor Stinnerc29b5852017-11-02 07:28:27 -07001176 _PyTime_t utime, stime;
1177
Victor Stinnerec895392012-04-29 02:41:27 +02001178 if (info) {
1179 info->implementation = "getrusage(RUSAGE_SELF)";
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001180 info->monotonic = 1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001181 info->adjustable = 0;
Victor Stinnerec895392012-04-29 02:41:27 +02001182 info->resolution = 1e-6;
1183 }
Victor Stinnerc29b5852017-11-02 07:28:27 -07001184
1185 if (_PyTime_FromTimeval(&utime, &ru.ru_utime) < 0) {
1186 return -1;
1187 }
1188 if (_PyTime_FromTimeval(&stime, &ru.ru_stime) < 0) {
1189 return -1;
1190 }
1191
1192 _PyTime_t total = utime + utime;
1193 *tp = total;
1194 return 0;
Victor Stinnerec895392012-04-29 02:41:27 +02001195 }
1196#endif
1197
Victor Stinnerc29b5852017-11-02 07:28:27 -07001198 /* times() */
Victor Stinnerec895392012-04-29 02:41:27 +02001199#ifdef HAVE_TIMES
Victor Stinnerc29b5852017-11-02 07:28:27 -07001200 struct tms t;
1201
Victor Stinnerec895392012-04-29 02:41:27 +02001202 if (times(&t) != (clock_t)-1) {
Victor Stinnerc29b5852017-11-02 07:28:27 -07001203 static long ticks_per_second = -1;
Victor Stinnerec895392012-04-29 02:41:27 +02001204
1205 if (ticks_per_second == -1) {
Victor Stinnerc29b5852017-11-02 07:28:27 -07001206 long freq;
Victor Stinnerec895392012-04-29 02:41:27 +02001207#if defined(HAVE_SYSCONF) && defined(_SC_CLK_TCK)
Victor Stinnerc29b5852017-11-02 07:28:27 -07001208 freq = sysconf(_SC_CLK_TCK);
1209 if (freq < 1) {
1210 freq = -1;
1211 }
Victor Stinnerec895392012-04-29 02:41:27 +02001212#elif defined(HZ)
Victor Stinnerc29b5852017-11-02 07:28:27 -07001213 freq = HZ;
Victor Stinnerec895392012-04-29 02:41:27 +02001214#else
Victor Stinnerc29b5852017-11-02 07:28:27 -07001215 freq = 60; /* magic fallback value; may be bogus */
Victor Stinnerec895392012-04-29 02:41:27 +02001216#endif
Victor Stinnerc29b5852017-11-02 07:28:27 -07001217
1218 if (freq != -1) {
1219 /* check that _PyTime_MulDiv(t, SEC_TO_NS, ticks_per_second)
1220 cannot overflow below */
Miss Islington (bot)7df80492018-02-09 07:56:34 -08001221#if LONG_MAX > _PyTime_MAX / SEC_TO_NS
Victor Stinnerc29b5852017-11-02 07:28:27 -07001222 if ((_PyTime_t)freq > _PyTime_MAX / SEC_TO_NS) {
1223 PyErr_SetString(PyExc_OverflowError,
1224 "_SC_CLK_TCK is too large");
1225 return -1;
1226 }
Miss Islington (bot)7df80492018-02-09 07:56:34 -08001227#endif
Victor Stinnerc29b5852017-11-02 07:28:27 -07001228
1229 ticks_per_second = freq;
1230 }
Victor Stinnerec895392012-04-29 02:41:27 +02001231 }
1232
1233 if (ticks_per_second != -1) {
Victor Stinnerec895392012-04-29 02:41:27 +02001234 if (info) {
1235 info->implementation = "times()";
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001236 info->monotonic = 1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001237 info->adjustable = 0;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001238 info->resolution = 1.0 / (double)ticks_per_second;
Victor Stinnerec895392012-04-29 02:41:27 +02001239 }
Victor Stinnerc29b5852017-11-02 07:28:27 -07001240
1241 _PyTime_t total;
1242 total = _PyTime_MulDiv(t.tms_utime, SEC_TO_NS, ticks_per_second);
1243 total += _PyTime_MulDiv(t.tms_stime, SEC_TO_NS, ticks_per_second);
1244 *tp = total;
1245 return 0;
Victor Stinnerec895392012-04-29 02:41:27 +02001246 }
1247 }
1248#endif
1249
Victor Stinnerc29b5852017-11-02 07:28:27 -07001250 /* clock */
Victor Stinner53e22bf2016-07-08 17:55:01 +02001251 /* Currently, Python 3 requires clock() to build: see issue #22624 */
Victor Stinnerc29b5852017-11-02 07:28:27 -07001252 return _PyTime_GetClockWithInfo(tp, info);
Victor Stinnerec895392012-04-29 02:41:27 +02001253#endif
1254}
1255
1256static PyObject *
1257time_process_time(PyObject *self, PyObject *unused)
1258{
Victor Stinnerc29b5852017-11-02 07:28:27 -07001259 _PyTime_t t;
1260 if (_PyTime_GetProcessTimeWithInfo(&t, NULL) < 0) {
1261 return NULL;
1262 }
1263 return _PyFloat_FromPyTime(t);
Victor Stinnerec895392012-04-29 02:41:27 +02001264}
1265
1266PyDoc_STRVAR(process_time_doc,
1267"process_time() -> float\n\
1268\n\
1269Process time for profiling: sum of the kernel and user-space CPU time.");
1270
Victor Stinnerc29b5852017-11-02 07:28:27 -07001271static PyObject *
1272time_process_time_ns(PyObject *self, PyObject *unused)
1273{
1274 _PyTime_t t;
1275 if (_PyTime_GetProcessTimeWithInfo(&t, NULL) < 0) {
1276 return NULL;
1277 }
1278 return _PyTime_AsNanosecondsObject(t);
1279}
1280
1281PyDoc_STRVAR(process_time_ns_doc,
1282"process_time() -> int\n\
1283\n\
1284Process time for profiling as nanoseconds:\n\
1285sum of the kernel and user-space CPU time.");
1286
Victor Stinnerec895392012-04-29 02:41:27 +02001287
Antoine Pitrou4bd41c92017-11-15 22:52:21 +01001288#if defined(MS_WINDOWS)
1289#define HAVE_THREAD_TIME
1290static int
1291_PyTime_GetThreadTimeWithInfo(_PyTime_t *tp, _Py_clock_info_t *info)
1292{
1293 HANDLE thread;
1294 FILETIME creation_time, exit_time, kernel_time, user_time;
1295 ULARGE_INTEGER large;
1296 _PyTime_t ktime, utime, t;
1297 BOOL ok;
1298
1299 thread = GetCurrentThread();
1300 ok = GetThreadTimes(thread, &creation_time, &exit_time,
1301 &kernel_time, &user_time);
1302 if (!ok) {
1303 PyErr_SetFromWindowsErr(0);
1304 return -1;
1305 }
1306
1307 if (info) {
1308 info->implementation = "GetThreadTimes()";
1309 info->resolution = 1e-7;
1310 info->monotonic = 1;
1311 info->adjustable = 0;
1312 }
1313
1314 large.u.LowPart = kernel_time.dwLowDateTime;
1315 large.u.HighPart = kernel_time.dwHighDateTime;
1316 ktime = large.QuadPart;
1317
1318 large.u.LowPart = user_time.dwLowDateTime;
1319 large.u.HighPart = user_time.dwHighDateTime;
1320 utime = large.QuadPart;
1321
1322 /* ktime and utime have a resolution of 100 nanoseconds */
1323 t = _PyTime_FromNanoseconds((ktime + utime) * 100);
1324 *tp = t;
1325 return 0;
1326}
1327
1328#elif defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_PROCESS_CPUTIME_ID)
1329#define HAVE_THREAD_TIME
1330static int
1331_PyTime_GetThreadTimeWithInfo(_PyTime_t *tp, _Py_clock_info_t *info)
1332{
1333 struct timespec ts;
1334 const clockid_t clk_id = CLOCK_THREAD_CPUTIME_ID;
1335 const char *function = "clock_gettime(CLOCK_THREAD_CPUTIME_ID)";
1336
1337 if (clock_gettime(clk_id, &ts)) {
1338 PyErr_SetFromErrno(PyExc_OSError);
1339 return -1;
1340 }
1341 if (info) {
1342 struct timespec res;
1343 info->implementation = function;
1344 info->monotonic = 1;
1345 info->adjustable = 0;
1346 if (clock_getres(clk_id, &res)) {
1347 PyErr_SetFromErrno(PyExc_OSError);
1348 return -1;
1349 }
1350 info->resolution = res.tv_sec + res.tv_nsec * 1e-9;
1351 }
1352
1353 if (_PyTime_FromTimespec(tp, &ts) < 0) {
1354 return -1;
1355 }
1356 return 0;
1357}
1358#endif
1359
1360#ifdef HAVE_THREAD_TIME
1361static PyObject *
1362time_thread_time(PyObject *self, PyObject *unused)
1363{
1364 _PyTime_t t;
1365 if (_PyTime_GetThreadTimeWithInfo(&t, NULL) < 0) {
1366 return NULL;
1367 }
1368 return _PyFloat_FromPyTime(t);
1369}
1370
1371PyDoc_STRVAR(thread_time_doc,
1372"thread_time() -> float\n\
1373\n\
1374Thread time for profiling: sum of the kernel and user-space CPU time.");
1375
1376static PyObject *
1377time_thread_time_ns(PyObject *self, PyObject *unused)
1378{
1379 _PyTime_t t;
1380 if (_PyTime_GetThreadTimeWithInfo(&t, NULL) < 0) {
1381 return NULL;
1382 }
1383 return _PyTime_AsNanosecondsObject(t);
1384}
1385
1386PyDoc_STRVAR(thread_time_ns_doc,
1387"thread_time() -> int\n\
1388\n\
1389Thread time for profiling as nanoseconds:\n\
1390sum of the kernel and user-space CPU time.");
1391#endif
1392
1393
Victor Stinnerec895392012-04-29 02:41:27 +02001394static PyObject *
1395time_get_clock_info(PyObject *self, PyObject *args)
1396{
1397 char *name;
Victor Stinnerec895392012-04-29 02:41:27 +02001398 _Py_clock_info_t info;
Victor Stinnerbda4b882012-06-12 22:11:44 +02001399 PyObject *obj = NULL, *dict, *ns;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001400 _PyTime_t t;
Victor Stinnerec895392012-04-29 02:41:27 +02001401
Victor Stinnerc29b5852017-11-02 07:28:27 -07001402 if (!PyArg_ParseTuple(args, "s:get_clock_info", &name)) {
Victor Stinnerec895392012-04-29 02:41:27 +02001403 return NULL;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001404 }
Victor Stinnerec895392012-04-29 02:41:27 +02001405
1406#ifdef Py_DEBUG
1407 info.implementation = NULL;
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001408 info.monotonic = -1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001409 info.adjustable = -1;
Victor Stinnerec895392012-04-29 02:41:27 +02001410 info.resolution = -1.0;
1411#else
1412 info.implementation = "";
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001413 info.monotonic = 0;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001414 info.adjustable = 0;
Victor Stinnerec895392012-04-29 02:41:27 +02001415 info.resolution = 1.0;
1416#endif
1417
Victor Stinnerc29b5852017-11-02 07:28:27 -07001418 if (strcmp(name, "time") == 0) {
1419 if (_PyTime_GetSystemClockWithInfo(&t, &info) < 0) {
1420 return NULL;
1421 }
1422 }
Victor Stinnerec895392012-04-29 02:41:27 +02001423#ifdef PYCLOCK
Victor Stinnerc29b5852017-11-02 07:28:27 -07001424 else if (strcmp(name, "clock") == 0) {
Victor Stinnerec895392012-04-29 02:41:27 +02001425 obj = pyclock(&info);
Victor Stinnerc29b5852017-11-02 07:28:27 -07001426 if (obj == NULL) {
1427 return NULL;
1428 }
1429 Py_DECREF(obj);
1430 }
Victor Stinnerec895392012-04-29 02:41:27 +02001431#endif
Victor Stinnerc29b5852017-11-02 07:28:27 -07001432 else if (strcmp(name, "monotonic") == 0) {
1433 if (_PyTime_GetMonotonicClockWithInfo(&t, &info) < 0) {
1434 return NULL;
1435 }
1436 }
1437 else if (strcmp(name, "perf_counter") == 0) {
1438 if (_PyTime_GetPerfCounterWithInfo(&t, &info) < 0) {
1439 return NULL;
1440 }
1441 }
1442 else if (strcmp(name, "process_time") == 0) {
1443 if (_PyTime_GetProcessTimeWithInfo(&t, &info) < 0) {
1444 return NULL;
1445 }
1446 }
Antoine Pitrou4bd41c92017-11-15 22:52:21 +01001447#ifdef HAVE_THREAD_TIME
1448 else if (strcmp(name, "thread_time") == 0) {
1449 if (_PyTime_GetThreadTimeWithInfo(&t, &info) < 0) {
1450 return NULL;
1451 }
1452 }
1453#endif
Victor Stinnerec895392012-04-29 02:41:27 +02001454 else {
1455 PyErr_SetString(PyExc_ValueError, "unknown clock");
1456 return NULL;
1457 }
Victor Stinnerec895392012-04-29 02:41:27 +02001458
Victor Stinnerbda4b882012-06-12 22:11:44 +02001459 dict = PyDict_New();
Victor Stinnerc29b5852017-11-02 07:28:27 -07001460 if (dict == NULL) {
Victor Stinnerec895392012-04-29 02:41:27 +02001461 return NULL;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001462 }
Victor Stinnerec895392012-04-29 02:41:27 +02001463
1464 assert(info.implementation != NULL);
1465 obj = PyUnicode_FromString(info.implementation);
Victor Stinnerc29b5852017-11-02 07:28:27 -07001466 if (obj == NULL) {
Victor Stinnerec895392012-04-29 02:41:27 +02001467 goto error;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001468 }
1469 if (PyDict_SetItemString(dict, "implementation", obj) == -1) {
Victor Stinnerbda4b882012-06-12 22:11:44 +02001470 goto error;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001471 }
Victor Stinnerbda4b882012-06-12 22:11:44 +02001472 Py_CLEAR(obj);
Victor Stinnerec895392012-04-29 02:41:27 +02001473
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001474 assert(info.monotonic != -1);
1475 obj = PyBool_FromLong(info.monotonic);
Victor Stinnerc29b5852017-11-02 07:28:27 -07001476 if (obj == NULL) {
Victor Stinnerec895392012-04-29 02:41:27 +02001477 goto error;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001478 }
1479 if (PyDict_SetItemString(dict, "monotonic", obj) == -1) {
Victor Stinnerbda4b882012-06-12 22:11:44 +02001480 goto error;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001481 }
Victor Stinnerbda4b882012-06-12 22:11:44 +02001482 Py_CLEAR(obj);
Victor Stinnerec895392012-04-29 02:41:27 +02001483
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001484 assert(info.adjustable != -1);
1485 obj = PyBool_FromLong(info.adjustable);
Victor Stinnerc29b5852017-11-02 07:28:27 -07001486 if (obj == NULL) {
Victor Stinnerec895392012-04-29 02:41:27 +02001487 goto error;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001488 }
1489 if (PyDict_SetItemString(dict, "adjustable", obj) == -1) {
Victor Stinnerbda4b882012-06-12 22:11:44 +02001490 goto error;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001491 }
Victor Stinnerbda4b882012-06-12 22:11:44 +02001492 Py_CLEAR(obj);
Victor Stinnerec895392012-04-29 02:41:27 +02001493
1494 assert(info.resolution > 0.0);
1495 assert(info.resolution <= 1.0);
1496 obj = PyFloat_FromDouble(info.resolution);
Victor Stinnerc29b5852017-11-02 07:28:27 -07001497 if (obj == NULL) {
Victor Stinnerec895392012-04-29 02:41:27 +02001498 goto error;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001499 }
1500 if (PyDict_SetItemString(dict, "resolution", obj) == -1) {
Victor Stinnerbda4b882012-06-12 22:11:44 +02001501 goto error;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001502 }
Victor Stinnerbda4b882012-06-12 22:11:44 +02001503 Py_CLEAR(obj);
Victor Stinnerec895392012-04-29 02:41:27 +02001504
Victor Stinnerbda4b882012-06-12 22:11:44 +02001505 ns = _PyNamespace_New(dict);
1506 Py_DECREF(dict);
1507 return ns;
Victor Stinnerec895392012-04-29 02:41:27 +02001508
1509error:
Victor Stinnerbda4b882012-06-12 22:11:44 +02001510 Py_DECREF(dict);
1511 Py_XDECREF(obj);
Victor Stinnerec895392012-04-29 02:41:27 +02001512 return NULL;
1513}
1514
1515PyDoc_STRVAR(get_clock_info_doc,
1516"get_clock_info(name: str) -> dict\n\
1517\n\
1518Get information of the specified clock.");
Victor Stinner8b302012012-02-07 23:29:46 +01001519
Victor Stinner8f5cdfa2017-04-20 13:41:09 +02001520#if !defined(HAVE_TZNAME) || defined(__GLIBC__) || defined(__CYGWIN__)
Martin v. Löwisd218dc12008-04-07 03:17:54 +00001521static void
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -04001522get_zone(char *zone, int n, struct tm *p)
1523{
1524#ifdef HAVE_STRUCT_TM_TM_ZONE
1525 strncpy(zone, p->tm_zone ? p->tm_zone : " ", n);
1526#else
1527 tzset();
1528 strftime(zone, n, "%Z", p);
1529#endif
1530}
1531
Victor Stinner38c06d92018-12-01 01:24:21 +01001532static time_t
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -04001533get_gmtoff(time_t t, struct tm *p)
1534{
1535#ifdef HAVE_STRUCT_TM_TM_ZONE
1536 return p->tm_gmtoff;
1537#else
1538 return timegm(p) - t;
1539#endif
1540}
Victor Stinner8f5cdfa2017-04-20 13:41:09 +02001541#endif /* !defined(HAVE_TZNAME) || defined(__GLIBC__) || defined(__CYGWIN__) */
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -04001542
Victor Stinner38c06d92018-12-01 01:24:21 +01001543static int
Victor Stinner5eb78c72018-12-04 00:09:02 +01001544init_timezone(PyObject *m)
Victor Stinner38c06d92018-12-01 01:24:21 +01001545{
1546 assert(!PyErr_Occurred());
1547
Martin v. Löwis1a214512008-06-11 05:26:20 +00001548 /* This code moved from PyInit_time wholesale to allow calling it from
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001549 time_tzset. In the future, some parts of it can be moved back
1550 (for platforms that don't HAVE_WORKING_TZSET, when we know what they
1551 are), and the extraneous calls to tzset(3) should be removed.
1552 I haven't done this yet, as I don't want to change this code as
1553 little as possible when introducing the time.tzset and time.tzsetwall
1554 methods. This should simply be a method of doing the following once,
1555 at the top of this function and removing the call to tzset() from
1556 time_tzset():
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001557
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001558 #ifdef HAVE_TZSET
1559 tzset()
1560 #endif
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001562 And I'm lazy and hate C so nyer.
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001563 */
Guido van Rossum10b164a2001-09-25 13:59:01 +00001564#if defined(HAVE_TZNAME) && !defined(__GLIBC__) && !defined(__CYGWIN__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001565 PyObject *otz0, *otz1;
1566 tzset();
Miss Islington (bot)0b3019a2019-02-25 16:15:04 -08001567 PyModule_AddIntConstant(m, "timezone", _Py_timezone);
Guido van Rossumb6775db1994-08-01 11:34:53 +00001568#ifdef HAVE_ALTZONE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001569 PyModule_AddIntConstant(m, "altzone", altzone);
Guido van Rossumb6775db1994-08-01 11:34:53 +00001570#else
Miss Islington (bot)0b3019a2019-02-25 16:15:04 -08001571 PyModule_AddIntConstant(m, "altzone", _Py_timezone-3600);
Guido van Rossumb6775db1994-08-01 11:34:53 +00001572#endif
Miss Islington (bot)0b3019a2019-02-25 16:15:04 -08001573 PyModule_AddIntConstant(m, "daylight", _Py_daylight);
1574 otz0 = PyUnicode_DecodeLocale(_Py_tzname[0], "surrogateescape");
Victor Stinner5eb78c72018-12-04 00:09:02 +01001575 if (otz0 == NULL) {
1576 return -1;
1577 }
Miss Islington (bot)0b3019a2019-02-25 16:15:04 -08001578 otz1 = PyUnicode_DecodeLocale(_Py_tzname[1], "surrogateescape");
Victor Stinner5eb78c72018-12-04 00:09:02 +01001579 if (otz1 == NULL) {
1580 Py_DECREF(otz0);
1581 return -1;
1582 }
1583 PyObject *tzname_obj = Py_BuildValue("(NN)", otz0, otz1);
1584 if (tzname_obj == NULL) {
1585 return -1;
1586 }
1587 PyModule_AddObject(m, "tzname", tzname_obj);
Guido van Rossum10b164a2001-09-25 13:59:01 +00001588#else /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001589 {
Guido van Rossum234f9421993-06-17 12:35:49 +00001590#define YEAR ((time_t)((365 * 24 + 6) * 3600))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001591 time_t t;
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -04001592 struct tm p;
Victor Stinner38c06d92018-12-01 01:24:21 +01001593 time_t janzone_t, julyzone_t;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001594 char janname[10], julyname[10];
1595 t = (time((time_t *)0) / YEAR) * YEAR;
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -04001596 _PyTime_localtime(t, &p);
1597 get_zone(janname, 9, &p);
Victor Stinner38c06d92018-12-01 01:24:21 +01001598 janzone_t = -get_gmtoff(t, &p);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001599 janname[9] = '\0';
1600 t += YEAR/2;
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -04001601 _PyTime_localtime(t, &p);
1602 get_zone(julyname, 9, &p);
Victor Stinner38c06d92018-12-01 01:24:21 +01001603 julyzone_t = -get_gmtoff(t, &p);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001604 julyname[9] = '\0';
Guido van Rossum10b164a2001-09-25 13:59:01 +00001605
Victor Stinner38c06d92018-12-01 01:24:21 +01001606 /* Sanity check, don't check for the validity of timezones.
1607 In practice, it should be more in range -12 hours .. +14 hours. */
1608#define MAX_TIMEZONE (48 * 3600)
1609 if (janzone_t < -MAX_TIMEZONE || janzone_t > MAX_TIMEZONE
1610 || julyzone_t < -MAX_TIMEZONE || julyzone_t > MAX_TIMEZONE)
1611 {
1612 PyErr_SetString(PyExc_RuntimeError, "invalid GMT offset");
1613 return -1;
1614 }
1615 int janzone = (int)janzone_t;
1616 int julyzone = (int)julyzone_t;
1617
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001618 if( janzone < julyzone ) {
1619 /* DST is reversed in the southern hemisphere */
1620 PyModule_AddIntConstant(m, "timezone", julyzone);
1621 PyModule_AddIntConstant(m, "altzone", janzone);
1622 PyModule_AddIntConstant(m, "daylight",
1623 janzone != julyzone);
1624 PyModule_AddObject(m, "tzname",
1625 Py_BuildValue("(zz)",
1626 julyname, janname));
1627 } else {
1628 PyModule_AddIntConstant(m, "timezone", janzone);
1629 PyModule_AddIntConstant(m, "altzone", julyzone);
1630 PyModule_AddIntConstant(m, "daylight",
1631 janzone != julyzone);
1632 PyModule_AddObject(m, "tzname",
1633 Py_BuildValue("(zz)",
1634 janname, julyname));
1635 }
1636 }
Tim Peters26ae7cd2001-03-20 03:26:49 +00001637#ifdef __CYGWIN__
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001638 tzset();
1639 PyModule_AddIntConstant(m, "timezone", _timezone);
1640 PyModule_AddIntConstant(m, "altzone", _timezone-3600);
1641 PyModule_AddIntConstant(m, "daylight", _daylight);
1642 PyModule_AddObject(m, "tzname",
1643 Py_BuildValue("(zz)", _tzname[0], _tzname[1]));
Tim Peters26ae7cd2001-03-20 03:26:49 +00001644#endif /* __CYGWIN__ */
Guido van Rossum10b164a2001-09-25 13:59:01 +00001645#endif /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/
Victor Stinner5eb78c72018-12-04 00:09:02 +01001646
1647 if (PyErr_Occurred()) {
1648 return -1;
1649 }
Victor Stinner38c06d92018-12-01 01:24:21 +01001650 return 0;
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001651}
1652
1653
1654static PyMethodDef time_methods[] = {
Victor Stinner4195b5c2012-02-08 23:03:19 +01001655 {"time", time_time, METH_NOARGS, time_doc},
Victor Stinnerc29b5852017-11-02 07:28:27 -07001656 {"time_ns", time_time_ns, METH_NOARGS, time_ns_doc},
Victor Stinnerec895392012-04-29 02:41:27 +02001657#ifdef PYCLOCK
Victor Stinner4195b5c2012-02-08 23:03:19 +01001658 {"clock", time_clock, METH_NOARGS, clock_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001659#endif
Victor Stinnere0be4232011-10-25 13:06:09 +02001660#ifdef HAVE_CLOCK_GETTIME
Victor Stinner4195b5c2012-02-08 23:03:19 +01001661 {"clock_gettime", time_clock_gettime, METH_VARARGS, clock_gettime_doc},
Victor Stinnerc29b5852017-11-02 07:28:27 -07001662 {"clock_gettime_ns",time_clock_gettime_ns, METH_VARARGS, clock_gettime_ns_doc},
Benjamin Peterson37098cd2016-09-13 22:55:09 -07001663#endif
1664#ifdef HAVE_CLOCK_SETTIME
Victor Stinner30d79472012-04-03 00:45:07 +02001665 {"clock_settime", time_clock_settime, METH_VARARGS, clock_settime_doc},
Victor Stinnerc29b5852017-11-02 07:28:27 -07001666 {"clock_settime_ns",time_clock_settime_ns, METH_VARARGS, clock_settime_ns_doc},
Benjamin Peterson37098cd2016-09-13 22:55:09 -07001667#endif
1668#ifdef HAVE_CLOCK_GETRES
Victor Stinner4195b5c2012-02-08 23:03:19 +01001669 {"clock_getres", time_clock_getres, METH_VARARGS, clock_getres_doc},
Victor Stinnere0be4232011-10-25 13:06:09 +02001670#endif
pdoxe14679c2017-10-05 00:01:56 -07001671#ifdef HAVE_PTHREAD_GETCPUCLOCKID
1672 {"pthread_getcpuclockid", time_pthread_getcpuclockid, METH_VARARGS, pthread_getcpuclockid_doc},
1673#endif
Victor Stinnercb29f012015-03-27 13:31:18 +01001674 {"sleep", time_sleep, METH_O, sleep_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001675 {"gmtime", time_gmtime, METH_VARARGS, gmtime_doc},
1676 {"localtime", time_localtime, METH_VARARGS, localtime_doc},
1677 {"asctime", time_asctime, METH_VARARGS, asctime_doc},
1678 {"ctime", time_ctime, METH_VARARGS, ctime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001679#ifdef HAVE_MKTIME
Victor Stinner4195b5c2012-02-08 23:03:19 +01001680 {"mktime", time_mktime, METH_O, mktime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001681#endif
1682#ifdef HAVE_STRFTIME
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001683 {"strftime", time_strftime, METH_VARARGS, strftime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001684#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001685 {"strptime", time_strptime, METH_VARARGS, strptime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001686#ifdef HAVE_WORKING_TZSET
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001687 {"tzset", time_tzset, METH_NOARGS, tzset_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001688#endif
Victor Stinnerec895392012-04-29 02:41:27 +02001689 {"monotonic", time_monotonic, METH_NOARGS, monotonic_doc},
Victor Stinnerc29b5852017-11-02 07:28:27 -07001690 {"monotonic_ns", time_monotonic_ns, METH_NOARGS, monotonic_ns_doc},
Victor Stinnerec895392012-04-29 02:41:27 +02001691 {"process_time", time_process_time, METH_NOARGS, process_time_doc},
Victor Stinnerc29b5852017-11-02 07:28:27 -07001692 {"process_time_ns", time_process_time_ns, METH_NOARGS, process_time_ns_doc},
Antoine Pitrou4bd41c92017-11-15 22:52:21 +01001693#ifdef HAVE_THREAD_TIME
1694 {"thread_time", time_thread_time, METH_NOARGS, thread_time_doc},
1695 {"thread_time_ns", time_thread_time_ns, METH_NOARGS, thread_time_ns_doc},
1696#endif
Victor Stinnerec895392012-04-29 02:41:27 +02001697 {"perf_counter", time_perf_counter, METH_NOARGS, perf_counter_doc},
Victor Stinnerc29b5852017-11-02 07:28:27 -07001698 {"perf_counter_ns", time_perf_counter_ns, METH_NOARGS, perf_counter_ns_doc},
Victor Stinnerec895392012-04-29 02:41:27 +02001699 {"get_clock_info", time_get_clock_info, METH_VARARGS, get_clock_info_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001700 {NULL, NULL} /* sentinel */
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001701};
1702
1703
1704PyDoc_STRVAR(module_doc,
1705"This module provides various functions to manipulate time values.\n\
1706\n\
1707There are two standard representations of time. One is the number\n\
1708of seconds since the Epoch, in UTC (a.k.a. GMT). It may be an integer\n\
1709or a floating point number (to represent fractions of seconds).\n\
1710The Epoch is system-defined; on Unix, it is generally January 1st, 1970.\n\
1711The actual value can be retrieved by calling gmtime(0).\n\
1712\n\
1713The other representation is a tuple of 9 integers giving local time.\n\
1714The tuple items are:\n\
Alexander Belopolsky03163ac2011-05-02 12:20:52 -04001715 year (including century, e.g. 1998)\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001716 month (1-12)\n\
1717 day (1-31)\n\
1718 hours (0-23)\n\
1719 minutes (0-59)\n\
1720 seconds (0-59)\n\
1721 weekday (0-6, Monday is 0)\n\
1722 Julian day (day in the year, 1-366)\n\
1723 DST (Daylight Savings Time) flag (-1, 0 or 1)\n\
1724If the DST flag is 0, the time is given in the regular time zone;\n\
1725if it is 1, the time is given in the DST time zone;\n\
Cheryl Sabella703ff382017-10-11 09:29:14 -04001726if it is -1, mktime() should guess based on the date and time.\n");
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001727
1728
Martin v. Löwis1a214512008-06-11 05:26:20 +00001729
1730static struct PyModuleDef timemodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001731 PyModuleDef_HEAD_INIT,
1732 "time",
1733 module_doc,
1734 -1,
1735 time_methods,
1736 NULL,
1737 NULL,
1738 NULL,
1739 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00001740};
1741
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001742PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00001743PyInit_time(void)
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001744{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001745 PyObject *m;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001746 m = PyModule_Create(&timemodule);
1747 if (m == NULL)
1748 return NULL;
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001749
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001750 /* Set, or reset, module variables like time.timezone */
Victor Stinner5eb78c72018-12-04 00:09:02 +01001751 if (init_timezone(m) < 0) {
Victor Stinner38c06d92018-12-01 01:24:21 +01001752 return NULL;
1753 }
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001754
Miss Islington (bot)002aef32018-10-20 17:41:38 -07001755#if defined(HAVE_CLOCK_GETTIME) || defined(HAVE_CLOCK_SETTIME) || defined(HAVE_CLOCK_GETRES)
1756
Benjamin Peterson37098cd2016-09-13 22:55:09 -07001757#ifdef CLOCK_REALTIME
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -04001758 PyModule_AddIntMacro(m, CLOCK_REALTIME);
Benjamin Peterson37098cd2016-09-13 22:55:09 -07001759#endif
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -04001760#ifdef CLOCK_MONOTONIC
1761 PyModule_AddIntMacro(m, CLOCK_MONOTONIC);
1762#endif
1763#ifdef CLOCK_MONOTONIC_RAW
1764 PyModule_AddIntMacro(m, CLOCK_MONOTONIC_RAW);
1765#endif
1766#ifdef CLOCK_HIGHRES
1767 PyModule_AddIntMacro(m, CLOCK_HIGHRES);
1768#endif
1769#ifdef CLOCK_PROCESS_CPUTIME_ID
1770 PyModule_AddIntMacro(m, CLOCK_PROCESS_CPUTIME_ID);
1771#endif
1772#ifdef CLOCK_THREAD_CPUTIME_ID
1773 PyModule_AddIntMacro(m, CLOCK_THREAD_CPUTIME_ID);
1774#endif
Victor Stinnera64ce972017-11-02 04:19:19 -07001775#ifdef CLOCK_PROF
1776 PyModule_AddIntMacro(m, CLOCK_PROF);
1777#endif
1778#ifdef CLOCK_BOOTTIME
1779 PyModule_AddIntMacro(m, CLOCK_BOOTTIME);
1780#endif
1781#ifdef CLOCK_UPTIME
1782 PyModule_AddIntMacro(m, CLOCK_UPTIME);
1783#endif
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -04001784
Miss Islington (bot)002aef32018-10-20 17:41:38 -07001785#endif /* defined(HAVE_CLOCK_GETTIME) || defined(HAVE_CLOCK_SETTIME) || defined(HAVE_CLOCK_GETRES) */
1786
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001787 if (!initialized) {
Victor Stinner1c8f0592013-07-22 22:24:54 +02001788 if (PyStructSequence_InitType2(&StructTimeType,
1789 &struct_time_type_desc) < 0)
1790 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001791 }
1792 Py_INCREF(&StructTimeType);
Alexander Belopolskyc142bba2012-06-13 22:15:26 -04001793 PyModule_AddIntConstant(m, "_STRUCT_TM_ITEMS", 11);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001794 PyModule_AddObject(m, "struct_time", (PyObject*) &StructTimeType);
1795 initialized = 1;
Victor Stinner5eb78c72018-12-04 00:09:02 +01001796
1797 if (PyErr_Occurred()) {
1798 return NULL;
1799 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001800 return m;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001801}
1802
Victor Stinnercb29f012015-03-27 13:31:18 +01001803/* Implement pysleep() for various platforms.
Guido van Rossumb6775db1994-08-01 11:34:53 +00001804 When interrupted (or when another error occurs), return -1 and
1805 set an exception; else return 0. */
1806
1807static int
Victor Stinnercb29f012015-03-27 13:31:18 +01001808pysleep(_PyTime_t secs)
Guido van Rossum426035c1991-02-19 12:27:35 +00001809{
Victor Stinnercb29f012015-03-27 13:31:18 +01001810 _PyTime_t deadline, monotonic;
Victor Stinner79d68f92015-03-19 21:54:09 +01001811#ifndef MS_WINDOWS
1812 struct timeval timeout;
Victor Stinner79d68f92015-03-19 21:54:09 +01001813 int err = 0;
1814#else
Victor Stinnercb29f012015-03-27 13:31:18 +01001815 _PyTime_t millisecs;
Victor Stinner79d68f92015-03-19 21:54:09 +01001816 unsigned long ul_millis;
1817 DWORD rc;
1818 HANDLE hInterruptEvent;
Victor Stinner0c2fd892015-03-17 10:49:17 +01001819#endif
Victor Stinner79d68f92015-03-19 21:54:09 +01001820
Victor Stinnercb29f012015-03-27 13:31:18 +01001821 deadline = _PyTime_GetMonotonicClock() + secs;
Victor Stinner79d68f92015-03-19 21:54:09 +01001822
1823 do {
1824#ifndef MS_WINDOWS
Victor Stinner869e1772015-03-30 03:49:14 +02001825 if (_PyTime_AsTimeval(secs, &timeout, _PyTime_ROUND_CEILING) < 0)
Victor Stinnercb29f012015-03-27 13:31:18 +01001826 return -1;
Victor Stinner79d68f92015-03-19 21:54:09 +01001827
1828 Py_BEGIN_ALLOW_THREADS
1829 err = select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &timeout);
1830 Py_END_ALLOW_THREADS
1831
1832 if (err == 0)
1833 break;
1834
1835 if (errno != EINTR) {
Victor Stinner0c2fd892015-03-17 10:49:17 +01001836 PyErr_SetFromErrno(PyExc_OSError);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001837 return -1;
1838 }
Victor Stinner79d68f92015-03-19 21:54:09 +01001839#else
Victor Stinner869e1772015-03-30 03:49:14 +02001840 millisecs = _PyTime_AsMilliseconds(secs, _PyTime_ROUND_CEILING);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001841 if (millisecs > (double)ULONG_MAX) {
1842 PyErr_SetString(PyExc_OverflowError,
1843 "sleep length is too large");
1844 return -1;
1845 }
Victor Stinner79d68f92015-03-19 21:54:09 +01001846
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001847 /* Allow sleep(0) to maintain win32 semantics, and as decreed
1848 * by Guido, only the main thread can be interrupted.
1849 */
1850 ul_millis = (unsigned long)millisecs;
Victor Stinner79d68f92015-03-19 21:54:09 +01001851 if (ul_millis == 0 || !_PyOS_IsMainThread()) {
1852 Py_BEGIN_ALLOW_THREADS
Victor Stinner0eac1302015-03-20 03:06:12 +01001853 Sleep(ul_millis);
Victor Stinner79d68f92015-03-19 21:54:09 +01001854 Py_END_ALLOW_THREADS
1855 break;
Victor Stinner945c82e2015-03-12 16:19:01 +01001856 }
Victor Stinner79d68f92015-03-19 21:54:09 +01001857
1858 hInterruptEvent = _PyOS_SigintEvent();
1859 ResetEvent(hInterruptEvent);
1860
1861 Py_BEGIN_ALLOW_THREADS
1862 rc = WaitForSingleObjectEx(hInterruptEvent, ul_millis, FALSE);
Victor Stinner0c2fd892015-03-17 10:49:17 +01001863 Py_END_ALLOW_THREADS
Victor Stinner79d68f92015-03-19 21:54:09 +01001864
1865 if (rc != WAIT_OBJECT_0)
1866 break;
Victor Stinner945c82e2015-03-12 16:19:01 +01001867#endif
Victor Stinner0c2fd892015-03-17 10:49:17 +01001868
Victor Stinner79d68f92015-03-19 21:54:09 +01001869 /* sleep was interrupted by SIGINT */
1870 if (PyErr_CheckSignals())
1871 return -1;
1872
Victor Stinnercb29f012015-03-27 13:31:18 +01001873 monotonic = _PyTime_GetMonotonicClock();
1874 secs = deadline - monotonic;
Victor Stinner6aa446c2015-03-30 21:33:51 +02001875 if (secs < 0)
Victor Stinner79d68f92015-03-19 21:54:09 +01001876 break;
1877 /* retry with the recomputed delay */
1878 } while (1);
1879
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001880 return 0;
Guido van Rossum80c9d881991-04-16 08:47:51 +00001881}