blob: 2e0f08d24a6612c740daddc620e46ae332f9b0bd [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
Victor Stinnerc29b5852017-11-02 07:28:27 -070041#define SEC_TO_NS (1000 * 1000 * 1000)
42
Guido van Rossum234f9421993-06-17 12:35:49 +000043/* Forward declarations */
Victor Stinnercb29f012015-03-27 13:31:18 +010044static int pysleep(_PyTime_t);
Victor Stinnerec895392012-04-29 02:41:27 +020045
Victor Stinner85fdfa82012-01-27 00:38:48 +010046
Victor Stinnera997c7b2017-10-10 02:51:50 -070047static PyObject*
48_PyFloat_FromPyTime(_PyTime_t t)
49{
50 double d = _PyTime_AsSecondsDouble(t);
51 return PyFloat_FromDouble(d);
52}
53
Victor Stinnerc29b5852017-11-02 07:28:27 -070054
Victor Stinner4195b5c2012-02-08 23:03:19 +010055static PyObject *
Victor Stinnerc29b5852017-11-02 07:28:27 -070056time_time(PyObject *self, PyObject *unused)
Victor Stinner85fdfa82012-01-27 00:38:48 +010057{
Victor Stinnerc29b5852017-11-02 07:28:27 -070058 _PyTime_t t = _PyTime_GetSystemClock();
59 return _PyFloat_FromPyTime(t);
60}
61
62
63PyDoc_STRVAR(time_doc,
64"time() -> floating point number\n\
65\n\
66Return the current time in seconds since the Epoch.\n\
67Fractions of a second may be present if the system clock provides them.");
68
69static PyObject *
70time_time_ns(PyObject *self, PyObject *unused)
71{
72 _PyTime_t t = _PyTime_GetSystemClock();
73 return _PyTime_AsNanosecondsObject(t);
74}
75
76PyDoc_STRVAR(time_ns_doc,
77"time_ns() -> int\n\
78\n\
79Return the current time in nanoseconds since the Epoch.");
80
81#if defined(HAVE_CLOCK)
82
83#ifndef CLOCKS_PER_SEC
84# ifdef CLK_TCK
85# define CLOCKS_PER_SEC CLK_TCK
86# else
87# define CLOCKS_PER_SEC 1000000
88# endif
89#endif
90
91static int
92_PyTime_GetClockWithInfo(_PyTime_t *tp, _Py_clock_info_t *info)
93{
94 static int initialized = 0;
95 clock_t ticks;
96
97 if (!initialized) {
98 initialized = 1;
99
100 /* must sure that _PyTime_MulDiv(ticks, SEC_TO_NS, CLOCKS_PER_SEC)
101 above cannot overflow */
102 if ((_PyTime_t)CLOCKS_PER_SEC > _PyTime_MAX / SEC_TO_NS) {
103 PyErr_SetString(PyExc_OverflowError,
104 "CLOCKS_PER_SEC is too large");
105 return -1;
106 }
Victor Stinner85fdfa82012-01-27 00:38:48 +0100107 }
Victor Stinnerc29b5852017-11-02 07:28:27 -0700108
Victor Stinnerec895392012-04-29 02:41:27 +0200109 if (info) {
110 info->implementation = "clock()";
111 info->resolution = 1.0 / (double)CLOCKS_PER_SEC;
Benjamin Peterson49a69e42012-05-01 09:38:34 -0400112 info->monotonic = 1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +0200113 info->adjustable = 0;
Victor Stinnerec895392012-04-29 02:41:27 +0200114 }
Victor Stinnerc29b5852017-11-02 07:28:27 -0700115
116 ticks = clock();
117 if (ticks == (clock_t)-1) {
118 PyErr_SetString(PyExc_RuntimeError,
119 "the processor time used is not available "
120 "or its value cannot be represented");
121 return -1;
122 }
123 *tp = _PyTime_MulDiv(ticks, SEC_TO_NS, (_PyTime_t)CLOCKS_PER_SEC);
124 return 0;
Victor Stinner85fdfa82012-01-27 00:38:48 +0100125}
126#endif /* HAVE_CLOCK */
127
Victor Stinnercba9a0c2017-10-12 08:51:56 -0700128static PyObject*
129perf_counter(_Py_clock_info_t *info)
130{
Victor Stinnerbdaeb7d2017-10-16 08:44:31 -0700131 _PyTime_t t;
132 if (_PyTime_GetPerfCounterWithInfo(&t, info) < 0) {
Victor Stinnercba9a0c2017-10-12 08:51:56 -0700133 return NULL;
134 }
Victor Stinnerc29b5852017-11-02 07:28:27 -0700135 return _PyFloat_FromPyTime(t);
Victor Stinnercba9a0c2017-10-12 08:51:56 -0700136}
137
Victor Stinnera997c7b2017-10-10 02:51:50 -0700138#if defined(MS_WINDOWS) || defined(HAVE_CLOCK)
Victor Stinnerec895392012-04-29 02:41:27 +0200139#define PYCLOCK
140static PyObject*
141pyclock(_Py_clock_info_t *info)
142{
Victor Stinner884d13a2017-10-17 14:46:45 -0700143 if (PyErr_WarnEx(PyExc_DeprecationWarning,
144 "time.clock has been deprecated in Python 3.3 and will "
145 "be removed from Python 3.8: "
146 "use time.perf_counter or time.process_time "
147 "instead", 1) < 0) {
148 return NULL;
149 }
Victor Stinnerc29b5852017-11-02 07:28:27 -0700150
Victor Stinnera997c7b2017-10-10 02:51:50 -0700151#ifdef MS_WINDOWS
Victor Stinnercba9a0c2017-10-12 08:51:56 -0700152 return perf_counter(info);
Victor Stinner54884492014-08-29 16:51:33 +0200153#else
Victor Stinnerc29b5852017-11-02 07:28:27 -0700154 _PyTime_t t;
155 if (_PyTime_GetClockWithInfo(&t, info) < 0) {
156 return NULL;
157 }
158 return _PyFloat_FromPyTime(t);
Victor Stinner54884492014-08-29 16:51:33 +0200159#endif
Victor Stinnerec895392012-04-29 02:41:27 +0200160}
161
Victor Stinner9122fdd2011-07-04 13:55:40 +0200162static PyObject *
Victor Stinner4195b5c2012-02-08 23:03:19 +0100163time_clock(PyObject *self, PyObject *unused)
Victor Stinner9122fdd2011-07-04 13:55:40 +0200164{
Victor Stinnerec895392012-04-29 02:41:27 +0200165 return pyclock(NULL);
Victor Stinner9122fdd2011-07-04 13:55:40 +0200166}
Victor Stinner9122fdd2011-07-04 13:55:40 +0200167
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000168PyDoc_STRVAR(clock_doc,
Victor Stinner4195b5c2012-02-08 23:03:19 +0100169"clock() -> floating point number\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000170\n\
171Return the CPU time or real time since the start of the process or since\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000172the first call to clock(). This has as much precision as the system\n\
173records.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000174#endif
175
Victor Stinnere0be4232011-10-25 13:06:09 +0200176#ifdef HAVE_CLOCK_GETTIME
177static PyObject *
Victor Stinner4195b5c2012-02-08 23:03:19 +0100178time_clock_gettime(PyObject *self, PyObject *args)
Victor Stinnere0be4232011-10-25 13:06:09 +0200179{
180 int ret;
Victor Stinnere0be4232011-10-25 13:06:09 +0200181 struct timespec tp;
182
Michael Felte2926b72018-12-28 14:57:37 +0100183#if defined(_AIX) && (SIZEOF_LONG == 8)
184 long clk_id;
185 if (!PyArg_ParseTuple(args, "l:clock_gettime", &clk_id)) {
186#else
187 int clk_id;
Victor Stinnerc29b5852017-11-02 07:28:27 -0700188 if (!PyArg_ParseTuple(args, "i:clock_gettime", &clk_id)) {
Michael Felte2926b72018-12-28 14:57:37 +0100189#endif
Victor Stinnere0be4232011-10-25 13:06:09 +0200190 return NULL;
Victor Stinnerc29b5852017-11-02 07:28:27 -0700191 }
Victor Stinnere0be4232011-10-25 13:06:09 +0200192
193 ret = clock_gettime((clockid_t)clk_id, &tp);
Antoine Pitrou2c085602012-01-18 01:41:44 +0100194 if (ret != 0) {
Victor Stinnera734af32014-07-31 13:07:17 +0200195 PyErr_SetFromErrno(PyExc_OSError);
Antoine Pitrou2c085602012-01-18 01:41:44 +0100196 return NULL;
197 }
Victor Stinner4195b5c2012-02-08 23:03:19 +0100198 return PyFloat_FromDouble(tp.tv_sec + tp.tv_nsec * 1e-9);
Victor Stinnere0be4232011-10-25 13:06:09 +0200199}
200
201PyDoc_STRVAR(clock_gettime_doc,
Victor Stinnerc29b5852017-11-02 07:28:27 -0700202"clock_gettime(clk_id) -> float\n\
Victor Stinnere0be4232011-10-25 13:06:09 +0200203\n\
204Return the time of the specified clock clk_id.");
Victor Stinnerc29b5852017-11-02 07:28:27 -0700205
206static PyObject *
207time_clock_gettime_ns(PyObject *self, PyObject *args)
208{
209 int ret;
210 int clk_id;
211 struct timespec ts;
212 _PyTime_t t;
213
214 if (!PyArg_ParseTuple(args, "i:clock_gettime", &clk_id)) {
215 return NULL;
216 }
217
218 ret = clock_gettime((clockid_t)clk_id, &ts);
219 if (ret != 0) {
220 PyErr_SetFromErrno(PyExc_OSError);
221 return NULL;
222 }
223 if (_PyTime_FromTimespec(&t, &ts) < 0) {
224 return NULL;
225 }
226 return _PyTime_AsNanosecondsObject(t);
227}
228
229PyDoc_STRVAR(clock_gettime_ns_doc,
230"clock_gettime_ns(clk_id) -> int\n\
231\n\
232Return the time of the specified clock clk_id as nanoseconds.");
Benjamin Peterson37098cd2016-09-13 22:55:09 -0700233#endif /* HAVE_CLOCK_GETTIME */
Victor Stinner30d79472012-04-03 00:45:07 +0200234
Benjamin Peterson37098cd2016-09-13 22:55:09 -0700235#ifdef HAVE_CLOCK_SETTIME
Victor Stinner30d79472012-04-03 00:45:07 +0200236static PyObject *
237time_clock_settime(PyObject *self, PyObject *args)
238{
Victor Stinnerb8d01692012-04-13 23:44:05 +0200239 int clk_id;
Victor Stinner30d79472012-04-03 00:45:07 +0200240 PyObject *obj;
Victor Stinnerb3b45442015-03-28 04:09:41 +0100241 _PyTime_t t;
Victor Stinner30d79472012-04-03 00:45:07 +0200242 struct timespec tp;
243 int ret;
244
245 if (!PyArg_ParseTuple(args, "iO:clock_settime", &clk_id, &obj))
246 return NULL;
247
Victor Stinner02937aa2015-03-28 05:02:39 +0100248 if (_PyTime_FromSecondsObject(&t, obj, _PyTime_ROUND_FLOOR) < 0)
Victor Stinner30d79472012-04-03 00:45:07 +0200249 return NULL;
Victor Stinnerb3b45442015-03-28 04:09:41 +0100250
251 if (_PyTime_AsTimespec(t, &tp) == -1)
252 return NULL;
Victor Stinner30d79472012-04-03 00:45:07 +0200253
254 ret = clock_settime((clockid_t)clk_id, &tp);
255 if (ret != 0) {
Victor Stinnera734af32014-07-31 13:07:17 +0200256 PyErr_SetFromErrno(PyExc_OSError);
Victor Stinner30d79472012-04-03 00:45:07 +0200257 return NULL;
258 }
259 Py_RETURN_NONE;
260}
261
262PyDoc_STRVAR(clock_settime_doc,
263"clock_settime(clk_id, time)\n\
264\n\
265Set the time of the specified clock clk_id.");
Victor Stinnerc29b5852017-11-02 07:28:27 -0700266
267static PyObject *
268time_clock_settime_ns(PyObject *self, PyObject *args)
269{
270 int clk_id;
271 PyObject *obj;
272 _PyTime_t t;
273 struct timespec ts;
274 int ret;
275
276 if (!PyArg_ParseTuple(args, "iO:clock_settime", &clk_id, &obj)) {
277 return NULL;
278 }
279
280 if (_PyTime_FromNanosecondsObject(&t, obj) < 0) {
281 return NULL;
282 }
283 if (_PyTime_AsTimespec(t, &ts) == -1) {
284 return NULL;
285 }
286
287 ret = clock_settime((clockid_t)clk_id, &ts);
288 if (ret != 0) {
289 PyErr_SetFromErrno(PyExc_OSError);
290 return NULL;
291 }
292 Py_RETURN_NONE;
293}
294
295PyDoc_STRVAR(clock_settime_ns_doc,
296"clock_settime_ns(clk_id, time)\n\
297\n\
298Set the time of the specified clock clk_id with nanoseconds.");
Benjamin Peterson37098cd2016-09-13 22:55:09 -0700299#endif /* HAVE_CLOCK_SETTIME */
Victor Stinnere0be4232011-10-25 13:06:09 +0200300
Benjamin Peterson37098cd2016-09-13 22:55:09 -0700301#ifdef HAVE_CLOCK_GETRES
Victor Stinnere0be4232011-10-25 13:06:09 +0200302static PyObject *
Victor Stinner4195b5c2012-02-08 23:03:19 +0100303time_clock_getres(PyObject *self, PyObject *args)
Victor Stinnere0be4232011-10-25 13:06:09 +0200304{
305 int ret;
Victor Stinnerb8d01692012-04-13 23:44:05 +0200306 int clk_id;
Victor Stinnere0be4232011-10-25 13:06:09 +0200307 struct timespec tp;
308
Victor Stinner4195b5c2012-02-08 23:03:19 +0100309 if (!PyArg_ParseTuple(args, "i:clock_getres", &clk_id))
Victor Stinnere0be4232011-10-25 13:06:09 +0200310 return NULL;
311
312 ret = clock_getres((clockid_t)clk_id, &tp);
Antoine Pitrou2c085602012-01-18 01:41:44 +0100313 if (ret != 0) {
Victor Stinnera734af32014-07-31 13:07:17 +0200314 PyErr_SetFromErrno(PyExc_OSError);
Antoine Pitrou2c085602012-01-18 01:41:44 +0100315 return NULL;
316 }
Victor Stinner4195b5c2012-02-08 23:03:19 +0100317
318 return PyFloat_FromDouble(tp.tv_sec + tp.tv_nsec * 1e-9);
Victor Stinnere0be4232011-10-25 13:06:09 +0200319}
320
321PyDoc_STRVAR(clock_getres_doc,
Victor Stinner4195b5c2012-02-08 23:03:19 +0100322"clock_getres(clk_id) -> floating point number\n\
Victor Stinnere0be4232011-10-25 13:06:09 +0200323\n\
324Return the resolution (precision) of the specified clock clk_id.");
Benjamin Peterson37098cd2016-09-13 22:55:09 -0700325#endif /* HAVE_CLOCK_GETRES */
Victor Stinnere0be4232011-10-25 13:06:09 +0200326
pdoxe14679c2017-10-05 00:01:56 -0700327#ifdef HAVE_PTHREAD_GETCPUCLOCKID
328static PyObject *
329time_pthread_getcpuclockid(PyObject *self, PyObject *args)
330{
331 unsigned long thread_id;
332 int err;
333 clockid_t clk_id;
334 if (!PyArg_ParseTuple(args, "k:pthread_getcpuclockid", &thread_id)) {
335 return NULL;
336 }
337 err = pthread_getcpuclockid((pthread_t)thread_id, &clk_id);
338 if (err) {
339 errno = err;
340 PyErr_SetFromErrno(PyExc_OSError);
341 return NULL;
342 }
Gregory P. Smithb474e672018-12-30 17:05:36 -0800343#ifdef _Py_MEMORY_SANITIZER
344 __msan_unpoison(&clk_id, sizeof(clk_id));
345#endif
pdoxe14679c2017-10-05 00:01:56 -0700346 return PyLong_FromLong(clk_id);
347}
348
349PyDoc_STRVAR(pthread_getcpuclockid_doc,
350"pthread_getcpuclockid(thread_id) -> int\n\
351\n\
352Return the clk_id of a thread's CPU time clock.");
353#endif /* HAVE_PTHREAD_GETCPUCLOCKID */
354
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000355static PyObject *
Victor Stinnercb29f012015-03-27 13:31:18 +0100356time_sleep(PyObject *self, PyObject *obj)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000357{
Victor Stinnercb29f012015-03-27 13:31:18 +0100358 _PyTime_t secs;
Pablo Galindo59af94f2017-10-18 08:13:09 +0100359 if (_PyTime_FromSecondsObject(&secs, obj, _PyTime_ROUND_TIMEOUT))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000360 return NULL;
Victor Stinner7f53a502011-07-05 22:00:25 +0200361 if (secs < 0) {
362 PyErr_SetString(PyExc_ValueError,
363 "sleep length must be non-negative");
364 return NULL;
365 }
Victor Stinnercb29f012015-03-27 13:31:18 +0100366 if (pysleep(secs) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000367 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200368 Py_RETURN_NONE;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000369}
370
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000371PyDoc_STRVAR(sleep_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000372"sleep(seconds)\n\
373\n\
374Delay execution for a given number of seconds. The argument may be\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000375a floating point number for subsecond precision.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000376
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000377static PyStructSequence_Field struct_time_type_fields[] = {
Alexander Belopolsky69f3fd02010-06-05 15:04:51 +0000378 {"tm_year", "year, for example, 1993"},
379 {"tm_mon", "month of year, range [1, 12]"},
380 {"tm_mday", "day of month, range [1, 31]"},
381 {"tm_hour", "hours, range [0, 23]"},
382 {"tm_min", "minutes, range [0, 59]"},
383 {"tm_sec", "seconds, range [0, 61])"},
384 {"tm_wday", "day of week, range [0, 6], Monday is 0"},
385 {"tm_yday", "day of year, range [1, 366]"},
386 {"tm_isdst", "1 if summer time is in effect, 0 if not, and -1 if unknown"},
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400387 {"tm_zone", "abbreviation of timezone name"},
388 {"tm_gmtoff", "offset from UTC in seconds"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000389 {0}
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000390};
391
392static PyStructSequence_Desc struct_time_type_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000393 "time.struct_time",
Alexander Belopolsky69f3fd02010-06-05 15:04:51 +0000394 "The time value as returned by gmtime(), localtime(), and strptime(), and\n"
395 " accepted by asctime(), mktime() and strftime(). May be considered as a\n"
396 " sequence of 9 integers.\n\n"
397 " Note that several fields' values are not the same as those defined by\n"
398 " the C language standard for struct tm. For example, the value of the\n"
399 " field tm_year is the actual year, not year - 1900. See individual\n"
400 " fields' descriptions for details.",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000401 struct_time_type_fields,
402 9,
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000403};
Tim Peters9ad4b682002-02-13 05:14:18 +0000404
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000405static int initialized;
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000406static PyTypeObject StructTimeType;
407
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400408
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000409static PyObject *
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -0400410tmtotuple(struct tm *p
411#ifndef HAVE_STRUCT_TM_TM_ZONE
Victor Stinner0d659e52017-04-25 01:22:42 +0200412 , const char *zone, time_t gmtoff
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -0400413#endif
414)
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000415{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000416 PyObject *v = PyStructSequence_New(&StructTimeType);
417 if (v == NULL)
418 return NULL;
Tim Peters9ad4b682002-02-13 05:14:18 +0000419
Christian Heimes217cfd12007-12-02 14:31:20 +0000420#define SET(i,val) PyStructSequence_SET_ITEM(v, i, PyLong_FromLong((long) val))
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000421
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000422 SET(0, p->tm_year + 1900);
423 SET(1, p->tm_mon + 1); /* Want January == 1 */
424 SET(2, p->tm_mday);
425 SET(3, p->tm_hour);
426 SET(4, p->tm_min);
427 SET(5, p->tm_sec);
428 SET(6, (p->tm_wday + 6) % 7); /* Want Monday == 0 */
429 SET(7, p->tm_yday + 1); /* Want January, 1 == 1 */
430 SET(8, p->tm_isdst);
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400431#ifdef HAVE_STRUCT_TM_TM_ZONE
432 PyStructSequence_SET_ITEM(v, 9,
Victor Stinner7ed7aea2018-01-15 10:45:49 +0100433 PyUnicode_DecodeLocale(p->tm_zone, "surrogateescape"));
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400434 SET(10, p->tm_gmtoff);
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -0400435#else
436 PyStructSequence_SET_ITEM(v, 9,
Victor Stinner7ed7aea2018-01-15 10:45:49 +0100437 PyUnicode_DecodeLocale(zone, "surrogateescape"));
Victor Stinner0d659e52017-04-25 01:22:42 +0200438 PyStructSequence_SET_ITEM(v, 10, _PyLong_FromTime_t(gmtoff));
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400439#endif /* HAVE_STRUCT_TM_TM_ZONE */
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000440#undef SET
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000441 if (PyErr_Occurred()) {
442 Py_XDECREF(v);
443 return NULL;
444 }
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000445
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000446 return v;
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000447}
448
Fred Drakef901abd2004-08-03 17:58:55 +0000449/* Parse arg tuple that can contain an optional float-or-None value;
450 format needs to be "|O:name".
451 Returns non-zero on success (parallels PyArg_ParseTuple).
452*/
453static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +0200454parse_time_t_args(PyObject *args, const char *format, time_t *pwhen)
Fred Drakef901abd2004-08-03 17:58:55 +0000455{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000456 PyObject *ot = NULL;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100457 time_t whent;
Fred Drakef901abd2004-08-03 17:58:55 +0000458
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000459 if (!PyArg_ParseTuple(args, format, &ot))
460 return 0;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100461 if (ot == NULL || ot == Py_None) {
462 whent = time(NULL);
463 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000464 else {
Victor Stinner02937aa2015-03-28 05:02:39 +0100465 if (_PyTime_ObjectToTime_t(ot, &whent, _PyTime_ROUND_FLOOR) == -1)
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100466 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000467 }
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100468 *pwhen = whent;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000469 return 1;
Fred Drakef901abd2004-08-03 17:58:55 +0000470}
471
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000472static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000473time_gmtime(PyObject *self, PyObject *args)
Guido van Rossum234f9421993-06-17 12:35:49 +0000474{
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100475 time_t when;
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -0400476 struct tm buf;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100477
478 if (!parse_time_t_args(args, "|O:gmtime", &when))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000479 return NULL;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100480
481 errno = 0;
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -0400482 if (_PyTime_gmtime(when, &buf) != 0)
483 return NULL;
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -0400484#ifdef HAVE_STRUCT_TM_TM_ZONE
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100485 return tmtotuple(&buf);
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -0400486#else
487 return tmtotuple(&buf, "UTC", 0);
488#endif
Guido van Rossum234f9421993-06-17 12:35:49 +0000489}
490
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -0400491#ifndef HAVE_TIMEGM
492static time_t
493timegm(struct tm *p)
494{
495 /* XXX: the following implementation will not work for tm_year < 1970.
496 but it is likely that platforms that don't have timegm do not support
497 negative timestamps anyways. */
498 return p->tm_sec + p->tm_min*60 + p->tm_hour*3600 + p->tm_yday*86400 +
499 (p->tm_year-70)*31536000 + ((p->tm_year-69)/4)*86400 -
500 ((p->tm_year-1)/100)*86400 + ((p->tm_year+299)/400)*86400;
501}
502#endif
503
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000504PyDoc_STRVAR(gmtime_doc,
Christian Heimes9a371592007-12-28 14:08:13 +0000505"gmtime([seconds]) -> (tm_year, tm_mon, tm_mday, tm_hour, tm_min,\n\
Fred Drake193a3f62002-03-12 21:38:49 +0000506 tm_sec, tm_wday, tm_yday, tm_isdst)\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000507\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000508Convert seconds since the Epoch to a time tuple expressing UTC (a.k.a.\n\
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400509GMT). When 'seconds' is not passed in, convert the current time instead.\n\
510\n\
511If the platform supports the tm_gmtoff and tm_zone, they are available as\n\
512attributes only.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000513
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000514static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000515time_localtime(PyObject *self, PyObject *args)
Guido van Rossum234f9421993-06-17 12:35:49 +0000516{
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100517 time_t when;
518 struct tm buf;
519
520 if (!parse_time_t_args(args, "|O:localtime", &when))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000521 return NULL;
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -0400522 if (_PyTime_localtime(when, &buf) != 0)
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100523 return NULL;
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -0400524#ifdef HAVE_STRUCT_TM_TM_ZONE
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100525 return tmtotuple(&buf);
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -0400526#else
527 {
528 struct tm local = buf;
529 char zone[100];
Victor Stinner0d659e52017-04-25 01:22:42 +0200530 time_t gmtoff;
Steve Dowerc3c6f712016-12-14 11:22:05 -0800531 strftime(zone, sizeof(zone), "%Z", &buf);
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -0400532 gmtoff = timegm(&buf) - when;
533 return tmtotuple(&local, zone, gmtoff);
534 }
535#endif
Guido van Rossum234f9421993-06-17 12:35:49 +0000536}
537
Benjamin Peterson5633c4f2018-09-14 09:09:04 -0700538#if defined(__linux__) && !defined(__GLIBC__)
539static const char *utc_string = NULL;
540#endif
541
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000542PyDoc_STRVAR(localtime_doc,
Christian Heimes9a371592007-12-28 14:08:13 +0000543"localtime([seconds]) -> (tm_year,tm_mon,tm_mday,tm_hour,tm_min,\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000544 tm_sec,tm_wday,tm_yday,tm_isdst)\n\
Martin v. Löwisb3cfc1d2001-12-02 12:27:43 +0000545\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000546Convert seconds since the Epoch to a time tuple expressing local time.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000547When 'seconds' is not passed in, convert the current time instead.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000548
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000549/* Convert 9-item tuple to tm structure. Return 1 on success, set
550 * an exception and return 0 on error.
551 */
Guido van Rossum9e90a671993-06-24 11:10:19 +0000552static int
Oren Milman1d1d3e92017-08-20 18:35:36 +0300553gettmarg(PyObject *args, struct tm *p, const char *format)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000554{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000555 int y;
Guido van Rossumcfbaecc1998-08-25 14:51:12 +0000556
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000557 memset((void *) p, '\0', sizeof(struct tm));
Guido van Rossumb9081262007-08-25 03:14:09 +0000558
Alexander Belopolsky610e5442011-01-06 21:57:06 +0000559 if (!PyTuple_Check(args)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000560 PyErr_SetString(PyExc_TypeError,
561 "Tuple or struct_time argument required");
562 return 0;
563 }
Skip Montanaro41cfce92007-08-24 21:11:00 +0000564
Oren Milman1d1d3e92017-08-20 18:35:36 +0300565 if (!PyArg_ParseTuple(args, format,
Alexander Belopolsky610e5442011-01-06 21:57:06 +0000566 &y, &p->tm_mon, &p->tm_mday,
567 &p->tm_hour, &p->tm_min, &p->tm_sec,
568 &p->tm_wday, &p->tm_yday, &p->tm_isdst))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000569 return 0;
Gregory P. Smith76be0ff2018-08-24 18:08:50 -0700570
571 if (y < INT_MIN + 1900) {
572 PyErr_SetString(PyExc_OverflowError, "year out of range");
573 return 0;
574 }
575
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000576 p->tm_year = y - 1900;
577 p->tm_mon--;
578 p->tm_wday = (p->tm_wday + 1) % 7;
579 p->tm_yday--;
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400580#ifdef HAVE_STRUCT_TM_TM_ZONE
581 if (Py_TYPE(args) == &StructTimeType) {
582 PyObject *item;
Victor Stinner1cdfcfc2018-11-28 15:19:51 +0100583 item = PyStructSequence_GET_ITEM(args, 9);
Benjamin Peterson5633c4f2018-09-14 09:09:04 -0700584 if (item != Py_None) {
Xiang Zhang163eca32018-10-28 23:58:42 +0800585 p->tm_zone = (char *)PyUnicode_AsUTF8(item);
Benjamin Peterson5633c4f2018-09-14 09:09:04 -0700586 if (p->tm_zone == NULL) {
587 return 0;
588 }
589#if defined(__linux__) && !defined(__GLIBC__)
590 // Make an attempt to return the C library's own timezone strings to
591 // it. musl refuses to process a tm_zone field unless it produced
592 // it. See issue #34672.
593 if (utc_string && strcmp(p->tm_zone, utc_string) == 0) {
594 p->tm_zone = utc_string;
595 }
596 else if (tzname[0] && strcmp(p->tm_zone, tzname[0]) == 0) {
597 p->tm_zone = tzname[0];
598 }
599 else if (tzname[1] && strcmp(p->tm_zone, tzname[1]) == 0) {
600 p->tm_zone = tzname[1];
601 }
602#endif
603 }
Victor Stinner1cdfcfc2018-11-28 15:19:51 +0100604 item = PyStructSequence_GET_ITEM(args, 10);
Benjamin Peterson5633c4f2018-09-14 09:09:04 -0700605 if (item != Py_None) {
606 p->tm_gmtoff = PyLong_AsLong(item);
607 if (PyErr_Occurred())
608 return 0;
609 }
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400610 }
611#endif /* HAVE_STRUCT_TM_TM_ZONE */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000612 return 1;
Guido van Rossum9e90a671993-06-24 11:10:19 +0000613}
614
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000615/* Check values of the struct tm fields before it is passed to strftime() and
616 * asctime(). Return 1 if all values are valid, otherwise set an exception
617 * and returns 0.
618 */
Victor Stinneref128102010-10-07 01:00:52 +0000619static int
620checktm(struct tm* buf)
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000621{
Victor Stinneref128102010-10-07 01:00:52 +0000622 /* Checks added to make sure strftime() and asctime() does not crash Python by
623 indexing blindly into some array for a textual representation
624 by some bad index (fixes bug #897625 and #6608).
625
626 Also support values of zero from Python code for arguments in which
627 that is out of range by forcing that value to the lowest value that
628 is valid (fixed bug #1520914).
629
630 Valid ranges based on what is allowed in struct tm:
631
632 - tm_year: [0, max(int)] (1)
633 - tm_mon: [0, 11] (2)
634 - tm_mday: [1, 31]
635 - tm_hour: [0, 23]
636 - tm_min: [0, 59]
637 - tm_sec: [0, 60]
638 - tm_wday: [0, 6] (1)
639 - tm_yday: [0, 365] (2)
640 - tm_isdst: [-max(int), max(int)]
641
642 (1) gettmarg() handles bounds-checking.
643 (2) Python's acceptable range is one greater than the range in C,
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000644 thus need to check against automatic decrement by gettmarg().
645 */
646 if (buf->tm_mon == -1)
647 buf->tm_mon = 0;
648 else if (buf->tm_mon < 0 || buf->tm_mon > 11) {
649 PyErr_SetString(PyExc_ValueError, "month out of range");
650 return 0;
651 }
652 if (buf->tm_mday == 0)
653 buf->tm_mday = 1;
654 else if (buf->tm_mday < 0 || buf->tm_mday > 31) {
655 PyErr_SetString(PyExc_ValueError, "day of month out of range");
656 return 0;
657 }
658 if (buf->tm_hour < 0 || buf->tm_hour > 23) {
659 PyErr_SetString(PyExc_ValueError, "hour out of range");
660 return 0;
661 }
662 if (buf->tm_min < 0 || buf->tm_min > 59) {
663 PyErr_SetString(PyExc_ValueError, "minute out of range");
664 return 0;
665 }
666 if (buf->tm_sec < 0 || buf->tm_sec > 61) {
667 PyErr_SetString(PyExc_ValueError, "seconds out of range");
668 return 0;
669 }
670 /* tm_wday does not need checking of its upper-bound since taking
671 ``% 7`` in gettmarg() automatically restricts the range. */
672 if (buf->tm_wday < 0) {
673 PyErr_SetString(PyExc_ValueError, "day of week out of range");
674 return 0;
675 }
676 if (buf->tm_yday == -1)
677 buf->tm_yday = 0;
678 else if (buf->tm_yday < 0 || buf->tm_yday > 365) {
679 PyErr_SetString(PyExc_ValueError, "day of year out of range");
680 return 0;
681 }
682 return 1;
683}
684
Victor Stinnerc1f32ca2011-10-14 02:36:13 +0200685#ifdef MS_WINDOWS
686 /* wcsftime() doesn't format correctly time zones, see issue #10653 */
687# undef HAVE_WCSFTIME
688#endif
Alexander Belopolskycf774542012-10-02 18:39:16 -0400689#define STRFTIME_FORMAT_CODES \
690"Commonly used format codes:\n\
691\n\
692%Y Year with century as a decimal number.\n\
693%m Month as a decimal number [01,12].\n\
694%d Day of the month as a decimal number [01,31].\n\
695%H Hour (24-hour clock) as a decimal number [00,23].\n\
696%M Minute as a decimal number [00,59].\n\
697%S Second as a decimal number [00,61].\n\
698%z Time zone offset from UTC.\n\
699%a Locale's abbreviated weekday name.\n\
700%A Locale's full weekday name.\n\
701%b Locale's abbreviated month name.\n\
702%B Locale's full month name.\n\
703%c Locale's appropriate date and time representation.\n\
704%I Hour (12-hour clock) as a decimal number [01,12].\n\
705%p Locale's equivalent of either AM or PM.\n\
706\n\
707Other codes may be available on your platform. See documentation for\n\
708the C library strftime function.\n"
Victor Stinnerc1f32ca2011-10-14 02:36:13 +0200709
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000710#ifdef HAVE_STRFTIME
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000711#ifdef HAVE_WCSFTIME
712#define time_char wchar_t
713#define format_time wcsftime
714#define time_strlen wcslen
715#else
716#define time_char char
717#define format_time strftime
718#define time_strlen strlen
719#endif
720
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000721static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000722time_strftime(PyObject *self, PyObject *args)
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000723{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000724 PyObject *tup = NULL;
725 struct tm buf;
726 const time_char *fmt;
Victor Stinnerb2904782010-09-29 10:34:19 +0000727#ifdef HAVE_WCSFTIME
728 wchar_t *format;
729#else
730 PyObject *format;
731#endif
Victor Stinneref128102010-10-07 01:00:52 +0000732 PyObject *format_arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000733 size_t fmtlen, buflen;
Victor Stinnerb2904782010-09-29 10:34:19 +0000734 time_char *outbuf = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000735 size_t i;
Victor Stinnerb2904782010-09-29 10:34:19 +0000736 PyObject *ret = NULL;
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000737
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000738 memset((void *) &buf, '\0', sizeof(buf));
Guido van Rossum1f41f841998-04-27 19:04:26 +0000739
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000740 /* Will always expect a unicode string to be passed as format.
741 Given that there's no str type anymore in py3k this seems safe.
742 */
Victor Stinneref128102010-10-07 01:00:52 +0000743 if (!PyArg_ParseTuple(args, "U|O:strftime", &format_arg, &tup))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000744 return NULL;
Thomas Woutersfe385252001-01-19 23:16:56 +0000745
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000746 if (tup == NULL) {
747 time_t tt = time(NULL);
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -0400748 if (_PyTime_localtime(tt, &buf) != 0)
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100749 return NULL;
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000750 }
Oren Milman1d1d3e92017-08-20 18:35:36 +0300751 else if (!gettmarg(tup, &buf,
752 "iiiiiiiii;strftime(): illegal time tuple argument") ||
753 !checktm(&buf))
754 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000755 return NULL;
Oren Milman1d1d3e92017-08-20 18:35:36 +0300756 }
Guido van Rossum10b164a2001-09-25 13:59:01 +0000757
Jakub Kulík6f9bc722018-12-31 03:16:40 +0100758#if defined(_MSC_VER) || (defined(__sun) && defined(__SVR4)) || defined(_AIX)
Victor Stinner73ea29c2011-01-08 01:56:31 +0000759 if (buf.tm_year + 1900 < 1 || 9999 < buf.tm_year + 1900) {
Victor Stinner6f0e4f92011-03-21 02:14:53 +0100760 PyErr_SetString(PyExc_ValueError,
761 "strftime() requires year in [1; 9999]");
Alexander Belopolsky0dd06f42011-01-08 01:23:02 +0000762 return NULL;
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000763 }
Victor Stinner73ea29c2011-01-08 01:56:31 +0000764#endif
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000765
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000766 /* Normalize tm_isdst just in case someone foolishly implements %Z
767 based on the assumption that tm_isdst falls within the range of
768 [-1, 1] */
769 if (buf.tm_isdst < -1)
770 buf.tm_isdst = -1;
771 else if (buf.tm_isdst > 1)
772 buf.tm_isdst = 1;
Brett Cannond1080a32004-03-02 04:38:10 +0000773
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000774#ifdef HAVE_WCSFTIME
Victor Stinnerbeb4135b2010-10-07 01:02:42 +0000775 format = PyUnicode_AsWideCharString(format_arg, NULL);
Victor Stinnerb2904782010-09-29 10:34:19 +0000776 if (format == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000777 return NULL;
Victor Stinnerb2904782010-09-29 10:34:19 +0000778 fmt = format;
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000779#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000780 /* Convert the unicode string to an ascii one */
Victor Stinner1b579672011-12-17 05:47:23 +0100781 format = PyUnicode_EncodeLocale(format_arg, "surrogateescape");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000782 if (format == NULL)
783 return NULL;
784 fmt = PyBytes_AS_STRING(format);
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000785#endif
Amaury Forgeot d'Arcb5be6d42009-03-02 23:52:57 +0000786
Stefan Krah4aea7d32012-02-27 16:30:26 +0100787#if defined(MS_WINDOWS) && !defined(HAVE_WCSFTIME)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000788 /* check that the format string contains only valid directives */
Steve Dowere5b58952015-09-06 19:20:51 -0700789 for (outbuf = strchr(fmt, '%');
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000790 outbuf != NULL;
Victor Stinner5a3ff792011-10-16 19:08:23 +0200791 outbuf = strchr(outbuf+2, '%'))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000792 {
Steve Dowere5b58952015-09-06 19:20:51 -0700793 if (outbuf[1] == '#')
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000794 ++outbuf; /* not documented by python, */
Steve Dowere5b58952015-09-06 19:20:51 -0700795 if (outbuf[1] == '\0')
796 break;
797 if ((outbuf[1] == 'y') && buf.tm_year < 0) {
Tim Golden6e51b8f2013-11-12 12:36:54 +0000798 PyErr_SetString(PyExc_ValueError,
799 "format %y requires year >= 1900 on Windows");
800 Py_DECREF(format);
801 return NULL;
802 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000803 }
Jakub Kulík6f9bc722018-12-31 03:16:40 +0100804#elif (defined(_AIX) || (defined(__sun) && defined(__SVR4))) && defined(HAVE_WCSFTIME)
Steve Dowere5b58952015-09-06 19:20:51 -0700805 for (outbuf = wcschr(fmt, '%');
Victor Stinner55329f82013-11-17 23:39:21 +0100806 outbuf != NULL;
807 outbuf = wcschr(outbuf+2, '%'))
808 {
Steve Dowere5b58952015-09-06 19:20:51 -0700809 if (outbuf[1] == L'\0')
810 break;
Victor Stinner55329f82013-11-17 23:39:21 +0100811 /* Issue #19634: On AIX, wcsftime("y", (1899, 1, 1, 0, 0, 0, 0, 0, 0))
812 returns "0/" instead of "99" */
813 if (outbuf[1] == L'y' && buf.tm_year < 0) {
814 PyErr_SetString(PyExc_ValueError,
815 "format %y requires year >= 1900 on AIX");
Zackery Spytz91e6c872018-09-21 00:09:48 -0600816 PyMem_Free(format);
Victor Stinner55329f82013-11-17 23:39:21 +0100817 return NULL;
818 }
819 }
Amaury Forgeot d'Arcb5be6d42009-03-02 23:52:57 +0000820#endif
821
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000822 fmtlen = time_strlen(fmt);
Guido van Rossumc222ec21999-02-23 00:00:10 +0000823
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000824 /* I hate these functions that presume you know how big the output
825 * will be ahead of time...
826 */
827 for (i = 1024; ; i += i) {
828 outbuf = (time_char *)PyMem_Malloc(i*sizeof(time_char));
829 if (outbuf == NULL) {
Victor Stinnerb2904782010-09-29 10:34:19 +0000830 PyErr_NoMemory();
831 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000832 }
Steve Dower57ab1cd2015-09-22 14:51:42 -0700833#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
834 errno = 0;
835#endif
Steve Dowerd9ef74e2015-05-22 15:08:34 -0700836 _Py_BEGIN_SUPPRESS_IPH
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000837 buflen = format_time(outbuf, i, fmt, &buf);
Steve Dowerd9ef74e2015-05-22 15:08:34 -0700838 _Py_END_SUPPRESS_IPH
Victor Stinner136ea492011-12-17 22:37:18 +0100839#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
Steve Dower97cded92015-09-08 19:12:51 -0700840 /* VisualStudio .NET 2005 does this properly */
841 if (buflen == 0 && errno == EINVAL) {
842 PyErr_SetString(PyExc_ValueError, "Invalid format string");
843 PyMem_Free(outbuf);
844 break;
845 }
Victor Stinner136ea492011-12-17 22:37:18 +0100846#endif
Steve Dower97cded92015-09-08 19:12:51 -0700847 if (buflen > 0 || i >= 256 * fmtlen) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000848 /* If the buffer is 256 times as long as the format,
849 it's probably not failing for lack of room!
850 More likely, the format yields an empty result,
851 e.g. an empty format, or %Z when the timezone
852 is unknown. */
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000853#ifdef HAVE_WCSFTIME
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000854 ret = PyUnicode_FromWideChar(outbuf, buflen);
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000855#else
Victor Stinner7ed7aea2018-01-15 10:45:49 +0100856 ret = PyUnicode_DecodeLocaleAndSize(outbuf, buflen, "surrogateescape");
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000857#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000858 PyMem_Free(outbuf);
Victor Stinnerb2904782010-09-29 10:34:19 +0000859 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000860 }
861 PyMem_Free(outbuf);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000862 }
Victor Stinnerb2904782010-09-29 10:34:19 +0000863#ifdef HAVE_WCSFTIME
864 PyMem_Free(format);
865#else
866 Py_DECREF(format);
867#endif
868 return ret;
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000869}
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000870
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000871#undef time_char
872#undef format_time
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000873PyDoc_STRVAR(strftime_doc,
Thomas Woutersfe385252001-01-19 23:16:56 +0000874"strftime(format[, tuple]) -> string\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000875\n\
876Convert a time tuple to a string according to a format specification.\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000877See the library reference manual for formatting codes. When the time tuple\n\
Alexander Belopolskycf774542012-10-02 18:39:16 -0400878is not present, current time as returned by localtime() is used.\n\
879\n" STRFTIME_FORMAT_CODES);
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000880#endif /* HAVE_STRFTIME */
881
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000882static PyObject *
883time_strptime(PyObject *self, PyObject *args)
884{
Victor Stinnerdbe28d22016-12-09 00:38:53 +0100885 PyObject *module, *func, *result;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200886 _Py_IDENTIFIER(_strptime_time);
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000887
Victor Stinnerdbe28d22016-12-09 00:38:53 +0100888 module = PyImport_ImportModuleNoBlock("_strptime");
889 if (!module)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000890 return NULL;
Victor Stinnerdbe28d22016-12-09 00:38:53 +0100891
892 func = _PyObject_GetAttrId(module, &PyId__strptime_time);
893 Py_DECREF(module);
894 if (!func) {
895 return NULL;
896 }
897
898 result = PyObject_Call(func, args, NULL);
899 Py_DECREF(func);
900 return result;
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000901}
902
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000903
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000904PyDoc_STRVAR(strptime_doc,
Brett Cannon20def8b2003-07-01 05:16:08 +0000905"strptime(string, format) -> struct_time\n\
Martin v. Löwisb3cfc1d2001-12-02 12:27:43 +0000906\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000907Parse a string to a time tuple according to a format specification.\n\
Alexander Belopolskycf774542012-10-02 18:39:16 -0400908See the library reference manual for formatting codes (same as\n\
909strftime()).\n\
910\n" STRFTIME_FORMAT_CODES);
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000911
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000912static PyObject *
913_asctime(struct tm *timeptr)
914{
915 /* Inspired by Open Group reference implementation available at
916 * http://pubs.opengroup.org/onlinepubs/009695399/functions/asctime.html */
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200917 static const char wday_name[7][4] = {
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000918 "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
919 };
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200920 static const char mon_name[12][4] = {
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000921 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
922 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
923 };
Victor Stinner499dfcf2011-03-21 13:26:24 +0100924 return PyUnicode_FromFormat(
925 "%s %s%3d %.2d:%.2d:%.2d %d",
926 wday_name[timeptr->tm_wday],
927 mon_name[timeptr->tm_mon],
928 timeptr->tm_mday, timeptr->tm_hour,
929 timeptr->tm_min, timeptr->tm_sec,
930 1900 + timeptr->tm_year);
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000931}
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000932
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000933static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000934time_asctime(PyObject *self, PyObject *args)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000935{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000936 PyObject *tup = NULL;
937 struct tm buf;
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000938
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000939 if (!PyArg_UnpackTuple(args, "asctime", 0, 1, &tup))
940 return NULL;
941 if (tup == NULL) {
942 time_t tt = time(NULL);
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -0400943 if (_PyTime_localtime(tt, &buf) != 0)
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100944 return NULL;
Oren Milman1d1d3e92017-08-20 18:35:36 +0300945 }
946 else if (!gettmarg(tup, &buf,
947 "iiiiiiiii;asctime(): illegal time tuple argument") ||
948 !checktm(&buf))
949 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000950 return NULL;
Oren Milman1d1d3e92017-08-20 18:35:36 +0300951 }
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000952 return _asctime(&buf);
Guido van Rossum9e90a671993-06-24 11:10:19 +0000953}
954
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000955PyDoc_STRVAR(asctime_doc,
Thomas Woutersfe385252001-01-19 23:16:56 +0000956"asctime([tuple]) -> string\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000957\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000958Convert a time tuple to a string, e.g. 'Sat Jun 06 16:26:11 1998'.\n\
959When the time tuple is not present, current time as returned by localtime()\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000960is used.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000961
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000962static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000963time_ctime(PyObject *self, PyObject *args)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000964{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000965 time_t tt;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100966 struct tm buf;
967 if (!parse_time_t_args(args, "|O:ctime", &tt))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000968 return NULL;
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -0400969 if (_PyTime_localtime(tt, &buf) != 0)
Alexander Belopolsky5da468f2011-01-04 17:15:52 +0000970 return NULL;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100971 return _asctime(&buf);
Guido van Rossum9e90a671993-06-24 11:10:19 +0000972}
973
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000974PyDoc_STRVAR(ctime_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000975"ctime(seconds) -> string\n\
976\n\
977Convert a time in seconds since the Epoch to a string in local time.\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000978This is equivalent to asctime(localtime(seconds)). When the time tuple is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000979not present, current time as returned by localtime() is used.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000980
Guido van Rossum60cd8131998-03-06 17:16:21 +0000981#ifdef HAVE_MKTIME
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000982static PyObject *
Victor Stinner4195b5c2012-02-08 23:03:19 +0100983time_mktime(PyObject *self, PyObject *tup)
Guido van Rossum234f9421993-06-17 12:35:49 +0000984{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000985 struct tm buf;
986 time_t tt;
Michael Felte2926b72018-12-28 14:57:37 +0100987#ifdef _AIX
988 time_t clk;
989 int year = buf.tm_year;
990 int delta_days = 0;
991#endif
992
Oren Milman1d1d3e92017-08-20 18:35:36 +0300993 if (!gettmarg(tup, &buf,
994 "iiiiiiiii;mktime(): illegal time tuple argument"))
995 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000996 return NULL;
Oren Milman1d1d3e92017-08-20 18:35:36 +0300997 }
Michael Felte2926b72018-12-28 14:57:37 +0100998#ifndef _AIX
999 buf.tm_wday = -1; /* sentinel; original value ignored */
1000 tt = mktime(&buf);
1001#else
Victor Stinner1ac42612014-02-21 09:27:17 +01001002 /* year < 1902 or year > 2037 */
Michael Felte2926b72018-12-28 14:57:37 +01001003 if ((buf.tm_year < 2) || (buf.tm_year > 137)) {
Victor Stinner1ac42612014-02-21 09:27:17 +01001004 /* Issue #19748: On AIX, mktime() doesn't report overflow error for
1005 * timestamp < -2^31 or timestamp > 2**31-1. */
1006 PyErr_SetString(PyExc_OverflowError,
1007 "mktime argument out of range");
1008 return NULL;
1009 }
Michael Felte2926b72018-12-28 14:57:37 +01001010 year = buf.tm_year;
1011 /* year < 1970 - adjust buf.tm_year into legal range */
1012 while (buf.tm_year < 70) {
1013 buf.tm_year += 4;
1014 delta_days -= (366 + (365 * 3));
1015 }
1016
1017 buf.tm_wday = -1;
1018 clk = mktime(&buf);
1019 buf.tm_year = year;
1020
1021 if ((buf.tm_wday != -1) && delta_days)
1022 buf.tm_wday = (buf.tm_wday + delta_days) % 7;
1023
1024 tt = clk + (delta_days * (24 * 3600));
Victor Stinner1ac42612014-02-21 09:27:17 +01001025#endif
Alexander Belopolskyb7d40d12011-01-11 01:21:25 +00001026 /* Return value of -1 does not necessarily mean an error, but tm_wday
Ezio Melotti13925002011-03-16 11:05:33 +02001027 * cannot remain set to -1 if mktime succeeded. */
Victor Stinner93037492013-06-25 22:54:35 +02001028 if (tt == (time_t)(-1)
Victor Stinner93037492013-06-25 22:54:35 +02001029 /* Return value of -1 does not necessarily mean an error, but
1030 * tm_wday cannot remain set to -1 if mktime succeeded. */
Michael Felte2926b72018-12-28 14:57:37 +01001031 && buf.tm_wday == -1)
Victor Stinner93037492013-06-25 22:54:35 +02001032 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001033 PyErr_SetString(PyExc_OverflowError,
1034 "mktime argument out of range");
1035 return NULL;
1036 }
Victor Stinner4195b5c2012-02-08 23:03:19 +01001037 return PyFloat_FromDouble((double)tt);
Guido van Rossum234f9421993-06-17 12:35:49 +00001038}
Guido van Rossum0ef577b1998-06-27 20:38:36 +00001039
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001040PyDoc_STRVAR(mktime_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +00001041"mktime(tuple) -> floating point number\n\
1042\n\
Alexander Belopolskyc142bba2012-06-13 22:15:26 -04001043Convert a time tuple in local time to seconds since the Epoch.\n\
1044Note that mktime(gmtime(0)) will not generally return zero for most\n\
1045time zones; instead the returned value will either be equal to that\n\
1046of the timezone or altzone attributes on the time module.");
Guido van Rossum60cd8131998-03-06 17:16:21 +00001047#endif /* HAVE_MKTIME */
Guido van Rossum234f9421993-06-17 12:35:49 +00001048
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001049#ifdef HAVE_WORKING_TZSET
Victor Stinner3bb150d2018-12-03 13:45:38 +01001050static int init_timezone(PyObject *module);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001051
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001052static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001053time_tzset(PyObject *self, PyObject *unused)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001054{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001055 PyObject* m;
Fred Drake9bb74322002-04-01 14:49:59 +00001056
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001057 m = PyImport_ImportModuleNoBlock("time");
1058 if (m == NULL) {
1059 return NULL;
1060 }
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001061
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001062 tzset();
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001063
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001064 /* Reset timezone, altzone, daylight and tzname */
Victor Stinner3bb150d2018-12-03 13:45:38 +01001065 if (init_timezone(m) < 0) {
Victor Stinner503ce5c2018-12-01 00:39:36 +01001066 return NULL;
1067 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001068 Py_DECREF(m);
Victor Stinner2ff51b82013-07-17 21:42:45 +02001069 if (PyErr_Occurred())
1070 return NULL;
Tim Peters1b6f7a92004-06-20 02:50:16 +00001071
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001072 Py_RETURN_NONE;
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001073}
1074
1075PyDoc_STRVAR(tzset_doc,
R. David Murray4d55bf92010-12-14 00:55:46 +00001076"tzset()\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001077\n\
1078Initialize, or reinitialize, the local timezone to the value stored in\n\
1079os.environ['TZ']. The TZ environment variable should be specified in\n\
Neal Norwitzdc8e1942004-07-20 22:34:37 +00001080standard Unix timezone format as documented in the tzset man page\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001081(eg. 'US/Eastern', 'Europe/Amsterdam'). Unknown timezones will silently\n\
1082fall back to UTC. If the TZ environment variable is not set, the local\n\
1083timezone is set to the systems best guess of wallclock time.\n\
1084Changing the TZ environment variable without calling tzset *may* change\n\
1085the local timezone used by methods such as localtime, but this behaviour\n\
1086should not be relied on.");
1087#endif /* HAVE_WORKING_TZSET */
1088
Victor Stinnerae586492014-09-02 23:18:25 +02001089static PyObject *
Victor Stinnerec895392012-04-29 02:41:27 +02001090time_monotonic(PyObject *self, PyObject *unused)
Victor Stinner071eca32012-03-15 01:17:09 +01001091{
Victor Stinnerc29b5852017-11-02 07:28:27 -07001092 _PyTime_t t = _PyTime_GetMonotonicClock();
1093 return _PyFloat_FromPyTime(t);
Victor Stinner071eca32012-03-15 01:17:09 +01001094}
1095
Victor Stinnerec895392012-04-29 02:41:27 +02001096PyDoc_STRVAR(monotonic_doc,
1097"monotonic() -> float\n\
Victor Stinner8b302012012-02-07 23:29:46 +01001098\n\
Victor Stinnerec895392012-04-29 02:41:27 +02001099Monotonic clock, cannot go backward.");
Victor Stinnerec919cc2012-03-15 00:58:32 +01001100
Victor Stinnerec895392012-04-29 02:41:27 +02001101static PyObject *
Victor Stinnerc29b5852017-11-02 07:28:27 -07001102time_monotonic_ns(PyObject *self, PyObject *unused)
1103{
1104 _PyTime_t t = _PyTime_GetMonotonicClock();
1105 return _PyTime_AsNanosecondsObject(t);
1106}
1107
1108PyDoc_STRVAR(monotonic_ns_doc,
1109"monotonic_ns() -> int\n\
1110\n\
1111Monotonic clock, cannot go backward, as nanoseconds.");
1112
1113static PyObject *
Victor Stinnerec895392012-04-29 02:41:27 +02001114time_perf_counter(PyObject *self, PyObject *unused)
1115{
1116 return perf_counter(NULL);
1117}
1118
1119PyDoc_STRVAR(perf_counter_doc,
1120"perf_counter() -> float\n\
1121\n\
1122Performance counter for benchmarking.");
1123
Victor Stinnerc29b5852017-11-02 07:28:27 -07001124static PyObject *
1125time_perf_counter_ns(PyObject *self, PyObject *unused)
1126{
1127 _PyTime_t t = _PyTime_GetPerfCounter();
1128 return _PyTime_AsNanosecondsObject(t);
1129}
1130
1131PyDoc_STRVAR(perf_counter_ns_doc,
1132"perf_counter_ns() -> int\n\
1133\n\
1134Performance counter for benchmarking as nanoseconds.");
1135
1136static int
1137_PyTime_GetProcessTimeWithInfo(_PyTime_t *tp, _Py_clock_info_t *info)
Victor Stinnerec895392012-04-29 02:41:27 +02001138{
1139#if defined(MS_WINDOWS)
1140 HANDLE process;
1141 FILETIME creation_time, exit_time, kernel_time, user_time;
1142 ULARGE_INTEGER large;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001143 _PyTime_t ktime, utime, t;
Victor Stinnerec895392012-04-29 02:41:27 +02001144 BOOL ok;
1145
1146 process = GetCurrentProcess();
Victor Stinnerc29b5852017-11-02 07:28:27 -07001147 ok = GetProcessTimes(process, &creation_time, &exit_time,
1148 &kernel_time, &user_time);
1149 if (!ok) {
1150 PyErr_SetFromWindowsErr(0);
1151 return -1;
1152 }
Victor Stinnerec895392012-04-29 02:41:27 +02001153
Victor Stinnerec895392012-04-29 02:41:27 +02001154 if (info) {
1155 info->implementation = "GetProcessTimes()";
1156 info->resolution = 1e-7;
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001157 info->monotonic = 1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001158 info->adjustable = 0;
Victor Stinnerec895392012-04-29 02:41:27 +02001159 }
Victor Stinnerc29b5852017-11-02 07:28:27 -07001160
1161 large.u.LowPart = kernel_time.dwLowDateTime;
1162 large.u.HighPart = kernel_time.dwHighDateTime;
1163 ktime = large.QuadPart;
1164
1165 large.u.LowPart = user_time.dwLowDateTime;
1166 large.u.HighPart = user_time.dwHighDateTime;
1167 utime = large.QuadPart;
1168
1169 /* ktime and utime have a resolution of 100 nanoseconds */
1170 t = _PyTime_FromNanoseconds((ktime + utime) * 100);
1171 *tp = t;
1172 return 0;
Victor Stinnerec895392012-04-29 02:41:27 +02001173#else
1174
Victor Stinnerc29b5852017-11-02 07:28:27 -07001175 /* clock_gettime */
Victor Stinnerec895392012-04-29 02:41:27 +02001176#if defined(HAVE_CLOCK_GETTIME) \
1177 && (defined(CLOCK_PROCESS_CPUTIME_ID) || defined(CLOCK_PROF))
Victor Stinnerc29b5852017-11-02 07:28:27 -07001178 struct timespec ts;
Victor Stinnerec895392012-04-29 02:41:27 +02001179#ifdef CLOCK_PROF
1180 const clockid_t clk_id = CLOCK_PROF;
1181 const char *function = "clock_gettime(CLOCK_PROF)";
1182#else
1183 const clockid_t clk_id = CLOCK_PROCESS_CPUTIME_ID;
1184 const char *function = "clock_gettime(CLOCK_PROCESS_CPUTIME_ID)";
1185#endif
1186
Victor Stinnerc29b5852017-11-02 07:28:27 -07001187 if (clock_gettime(clk_id, &ts) == 0) {
Victor Stinnerec895392012-04-29 02:41:27 +02001188 if (info) {
1189 struct timespec res;
1190 info->implementation = function;
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001191 info->monotonic = 1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001192 info->adjustable = 0;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001193 if (clock_getres(clk_id, &res)) {
1194 PyErr_SetFromErrno(PyExc_OSError);
1195 return -1;
1196 }
1197 info->resolution = res.tv_sec + res.tv_nsec * 1e-9;
Victor Stinnerec895392012-04-29 02:41:27 +02001198 }
Victor Stinnerc29b5852017-11-02 07:28:27 -07001199
1200 if (_PyTime_FromTimespec(tp, &ts) < 0) {
1201 return -1;
1202 }
1203 return 0;
Victor Stinnerec895392012-04-29 02:41:27 +02001204 }
1205#endif
1206
Victor Stinnerc29b5852017-11-02 07:28:27 -07001207 /* getrusage(RUSAGE_SELF) */
Victor Stinnerec895392012-04-29 02:41:27 +02001208#if defined(HAVE_SYS_RESOURCE_H)
Victor Stinnerc29b5852017-11-02 07:28:27 -07001209 struct rusage ru;
1210
Victor Stinnerec895392012-04-29 02:41:27 +02001211 if (getrusage(RUSAGE_SELF, &ru) == 0) {
Victor Stinnerc29b5852017-11-02 07:28:27 -07001212 _PyTime_t utime, stime;
1213
Victor Stinnerec895392012-04-29 02:41:27 +02001214 if (info) {
1215 info->implementation = "getrusage(RUSAGE_SELF)";
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001216 info->monotonic = 1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001217 info->adjustable = 0;
Victor Stinnerec895392012-04-29 02:41:27 +02001218 info->resolution = 1e-6;
1219 }
Victor Stinnerc29b5852017-11-02 07:28:27 -07001220
1221 if (_PyTime_FromTimeval(&utime, &ru.ru_utime) < 0) {
1222 return -1;
1223 }
1224 if (_PyTime_FromTimeval(&stime, &ru.ru_stime) < 0) {
1225 return -1;
1226 }
1227
1228 _PyTime_t total = utime + utime;
1229 *tp = total;
1230 return 0;
Victor Stinnerec895392012-04-29 02:41:27 +02001231 }
1232#endif
1233
Victor Stinnerc29b5852017-11-02 07:28:27 -07001234 /* times() */
Victor Stinnerec895392012-04-29 02:41:27 +02001235#ifdef HAVE_TIMES
Victor Stinnerc29b5852017-11-02 07:28:27 -07001236 struct tms t;
1237
Victor Stinnerec895392012-04-29 02:41:27 +02001238 if (times(&t) != (clock_t)-1) {
Victor Stinnerc29b5852017-11-02 07:28:27 -07001239 static long ticks_per_second = -1;
Victor Stinnerec895392012-04-29 02:41:27 +02001240
1241 if (ticks_per_second == -1) {
Victor Stinnerc29b5852017-11-02 07:28:27 -07001242 long freq;
Victor Stinnerec895392012-04-29 02:41:27 +02001243#if defined(HAVE_SYSCONF) && defined(_SC_CLK_TCK)
Victor Stinnerc29b5852017-11-02 07:28:27 -07001244 freq = sysconf(_SC_CLK_TCK);
1245 if (freq < 1) {
1246 freq = -1;
1247 }
Victor Stinnerec895392012-04-29 02:41:27 +02001248#elif defined(HZ)
Victor Stinnerc29b5852017-11-02 07:28:27 -07001249 freq = HZ;
Victor Stinnerec895392012-04-29 02:41:27 +02001250#else
Victor Stinnerc29b5852017-11-02 07:28:27 -07001251 freq = 60; /* magic fallback value; may be bogus */
Victor Stinnerec895392012-04-29 02:41:27 +02001252#endif
Victor Stinnerc29b5852017-11-02 07:28:27 -07001253
1254 if (freq != -1) {
1255 /* check that _PyTime_MulDiv(t, SEC_TO_NS, ticks_per_second)
1256 cannot overflow below */
Serhiy Storchakabfe4fd52018-02-09 17:31:26 +02001257#if LONG_MAX > _PyTime_MAX / SEC_TO_NS
Victor Stinnerc29b5852017-11-02 07:28:27 -07001258 if ((_PyTime_t)freq > _PyTime_MAX / SEC_TO_NS) {
1259 PyErr_SetString(PyExc_OverflowError,
1260 "_SC_CLK_TCK is too large");
1261 return -1;
1262 }
Serhiy Storchakabfe4fd52018-02-09 17:31:26 +02001263#endif
Victor Stinnerc29b5852017-11-02 07:28:27 -07001264
1265 ticks_per_second = freq;
1266 }
Victor Stinnerec895392012-04-29 02:41:27 +02001267 }
1268
1269 if (ticks_per_second != -1) {
Victor Stinnerec895392012-04-29 02:41:27 +02001270 if (info) {
1271 info->implementation = "times()";
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001272 info->monotonic = 1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001273 info->adjustable = 0;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001274 info->resolution = 1.0 / (double)ticks_per_second;
Victor Stinnerec895392012-04-29 02:41:27 +02001275 }
Victor Stinnerc29b5852017-11-02 07:28:27 -07001276
1277 _PyTime_t total;
1278 total = _PyTime_MulDiv(t.tms_utime, SEC_TO_NS, ticks_per_second);
1279 total += _PyTime_MulDiv(t.tms_stime, SEC_TO_NS, ticks_per_second);
1280 *tp = total;
1281 return 0;
Victor Stinnerec895392012-04-29 02:41:27 +02001282 }
1283 }
1284#endif
1285
Victor Stinnerc29b5852017-11-02 07:28:27 -07001286 /* clock */
Victor Stinner53e22bf2016-07-08 17:55:01 +02001287 /* Currently, Python 3 requires clock() to build: see issue #22624 */
Victor Stinnerc29b5852017-11-02 07:28:27 -07001288 return _PyTime_GetClockWithInfo(tp, info);
Victor Stinnerec895392012-04-29 02:41:27 +02001289#endif
1290}
1291
1292static PyObject *
1293time_process_time(PyObject *self, PyObject *unused)
1294{
Victor Stinnerc29b5852017-11-02 07:28:27 -07001295 _PyTime_t t;
1296 if (_PyTime_GetProcessTimeWithInfo(&t, NULL) < 0) {
1297 return NULL;
1298 }
1299 return _PyFloat_FromPyTime(t);
Victor Stinnerec895392012-04-29 02:41:27 +02001300}
1301
1302PyDoc_STRVAR(process_time_doc,
1303"process_time() -> float\n\
1304\n\
1305Process time for profiling: sum of the kernel and user-space CPU time.");
1306
Victor Stinnerc29b5852017-11-02 07:28:27 -07001307static PyObject *
1308time_process_time_ns(PyObject *self, PyObject *unused)
1309{
1310 _PyTime_t t;
1311 if (_PyTime_GetProcessTimeWithInfo(&t, NULL) < 0) {
1312 return NULL;
1313 }
1314 return _PyTime_AsNanosecondsObject(t);
1315}
1316
1317PyDoc_STRVAR(process_time_ns_doc,
1318"process_time() -> int\n\
1319\n\
1320Process time for profiling as nanoseconds:\n\
1321sum of the kernel and user-space CPU time.");
1322
Victor Stinnerec895392012-04-29 02:41:27 +02001323
Antoine Pitrou4bd41c92017-11-15 22:52:21 +01001324#if defined(MS_WINDOWS)
1325#define HAVE_THREAD_TIME
1326static int
1327_PyTime_GetThreadTimeWithInfo(_PyTime_t *tp, _Py_clock_info_t *info)
1328{
1329 HANDLE thread;
1330 FILETIME creation_time, exit_time, kernel_time, user_time;
1331 ULARGE_INTEGER large;
1332 _PyTime_t ktime, utime, t;
1333 BOOL ok;
1334
1335 thread = GetCurrentThread();
1336 ok = GetThreadTimes(thread, &creation_time, &exit_time,
1337 &kernel_time, &user_time);
1338 if (!ok) {
1339 PyErr_SetFromWindowsErr(0);
1340 return -1;
1341 }
1342
1343 if (info) {
1344 info->implementation = "GetThreadTimes()";
1345 info->resolution = 1e-7;
1346 info->monotonic = 1;
1347 info->adjustable = 0;
1348 }
1349
1350 large.u.LowPart = kernel_time.dwLowDateTime;
1351 large.u.HighPart = kernel_time.dwHighDateTime;
1352 ktime = large.QuadPart;
1353
1354 large.u.LowPart = user_time.dwLowDateTime;
1355 large.u.HighPart = user_time.dwHighDateTime;
1356 utime = large.QuadPart;
1357
1358 /* ktime and utime have a resolution of 100 nanoseconds */
1359 t = _PyTime_FromNanoseconds((ktime + utime) * 100);
1360 *tp = t;
1361 return 0;
1362}
1363
1364#elif defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_PROCESS_CPUTIME_ID)
1365#define HAVE_THREAD_TIME
1366static int
1367_PyTime_GetThreadTimeWithInfo(_PyTime_t *tp, _Py_clock_info_t *info)
1368{
1369 struct timespec ts;
1370 const clockid_t clk_id = CLOCK_THREAD_CPUTIME_ID;
1371 const char *function = "clock_gettime(CLOCK_THREAD_CPUTIME_ID)";
1372
1373 if (clock_gettime(clk_id, &ts)) {
1374 PyErr_SetFromErrno(PyExc_OSError);
1375 return -1;
1376 }
1377 if (info) {
1378 struct timespec res;
1379 info->implementation = function;
1380 info->monotonic = 1;
1381 info->adjustable = 0;
1382 if (clock_getres(clk_id, &res)) {
1383 PyErr_SetFromErrno(PyExc_OSError);
1384 return -1;
1385 }
1386 info->resolution = res.tv_sec + res.tv_nsec * 1e-9;
1387 }
1388
1389 if (_PyTime_FromTimespec(tp, &ts) < 0) {
1390 return -1;
1391 }
1392 return 0;
1393}
1394#endif
1395
1396#ifdef HAVE_THREAD_TIME
1397static PyObject *
1398time_thread_time(PyObject *self, PyObject *unused)
1399{
1400 _PyTime_t t;
1401 if (_PyTime_GetThreadTimeWithInfo(&t, NULL) < 0) {
1402 return NULL;
1403 }
1404 return _PyFloat_FromPyTime(t);
1405}
1406
1407PyDoc_STRVAR(thread_time_doc,
1408"thread_time() -> float\n\
1409\n\
1410Thread time for profiling: sum of the kernel and user-space CPU time.");
1411
1412static PyObject *
1413time_thread_time_ns(PyObject *self, PyObject *unused)
1414{
1415 _PyTime_t t;
1416 if (_PyTime_GetThreadTimeWithInfo(&t, NULL) < 0) {
1417 return NULL;
1418 }
1419 return _PyTime_AsNanosecondsObject(t);
1420}
1421
1422PyDoc_STRVAR(thread_time_ns_doc,
1423"thread_time() -> int\n\
1424\n\
1425Thread time for profiling as nanoseconds:\n\
1426sum of the kernel and user-space CPU time.");
1427#endif
1428
1429
Victor Stinnerec895392012-04-29 02:41:27 +02001430static PyObject *
1431time_get_clock_info(PyObject *self, PyObject *args)
1432{
1433 char *name;
Victor Stinnerec895392012-04-29 02:41:27 +02001434 _Py_clock_info_t info;
Victor Stinnerbda4b882012-06-12 22:11:44 +02001435 PyObject *obj = NULL, *dict, *ns;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001436 _PyTime_t t;
Victor Stinnerec895392012-04-29 02:41:27 +02001437
Victor Stinnerc29b5852017-11-02 07:28:27 -07001438 if (!PyArg_ParseTuple(args, "s:get_clock_info", &name)) {
Victor Stinnerec895392012-04-29 02:41:27 +02001439 return NULL;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001440 }
Victor Stinnerec895392012-04-29 02:41:27 +02001441
1442#ifdef Py_DEBUG
1443 info.implementation = NULL;
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001444 info.monotonic = -1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001445 info.adjustable = -1;
Victor Stinnerec895392012-04-29 02:41:27 +02001446 info.resolution = -1.0;
1447#else
1448 info.implementation = "";
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001449 info.monotonic = 0;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001450 info.adjustable = 0;
Victor Stinnerec895392012-04-29 02:41:27 +02001451 info.resolution = 1.0;
1452#endif
1453
Victor Stinnerc29b5852017-11-02 07:28:27 -07001454 if (strcmp(name, "time") == 0) {
1455 if (_PyTime_GetSystemClockWithInfo(&t, &info) < 0) {
1456 return NULL;
1457 }
1458 }
Victor Stinnerec895392012-04-29 02:41:27 +02001459#ifdef PYCLOCK
Victor Stinnerc29b5852017-11-02 07:28:27 -07001460 else if (strcmp(name, "clock") == 0) {
Victor Stinnerec895392012-04-29 02:41:27 +02001461 obj = pyclock(&info);
Victor Stinnerc29b5852017-11-02 07:28:27 -07001462 if (obj == NULL) {
1463 return NULL;
1464 }
1465 Py_DECREF(obj);
1466 }
Victor Stinnerec895392012-04-29 02:41:27 +02001467#endif
Victor Stinnerc29b5852017-11-02 07:28:27 -07001468 else if (strcmp(name, "monotonic") == 0) {
1469 if (_PyTime_GetMonotonicClockWithInfo(&t, &info) < 0) {
1470 return NULL;
1471 }
1472 }
1473 else if (strcmp(name, "perf_counter") == 0) {
1474 if (_PyTime_GetPerfCounterWithInfo(&t, &info) < 0) {
1475 return NULL;
1476 }
1477 }
1478 else if (strcmp(name, "process_time") == 0) {
1479 if (_PyTime_GetProcessTimeWithInfo(&t, &info) < 0) {
1480 return NULL;
1481 }
1482 }
Antoine Pitrou4bd41c92017-11-15 22:52:21 +01001483#ifdef HAVE_THREAD_TIME
1484 else if (strcmp(name, "thread_time") == 0) {
1485 if (_PyTime_GetThreadTimeWithInfo(&t, &info) < 0) {
1486 return NULL;
1487 }
1488 }
1489#endif
Victor Stinnerec895392012-04-29 02:41:27 +02001490 else {
1491 PyErr_SetString(PyExc_ValueError, "unknown clock");
1492 return NULL;
1493 }
Victor Stinnerec895392012-04-29 02:41:27 +02001494
Victor Stinnerbda4b882012-06-12 22:11:44 +02001495 dict = PyDict_New();
Victor Stinnerc29b5852017-11-02 07:28:27 -07001496 if (dict == NULL) {
Victor Stinnerec895392012-04-29 02:41:27 +02001497 return NULL;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001498 }
Victor Stinnerec895392012-04-29 02:41:27 +02001499
1500 assert(info.implementation != NULL);
1501 obj = PyUnicode_FromString(info.implementation);
Victor Stinnerc29b5852017-11-02 07:28:27 -07001502 if (obj == NULL) {
Victor Stinnerec895392012-04-29 02:41:27 +02001503 goto error;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001504 }
1505 if (PyDict_SetItemString(dict, "implementation", obj) == -1) {
Victor Stinnerbda4b882012-06-12 22:11:44 +02001506 goto error;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001507 }
Victor Stinnerbda4b882012-06-12 22:11:44 +02001508 Py_CLEAR(obj);
Victor Stinnerec895392012-04-29 02:41:27 +02001509
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001510 assert(info.monotonic != -1);
1511 obj = PyBool_FromLong(info.monotonic);
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, "monotonic", 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
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001520 assert(info.adjustable != -1);
1521 obj = PyBool_FromLong(info.adjustable);
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, "adjustable", 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
1530 assert(info.resolution > 0.0);
1531 assert(info.resolution <= 1.0);
1532 obj = PyFloat_FromDouble(info.resolution);
Victor Stinnerc29b5852017-11-02 07:28:27 -07001533 if (obj == NULL) {
Victor Stinnerec895392012-04-29 02:41:27 +02001534 goto error;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001535 }
1536 if (PyDict_SetItemString(dict, "resolution", obj) == -1) {
Victor Stinnerbda4b882012-06-12 22:11:44 +02001537 goto error;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001538 }
Victor Stinnerbda4b882012-06-12 22:11:44 +02001539 Py_CLEAR(obj);
Victor Stinnerec895392012-04-29 02:41:27 +02001540
Victor Stinnerbda4b882012-06-12 22:11:44 +02001541 ns = _PyNamespace_New(dict);
1542 Py_DECREF(dict);
1543 return ns;
Victor Stinnerec895392012-04-29 02:41:27 +02001544
1545error:
Victor Stinnerbda4b882012-06-12 22:11:44 +02001546 Py_DECREF(dict);
1547 Py_XDECREF(obj);
Victor Stinnerec895392012-04-29 02:41:27 +02001548 return NULL;
1549}
1550
1551PyDoc_STRVAR(get_clock_info_doc,
1552"get_clock_info(name: str) -> dict\n\
1553\n\
1554Get information of the specified clock.");
Victor Stinner8b302012012-02-07 23:29:46 +01001555
Benjamin Petersonc510c6b2018-09-20 19:52:18 -07001556#ifndef HAVE_DECL_TZNAME
Victor Stinner1fb399b2018-09-17 13:56:17 -07001557static void
1558get_zone(char *zone, int n, struct tm *p)
1559{
1560#ifdef HAVE_STRUCT_TM_TM_ZONE
1561 strncpy(zone, p->tm_zone ? p->tm_zone : " ", n);
1562#else
1563 tzset();
1564 strftime(zone, n, "%Z", p);
1565#endif
1566}
1567
Victor Stinner503ce5c2018-12-01 00:39:36 +01001568static time_t
Victor Stinner1fb399b2018-09-17 13:56:17 -07001569get_gmtoff(time_t t, struct tm *p)
1570{
1571#ifdef HAVE_STRUCT_TM_TM_ZONE
1572 return p->tm_gmtoff;
1573#else
1574 return timegm(p) - t;
1575#endif
1576}
Benjamin Petersonc510c6b2018-09-20 19:52:18 -07001577#endif // !HAVE_DECL_TZNAME
Victor Stinner1fb399b2018-09-17 13:56:17 -07001578
Victor Stinner503ce5c2018-12-01 00:39:36 +01001579static int
Victor Stinner3bb150d2018-12-03 13:45:38 +01001580init_timezone(PyObject *m)
Victor Stinner503ce5c2018-12-01 00:39:36 +01001581{
1582 assert(!PyErr_Occurred());
1583
Martin v. Löwis1a214512008-06-11 05:26:20 +00001584 /* This code moved from PyInit_time wholesale to allow calling it from
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001585 time_tzset. In the future, some parts of it can be moved back
1586 (for platforms that don't HAVE_WORKING_TZSET, when we know what they
1587 are), and the extraneous calls to tzset(3) should be removed.
1588 I haven't done this yet, as I don't want to change this code as
1589 little as possible when introducing the time.tzset and time.tzsetwall
1590 methods. This should simply be a method of doing the following once,
1591 at the top of this function and removing the call to tzset() from
1592 time_tzset():
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001593
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001594 #ifdef HAVE_TZSET
1595 tzset()
1596 #endif
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001597
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001598 And I'm lazy and hate C so nyer.
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001599 */
Benjamin Petersonc510c6b2018-09-20 19:52:18 -07001600#ifdef HAVE_DECL_TZNAME
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001601 PyObject *otz0, *otz1;
1602 tzset();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001603 PyModule_AddIntConstant(m, "timezone", timezone);
Guido van Rossumb6775db1994-08-01 11:34:53 +00001604#ifdef HAVE_ALTZONE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001605 PyModule_AddIntConstant(m, "altzone", altzone);
Guido van Rossumb6775db1994-08-01 11:34:53 +00001606#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001607 PyModule_AddIntConstant(m, "altzone", timezone-3600);
Guido van Rossumb6775db1994-08-01 11:34:53 +00001608#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001609 PyModule_AddIntConstant(m, "daylight", daylight);
Victor Stinner7ed7aea2018-01-15 10:45:49 +01001610 otz0 = PyUnicode_DecodeLocale(tzname[0], "surrogateescape");
Benjamin Petersonc510c6b2018-09-20 19:52:18 -07001611 if (otz0 == NULL) {
Victor Stinnerab661492018-12-03 12:02:43 +01001612 return -1;
Victor Stinner1fb399b2018-09-17 13:56:17 -07001613 }
Benjamin Petersonc510c6b2018-09-20 19:52:18 -07001614 otz1 = PyUnicode_DecodeLocale(tzname[1], "surrogateescape");
1615 if (otz1 == NULL) {
1616 Py_DECREF(otz0);
Victor Stinnerab661492018-12-03 12:02:43 +01001617 return -1;
Benjamin Petersonc510c6b2018-09-20 19:52:18 -07001618 }
1619 PyObject *tzname_obj = Py_BuildValue("(NN)", otz0, otz1);
Victor Stinnerab661492018-12-03 12:02:43 +01001620 if (tzname_obj == NULL) {
1621 return -1;
1622 }
Benjamin Petersonc510c6b2018-09-20 19:52:18 -07001623 PyModule_AddObject(m, "tzname", tzname_obj);
1624#else // !HAVE_DECL_TZNAME
1625 static const time_t YEAR = (365 * 24 + 6) * 3600;
1626 time_t t;
1627 struct tm p;
Victor Stinner503ce5c2018-12-01 00:39:36 +01001628 time_t janzone_t, julyzone_t;
Benjamin Petersonc510c6b2018-09-20 19:52:18 -07001629 char janname[10], julyname[10];
1630 t = (time((time_t *)0) / YEAR) * YEAR;
1631 _PyTime_localtime(t, &p);
1632 get_zone(janname, 9, &p);
Victor Stinner503ce5c2018-12-01 00:39:36 +01001633 janzone_t = -get_gmtoff(t, &p);
Benjamin Petersonc510c6b2018-09-20 19:52:18 -07001634 janname[9] = '\0';
1635 t += YEAR/2;
1636 _PyTime_localtime(t, &p);
1637 get_zone(julyname, 9, &p);
Victor Stinner503ce5c2018-12-01 00:39:36 +01001638 julyzone_t = -get_gmtoff(t, &p);
Benjamin Petersonc510c6b2018-09-20 19:52:18 -07001639 julyname[9] = '\0';
1640
Victor Stinner503ce5c2018-12-01 00:39:36 +01001641 /* Sanity check, don't check for the validity of timezones.
1642 In practice, it should be more in range -12 hours .. +14 hours. */
1643#define MAX_TIMEZONE (48 * 3600)
1644 if (janzone_t < -MAX_TIMEZONE || janzone_t > MAX_TIMEZONE
1645 || julyzone_t < -MAX_TIMEZONE || julyzone_t > MAX_TIMEZONE)
1646 {
1647 PyErr_SetString(PyExc_RuntimeError, "invalid GMT offset");
1648 return -1;
1649 }
1650 int janzone = (int)janzone_t;
1651 int julyzone = (int)julyzone_t;
1652
Benjamin Petersonc510c6b2018-09-20 19:52:18 -07001653 PyObject *tzname_obj;
1654 if (janzone < julyzone) {
1655 /* DST is reversed in the southern hemisphere */
1656 PyModule_AddIntConstant(m, "timezone", julyzone);
1657 PyModule_AddIntConstant(m, "altzone", janzone);
1658 PyModule_AddIntConstant(m, "daylight", janzone != julyzone);
1659 tzname_obj = Py_BuildValue("(zz)", julyname, janname);
1660 } else {
1661 PyModule_AddIntConstant(m, "timezone", janzone);
1662 PyModule_AddIntConstant(m, "altzone", julyzone);
1663 PyModule_AddIntConstant(m, "daylight", janzone != julyzone);
1664 tzname_obj = Py_BuildValue("(zz)", janname, julyname);
1665 }
Victor Stinner503ce5c2018-12-01 00:39:36 +01001666 if (tzname_obj == NULL) {
1667 return -1;
1668 }
Benjamin Petersonc510c6b2018-09-20 19:52:18 -07001669 PyModule_AddObject(m, "tzname", tzname_obj);
1670#endif // !HAVE_DECL_TZNAME
Victor Stinner503ce5c2018-12-01 00:39:36 +01001671
1672 if (PyErr_Occurred()) {
1673 return -1;
1674 }
1675 return 0;
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001676}
1677
1678
1679static PyMethodDef time_methods[] = {
Victor Stinner4195b5c2012-02-08 23:03:19 +01001680 {"time", time_time, METH_NOARGS, time_doc},
Victor Stinnerc29b5852017-11-02 07:28:27 -07001681 {"time_ns", time_time_ns, METH_NOARGS, time_ns_doc},
Victor Stinnerec895392012-04-29 02:41:27 +02001682#ifdef PYCLOCK
Victor Stinner4195b5c2012-02-08 23:03:19 +01001683 {"clock", time_clock, METH_NOARGS, clock_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001684#endif
Victor Stinnere0be4232011-10-25 13:06:09 +02001685#ifdef HAVE_CLOCK_GETTIME
Victor Stinner4195b5c2012-02-08 23:03:19 +01001686 {"clock_gettime", time_clock_gettime, METH_VARARGS, clock_gettime_doc},
Victor Stinnerc29b5852017-11-02 07:28:27 -07001687 {"clock_gettime_ns",time_clock_gettime_ns, METH_VARARGS, clock_gettime_ns_doc},
Benjamin Peterson37098cd2016-09-13 22:55:09 -07001688#endif
1689#ifdef HAVE_CLOCK_SETTIME
Victor Stinner30d79472012-04-03 00:45:07 +02001690 {"clock_settime", time_clock_settime, METH_VARARGS, clock_settime_doc},
Victor Stinnerc29b5852017-11-02 07:28:27 -07001691 {"clock_settime_ns",time_clock_settime_ns, METH_VARARGS, clock_settime_ns_doc},
Benjamin Peterson37098cd2016-09-13 22:55:09 -07001692#endif
1693#ifdef HAVE_CLOCK_GETRES
Victor Stinner4195b5c2012-02-08 23:03:19 +01001694 {"clock_getres", time_clock_getres, METH_VARARGS, clock_getres_doc},
Victor Stinnere0be4232011-10-25 13:06:09 +02001695#endif
pdoxe14679c2017-10-05 00:01:56 -07001696#ifdef HAVE_PTHREAD_GETCPUCLOCKID
1697 {"pthread_getcpuclockid", time_pthread_getcpuclockid, METH_VARARGS, pthread_getcpuclockid_doc},
1698#endif
Victor Stinnercb29f012015-03-27 13:31:18 +01001699 {"sleep", time_sleep, METH_O, sleep_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001700 {"gmtime", time_gmtime, METH_VARARGS, gmtime_doc},
1701 {"localtime", time_localtime, METH_VARARGS, localtime_doc},
1702 {"asctime", time_asctime, METH_VARARGS, asctime_doc},
1703 {"ctime", time_ctime, METH_VARARGS, ctime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001704#ifdef HAVE_MKTIME
Victor Stinner4195b5c2012-02-08 23:03:19 +01001705 {"mktime", time_mktime, METH_O, mktime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001706#endif
1707#ifdef HAVE_STRFTIME
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001708 {"strftime", time_strftime, METH_VARARGS, strftime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001709#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001710 {"strptime", time_strptime, METH_VARARGS, strptime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001711#ifdef HAVE_WORKING_TZSET
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001712 {"tzset", time_tzset, METH_NOARGS, tzset_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001713#endif
Victor Stinnerec895392012-04-29 02:41:27 +02001714 {"monotonic", time_monotonic, METH_NOARGS, monotonic_doc},
Victor Stinnerc29b5852017-11-02 07:28:27 -07001715 {"monotonic_ns", time_monotonic_ns, METH_NOARGS, monotonic_ns_doc},
Victor Stinnerec895392012-04-29 02:41:27 +02001716 {"process_time", time_process_time, METH_NOARGS, process_time_doc},
Victor Stinnerc29b5852017-11-02 07:28:27 -07001717 {"process_time_ns", time_process_time_ns, METH_NOARGS, process_time_ns_doc},
Antoine Pitrou4bd41c92017-11-15 22:52:21 +01001718#ifdef HAVE_THREAD_TIME
1719 {"thread_time", time_thread_time, METH_NOARGS, thread_time_doc},
1720 {"thread_time_ns", time_thread_time_ns, METH_NOARGS, thread_time_ns_doc},
1721#endif
Victor Stinnerec895392012-04-29 02:41:27 +02001722 {"perf_counter", time_perf_counter, METH_NOARGS, perf_counter_doc},
Victor Stinnerc29b5852017-11-02 07:28:27 -07001723 {"perf_counter_ns", time_perf_counter_ns, METH_NOARGS, perf_counter_ns_doc},
Victor Stinnerec895392012-04-29 02:41:27 +02001724 {"get_clock_info", time_get_clock_info, METH_VARARGS, get_clock_info_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001725 {NULL, NULL} /* sentinel */
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001726};
1727
1728
1729PyDoc_STRVAR(module_doc,
1730"This module provides various functions to manipulate time values.\n\
1731\n\
1732There are two standard representations of time. One is the number\n\
1733of seconds since the Epoch, in UTC (a.k.a. GMT). It may be an integer\n\
1734or a floating point number (to represent fractions of seconds).\n\
1735The Epoch is system-defined; on Unix, it is generally January 1st, 1970.\n\
1736The actual value can be retrieved by calling gmtime(0).\n\
1737\n\
1738The other representation is a tuple of 9 integers giving local time.\n\
1739The tuple items are:\n\
Alexander Belopolsky03163ac2011-05-02 12:20:52 -04001740 year (including century, e.g. 1998)\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001741 month (1-12)\n\
1742 day (1-31)\n\
1743 hours (0-23)\n\
1744 minutes (0-59)\n\
1745 seconds (0-59)\n\
1746 weekday (0-6, Monday is 0)\n\
1747 Julian day (day in the year, 1-366)\n\
1748 DST (Daylight Savings Time) flag (-1, 0 or 1)\n\
1749If the DST flag is 0, the time is given in the regular time zone;\n\
1750if it is 1, the time is given in the DST time zone;\n\
Cheryl Sabella703ff382017-10-11 09:29:14 -04001751if it is -1, mktime() should guess based on the date and time.\n");
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001752
1753
Martin v. Löwis1a214512008-06-11 05:26:20 +00001754
1755static struct PyModuleDef timemodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001756 PyModuleDef_HEAD_INIT,
1757 "time",
1758 module_doc,
1759 -1,
1760 time_methods,
1761 NULL,
1762 NULL,
1763 NULL,
1764 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00001765};
1766
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001767PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00001768PyInit_time(void)
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001769{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001770 PyObject *m;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001771 m = PyModule_Create(&timemodule);
1772 if (m == NULL)
1773 return NULL;
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001774
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001775 /* Set, or reset, module variables like time.timezone */
Victor Stinner3bb150d2018-12-03 13:45:38 +01001776 if (init_timezone(m) < 0) {
Victor Stinner503ce5c2018-12-01 00:39:36 +01001777 return NULL;
1778 }
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001779
Max Bélanger94451182018-10-20 17:07:54 -07001780#if defined(HAVE_CLOCK_GETTIME) || defined(HAVE_CLOCK_SETTIME) || defined(HAVE_CLOCK_GETRES)
1781
Benjamin Peterson37098cd2016-09-13 22:55:09 -07001782#ifdef CLOCK_REALTIME
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -04001783 PyModule_AddIntMacro(m, CLOCK_REALTIME);
Benjamin Peterson37098cd2016-09-13 22:55:09 -07001784#endif
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -04001785#ifdef CLOCK_MONOTONIC
1786 PyModule_AddIntMacro(m, CLOCK_MONOTONIC);
1787#endif
1788#ifdef CLOCK_MONOTONIC_RAW
1789 PyModule_AddIntMacro(m, CLOCK_MONOTONIC_RAW);
1790#endif
1791#ifdef CLOCK_HIGHRES
1792 PyModule_AddIntMacro(m, CLOCK_HIGHRES);
1793#endif
1794#ifdef CLOCK_PROCESS_CPUTIME_ID
1795 PyModule_AddIntMacro(m, CLOCK_PROCESS_CPUTIME_ID);
1796#endif
1797#ifdef CLOCK_THREAD_CPUTIME_ID
1798 PyModule_AddIntMacro(m, CLOCK_THREAD_CPUTIME_ID);
1799#endif
Victor Stinnera64ce972017-11-02 04:19:19 -07001800#ifdef CLOCK_PROF
1801 PyModule_AddIntMacro(m, CLOCK_PROF);
1802#endif
1803#ifdef CLOCK_BOOTTIME
1804 PyModule_AddIntMacro(m, CLOCK_BOOTTIME);
1805#endif
1806#ifdef CLOCK_UPTIME
1807 PyModule_AddIntMacro(m, CLOCK_UPTIME);
1808#endif
Joannah Nanjekye572168a2019-01-10 19:56:38 +03001809#ifdef CLOCK_UPTIME_RAW
1810 PyModule_AddIntMacro(m, CLOCK_UPTIME_RAW);
1811#endif
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -04001812
Max Bélanger94451182018-10-20 17:07:54 -07001813#endif /* defined(HAVE_CLOCK_GETTIME) || defined(HAVE_CLOCK_SETTIME) || defined(HAVE_CLOCK_GETRES) */
1814
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001815 if (!initialized) {
Victor Stinner1c8f0592013-07-22 22:24:54 +02001816 if (PyStructSequence_InitType2(&StructTimeType,
1817 &struct_time_type_desc) < 0)
1818 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001819 }
1820 Py_INCREF(&StructTimeType);
Alexander Belopolskyc142bba2012-06-13 22:15:26 -04001821 PyModule_AddIntConstant(m, "_STRUCT_TM_ITEMS", 11);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001822 PyModule_AddObject(m, "struct_time", (PyObject*) &StructTimeType);
1823 initialized = 1;
Benjamin Peterson5633c4f2018-09-14 09:09:04 -07001824
1825#if defined(__linux__) && !defined(__GLIBC__)
1826 struct tm tm;
Benjamin Petersonb93062b2018-09-14 10:39:13 -07001827 const time_t zero = 0;
1828 if (gmtime_r(&zero, &tm) != NULL)
Benjamin Peterson5633c4f2018-09-14 09:09:04 -07001829 utc_string = tm.tm_zone;
1830#endif
1831
Victor Stinner3bb150d2018-12-03 13:45:38 +01001832 if (PyErr_Occurred()) {
1833 return NULL;
1834 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001835 return m;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001836}
1837
Victor Stinnercb29f012015-03-27 13:31:18 +01001838/* Implement pysleep() for various platforms.
Guido van Rossumb6775db1994-08-01 11:34:53 +00001839 When interrupted (or when another error occurs), return -1 and
1840 set an exception; else return 0. */
1841
1842static int
Victor Stinnercb29f012015-03-27 13:31:18 +01001843pysleep(_PyTime_t secs)
Guido van Rossum426035c1991-02-19 12:27:35 +00001844{
Victor Stinnercb29f012015-03-27 13:31:18 +01001845 _PyTime_t deadline, monotonic;
Victor Stinner79d68f92015-03-19 21:54:09 +01001846#ifndef MS_WINDOWS
1847 struct timeval timeout;
Victor Stinner79d68f92015-03-19 21:54:09 +01001848 int err = 0;
1849#else
Victor Stinnercb29f012015-03-27 13:31:18 +01001850 _PyTime_t millisecs;
Victor Stinner79d68f92015-03-19 21:54:09 +01001851 unsigned long ul_millis;
1852 DWORD rc;
1853 HANDLE hInterruptEvent;
Victor Stinner0c2fd892015-03-17 10:49:17 +01001854#endif
Victor Stinner79d68f92015-03-19 21:54:09 +01001855
Victor Stinnercb29f012015-03-27 13:31:18 +01001856 deadline = _PyTime_GetMonotonicClock() + secs;
Victor Stinner79d68f92015-03-19 21:54:09 +01001857
1858 do {
1859#ifndef MS_WINDOWS
Victor Stinner869e1772015-03-30 03:49:14 +02001860 if (_PyTime_AsTimeval(secs, &timeout, _PyTime_ROUND_CEILING) < 0)
Victor Stinnercb29f012015-03-27 13:31:18 +01001861 return -1;
Victor Stinner79d68f92015-03-19 21:54:09 +01001862
1863 Py_BEGIN_ALLOW_THREADS
1864 err = select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &timeout);
1865 Py_END_ALLOW_THREADS
1866
1867 if (err == 0)
1868 break;
1869
1870 if (errno != EINTR) {
Victor Stinner0c2fd892015-03-17 10:49:17 +01001871 PyErr_SetFromErrno(PyExc_OSError);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001872 return -1;
1873 }
Victor Stinner79d68f92015-03-19 21:54:09 +01001874#else
Victor Stinner869e1772015-03-30 03:49:14 +02001875 millisecs = _PyTime_AsMilliseconds(secs, _PyTime_ROUND_CEILING);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001876 if (millisecs > (double)ULONG_MAX) {
1877 PyErr_SetString(PyExc_OverflowError,
1878 "sleep length is too large");
1879 return -1;
1880 }
Victor Stinner79d68f92015-03-19 21:54:09 +01001881
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001882 /* Allow sleep(0) to maintain win32 semantics, and as decreed
1883 * by Guido, only the main thread can be interrupted.
1884 */
1885 ul_millis = (unsigned long)millisecs;
Victor Stinner79d68f92015-03-19 21:54:09 +01001886 if (ul_millis == 0 || !_PyOS_IsMainThread()) {
1887 Py_BEGIN_ALLOW_THREADS
Victor Stinner0eac1302015-03-20 03:06:12 +01001888 Sleep(ul_millis);
Victor Stinner79d68f92015-03-19 21:54:09 +01001889 Py_END_ALLOW_THREADS
1890 break;
Victor Stinner945c82e2015-03-12 16:19:01 +01001891 }
Victor Stinner79d68f92015-03-19 21:54:09 +01001892
1893 hInterruptEvent = _PyOS_SigintEvent();
1894 ResetEvent(hInterruptEvent);
1895
1896 Py_BEGIN_ALLOW_THREADS
1897 rc = WaitForSingleObjectEx(hInterruptEvent, ul_millis, FALSE);
Victor Stinner0c2fd892015-03-17 10:49:17 +01001898 Py_END_ALLOW_THREADS
Victor Stinner79d68f92015-03-19 21:54:09 +01001899
1900 if (rc != WAIT_OBJECT_0)
1901 break;
Victor Stinner945c82e2015-03-12 16:19:01 +01001902#endif
Victor Stinner0c2fd892015-03-17 10:49:17 +01001903
Victor Stinner79d68f92015-03-19 21:54:09 +01001904 /* sleep was interrupted by SIGINT */
1905 if (PyErr_CheckSignals())
1906 return -1;
1907
Victor Stinnercb29f012015-03-27 13:31:18 +01001908 monotonic = _PyTime_GetMonotonicClock();
1909 secs = deadline - monotonic;
Victor Stinner6aa446c2015-03-30 21:33:51 +02001910 if (secs < 0)
Victor Stinner79d68f92015-03-19 21:54:09 +01001911 break;
1912 /* retry with the recomputed delay */
1913 } while (1);
1914
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001915 return 0;
Guido van Rossum80c9d881991-04-16 08:47:51 +00001916}