blob: f991f31ee15ed77465b0804c124b6e7126b63a4f [file] [log] [blame]
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001/* Time module */
2
Barry Warsaw9a2a8a81996-12-06 23:32:14 +00003#include "Python.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +00004
Guido van Rossum87ce7bb1998-06-09 16:30:31 +00005#include <ctype.h>
6
Victor Stinnerec895392012-04-29 02:41:27 +02007#ifdef HAVE_SYS_TIMES_H
8#include <sys/times.h>
9#endif
10
Thomas Wouters0e3f5912006-08-11 14:57:12 +000011#ifdef HAVE_SYS_TYPES_H
Guido van Rossumb6775db1994-08-01 11:34:53 +000012#include <sys/types.h>
Victor Stinnerec895392012-04-29 02:41:27 +020013#endif
14
15#if defined(HAVE_SYS_RESOURCE_H)
16#include <sys/resource.h>
17#endif
Guido van Rossum6d946f91992-08-14 13:49:30 +000018
Guido van Rossumb6775db1994-08-01 11:34:53 +000019#ifdef QUICKWIN
20#include <io.h>
21#endif
22
pdoxe14679c2017-10-05 00:01:56 -070023#if defined(HAVE_PTHREAD_H)
24# include <pthread.h>
25#endif
26
Guido van Rossum7bf22de1997-12-02 20:34:19 +000027#if defined(__WATCOMC__) && !defined(__QNX__)
Guido van Rossumbceeac81996-05-23 22:53:47 +000028#include <i86.h>
29#else
Guido van Rossumcac6c721996-09-06 13:34:02 +000030#ifdef MS_WINDOWS
Mark Hammond975e3922002-07-16 01:29:19 +000031#define WIN32_LEAN_AND_MEAN
Guido van Rossum258ccd42001-03-02 06:53:29 +000032#include <windows.h>
Mark Hammond975e3922002-07-16 01:29:19 +000033#include "pythread.h"
Guido van Rossumcac6c721996-09-06 13:34:02 +000034#endif /* MS_WINDOWS */
Guido van Rossum7bf22de1997-12-02 20:34:19 +000035#endif /* !__WATCOMC__ || __QNX__ */
Guido van Rossum234f9421993-06-17 12:35:49 +000036
Gregory P. Smithb474e672018-12-30 17:05:36 -080037#ifdef _Py_MEMORY_SANITIZER
38# include <sanitizer/msan_interface.h>
39#endif
40
Zackery Spytz6673dec2019-02-25 16:56:44 -070041#ifdef _MSC_VER
42#define _Py_timezone _timezone
43#define _Py_daylight _daylight
44#define _Py_tzname _tzname
45#else
46#define _Py_timezone timezone
47#define _Py_daylight daylight
48#define _Py_tzname tzname
49#endif
50
Victor Stinnerc29b5852017-11-02 07:28:27 -070051#define SEC_TO_NS (1000 * 1000 * 1000)
52
Guido van Rossum234f9421993-06-17 12:35:49 +000053/* Forward declarations */
Victor Stinnercb29f012015-03-27 13:31:18 +010054static int pysleep(_PyTime_t);
Victor Stinnerec895392012-04-29 02:41:27 +020055
Victor Stinner85fdfa82012-01-27 00:38:48 +010056
Victor Stinnera997c7b2017-10-10 02:51:50 -070057static PyObject*
58_PyFloat_FromPyTime(_PyTime_t t)
59{
60 double d = _PyTime_AsSecondsDouble(t);
61 return PyFloat_FromDouble(d);
62}
63
Victor Stinnerc29b5852017-11-02 07:28:27 -070064
Victor Stinner4195b5c2012-02-08 23:03:19 +010065static PyObject *
Victor Stinnerc29b5852017-11-02 07:28:27 -070066time_time(PyObject *self, PyObject *unused)
Victor Stinner85fdfa82012-01-27 00:38:48 +010067{
Victor Stinnerc29b5852017-11-02 07:28:27 -070068 _PyTime_t t = _PyTime_GetSystemClock();
69 return _PyFloat_FromPyTime(t);
70}
71
72
73PyDoc_STRVAR(time_doc,
74"time() -> floating point number\n\
75\n\
76Return the current time in seconds since the Epoch.\n\
77Fractions of a second may be present if the system clock provides them.");
78
79static PyObject *
80time_time_ns(PyObject *self, PyObject *unused)
81{
82 _PyTime_t t = _PyTime_GetSystemClock();
83 return _PyTime_AsNanosecondsObject(t);
84}
85
86PyDoc_STRVAR(time_ns_doc,
87"time_ns() -> int\n\
88\n\
89Return the current time in nanoseconds since the Epoch.");
90
91#if defined(HAVE_CLOCK)
92
93#ifndef CLOCKS_PER_SEC
94# ifdef CLK_TCK
95# define CLOCKS_PER_SEC CLK_TCK
96# else
97# define CLOCKS_PER_SEC 1000000
98# endif
99#endif
100
101static int
102_PyTime_GetClockWithInfo(_PyTime_t *tp, _Py_clock_info_t *info)
103{
104 static int initialized = 0;
105 clock_t ticks;
106
107 if (!initialized) {
108 initialized = 1;
109
110 /* must sure that _PyTime_MulDiv(ticks, SEC_TO_NS, CLOCKS_PER_SEC)
111 above cannot overflow */
112 if ((_PyTime_t)CLOCKS_PER_SEC > _PyTime_MAX / SEC_TO_NS) {
113 PyErr_SetString(PyExc_OverflowError,
114 "CLOCKS_PER_SEC is too large");
115 return -1;
116 }
Victor Stinner85fdfa82012-01-27 00:38:48 +0100117 }
Victor Stinnerc29b5852017-11-02 07:28:27 -0700118
Victor Stinnerec895392012-04-29 02:41:27 +0200119 if (info) {
120 info->implementation = "clock()";
121 info->resolution = 1.0 / (double)CLOCKS_PER_SEC;
Benjamin Peterson49a69e42012-05-01 09:38:34 -0400122 info->monotonic = 1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +0200123 info->adjustable = 0;
Victor Stinnerec895392012-04-29 02:41:27 +0200124 }
Victor Stinnerc29b5852017-11-02 07:28:27 -0700125
126 ticks = clock();
127 if (ticks == (clock_t)-1) {
128 PyErr_SetString(PyExc_RuntimeError,
129 "the processor time used is not available "
130 "or its value cannot be represented");
131 return -1;
132 }
133 *tp = _PyTime_MulDiv(ticks, SEC_TO_NS, (_PyTime_t)CLOCKS_PER_SEC);
134 return 0;
Victor Stinner85fdfa82012-01-27 00:38:48 +0100135}
136#endif /* HAVE_CLOCK */
137
Victor Stinnercba9a0c2017-10-12 08:51:56 -0700138static PyObject*
139perf_counter(_Py_clock_info_t *info)
140{
Victor Stinnerbdaeb7d2017-10-16 08:44:31 -0700141 _PyTime_t t;
142 if (_PyTime_GetPerfCounterWithInfo(&t, info) < 0) {
Victor Stinnercba9a0c2017-10-12 08:51:56 -0700143 return NULL;
144 }
Victor Stinnerc29b5852017-11-02 07:28:27 -0700145 return _PyFloat_FromPyTime(t);
Victor Stinnercba9a0c2017-10-12 08:51:56 -0700146}
147
Victor Stinnere0be4232011-10-25 13:06:09 +0200148#ifdef HAVE_CLOCK_GETTIME
149static PyObject *
Victor Stinner4195b5c2012-02-08 23:03:19 +0100150time_clock_gettime(PyObject *self, PyObject *args)
Victor Stinnere0be4232011-10-25 13:06:09 +0200151{
152 int ret;
Victor Stinnere0be4232011-10-25 13:06:09 +0200153 struct timespec tp;
154
Michael Felte2926b72018-12-28 14:57:37 +0100155#if defined(_AIX) && (SIZEOF_LONG == 8)
156 long clk_id;
157 if (!PyArg_ParseTuple(args, "l:clock_gettime", &clk_id)) {
158#else
159 int clk_id;
Victor Stinnerc29b5852017-11-02 07:28:27 -0700160 if (!PyArg_ParseTuple(args, "i:clock_gettime", &clk_id)) {
Michael Felte2926b72018-12-28 14:57:37 +0100161#endif
Victor Stinnere0be4232011-10-25 13:06:09 +0200162 return NULL;
Victor Stinnerc29b5852017-11-02 07:28:27 -0700163 }
Victor Stinnere0be4232011-10-25 13:06:09 +0200164
165 ret = clock_gettime((clockid_t)clk_id, &tp);
Antoine Pitrou2c085602012-01-18 01:41:44 +0100166 if (ret != 0) {
Victor Stinnera734af32014-07-31 13:07:17 +0200167 PyErr_SetFromErrno(PyExc_OSError);
Antoine Pitrou2c085602012-01-18 01:41:44 +0100168 return NULL;
169 }
Victor Stinner4195b5c2012-02-08 23:03:19 +0100170 return PyFloat_FromDouble(tp.tv_sec + tp.tv_nsec * 1e-9);
Victor Stinnere0be4232011-10-25 13:06:09 +0200171}
172
173PyDoc_STRVAR(clock_gettime_doc,
Victor Stinnerc29b5852017-11-02 07:28:27 -0700174"clock_gettime(clk_id) -> float\n\
Victor Stinnere0be4232011-10-25 13:06:09 +0200175\n\
176Return the time of the specified clock clk_id.");
Victor Stinnerc29b5852017-11-02 07:28:27 -0700177
178static PyObject *
179time_clock_gettime_ns(PyObject *self, PyObject *args)
180{
181 int ret;
182 int clk_id;
183 struct timespec ts;
184 _PyTime_t t;
185
186 if (!PyArg_ParseTuple(args, "i:clock_gettime", &clk_id)) {
187 return NULL;
188 }
189
190 ret = clock_gettime((clockid_t)clk_id, &ts);
191 if (ret != 0) {
192 PyErr_SetFromErrno(PyExc_OSError);
193 return NULL;
194 }
195 if (_PyTime_FromTimespec(&t, &ts) < 0) {
196 return NULL;
197 }
198 return _PyTime_AsNanosecondsObject(t);
199}
200
201PyDoc_STRVAR(clock_gettime_ns_doc,
202"clock_gettime_ns(clk_id) -> int\n\
203\n\
204Return the time of the specified clock clk_id as nanoseconds.");
Benjamin Peterson37098cd2016-09-13 22:55:09 -0700205#endif /* HAVE_CLOCK_GETTIME */
Victor Stinner30d79472012-04-03 00:45:07 +0200206
Benjamin Peterson37098cd2016-09-13 22:55:09 -0700207#ifdef HAVE_CLOCK_SETTIME
Victor Stinner30d79472012-04-03 00:45:07 +0200208static PyObject *
209time_clock_settime(PyObject *self, PyObject *args)
210{
Victor Stinnerb8d01692012-04-13 23:44:05 +0200211 int clk_id;
Victor Stinner30d79472012-04-03 00:45:07 +0200212 PyObject *obj;
Victor Stinnerb3b45442015-03-28 04:09:41 +0100213 _PyTime_t t;
Victor Stinner30d79472012-04-03 00:45:07 +0200214 struct timespec tp;
215 int ret;
216
217 if (!PyArg_ParseTuple(args, "iO:clock_settime", &clk_id, &obj))
218 return NULL;
219
Victor Stinner02937aa2015-03-28 05:02:39 +0100220 if (_PyTime_FromSecondsObject(&t, obj, _PyTime_ROUND_FLOOR) < 0)
Victor Stinner30d79472012-04-03 00:45:07 +0200221 return NULL;
Victor Stinnerb3b45442015-03-28 04:09:41 +0100222
223 if (_PyTime_AsTimespec(t, &tp) == -1)
224 return NULL;
Victor Stinner30d79472012-04-03 00:45:07 +0200225
226 ret = clock_settime((clockid_t)clk_id, &tp);
227 if (ret != 0) {
Victor Stinnera734af32014-07-31 13:07:17 +0200228 PyErr_SetFromErrno(PyExc_OSError);
Victor Stinner30d79472012-04-03 00:45:07 +0200229 return NULL;
230 }
231 Py_RETURN_NONE;
232}
233
234PyDoc_STRVAR(clock_settime_doc,
235"clock_settime(clk_id, time)\n\
236\n\
237Set the time of the specified clock clk_id.");
Victor Stinnerc29b5852017-11-02 07:28:27 -0700238
239static PyObject *
240time_clock_settime_ns(PyObject *self, PyObject *args)
241{
242 int clk_id;
243 PyObject *obj;
244 _PyTime_t t;
245 struct timespec ts;
246 int ret;
247
248 if (!PyArg_ParseTuple(args, "iO:clock_settime", &clk_id, &obj)) {
249 return NULL;
250 }
251
252 if (_PyTime_FromNanosecondsObject(&t, obj) < 0) {
253 return NULL;
254 }
255 if (_PyTime_AsTimespec(t, &ts) == -1) {
256 return NULL;
257 }
258
259 ret = clock_settime((clockid_t)clk_id, &ts);
260 if (ret != 0) {
261 PyErr_SetFromErrno(PyExc_OSError);
262 return NULL;
263 }
264 Py_RETURN_NONE;
265}
266
267PyDoc_STRVAR(clock_settime_ns_doc,
268"clock_settime_ns(clk_id, time)\n\
269\n\
270Set the time of the specified clock clk_id with nanoseconds.");
Benjamin Peterson37098cd2016-09-13 22:55:09 -0700271#endif /* HAVE_CLOCK_SETTIME */
Victor Stinnere0be4232011-10-25 13:06:09 +0200272
Benjamin Peterson37098cd2016-09-13 22:55:09 -0700273#ifdef HAVE_CLOCK_GETRES
Victor Stinnere0be4232011-10-25 13:06:09 +0200274static PyObject *
Victor Stinner4195b5c2012-02-08 23:03:19 +0100275time_clock_getres(PyObject *self, PyObject *args)
Victor Stinnere0be4232011-10-25 13:06:09 +0200276{
277 int ret;
Victor Stinnerb8d01692012-04-13 23:44:05 +0200278 int clk_id;
Victor Stinnere0be4232011-10-25 13:06:09 +0200279 struct timespec tp;
280
Victor Stinner4195b5c2012-02-08 23:03:19 +0100281 if (!PyArg_ParseTuple(args, "i:clock_getres", &clk_id))
Victor Stinnere0be4232011-10-25 13:06:09 +0200282 return NULL;
283
284 ret = clock_getres((clockid_t)clk_id, &tp);
Antoine Pitrou2c085602012-01-18 01:41:44 +0100285 if (ret != 0) {
Victor Stinnera734af32014-07-31 13:07:17 +0200286 PyErr_SetFromErrno(PyExc_OSError);
Antoine Pitrou2c085602012-01-18 01:41:44 +0100287 return NULL;
288 }
Victor Stinner4195b5c2012-02-08 23:03:19 +0100289
290 return PyFloat_FromDouble(tp.tv_sec + tp.tv_nsec * 1e-9);
Victor Stinnere0be4232011-10-25 13:06:09 +0200291}
292
293PyDoc_STRVAR(clock_getres_doc,
Victor Stinner4195b5c2012-02-08 23:03:19 +0100294"clock_getres(clk_id) -> floating point number\n\
Victor Stinnere0be4232011-10-25 13:06:09 +0200295\n\
296Return the resolution (precision) of the specified clock clk_id.");
Benjamin Peterson37098cd2016-09-13 22:55:09 -0700297#endif /* HAVE_CLOCK_GETRES */
Victor Stinnere0be4232011-10-25 13:06:09 +0200298
pdoxe14679c2017-10-05 00:01:56 -0700299#ifdef HAVE_PTHREAD_GETCPUCLOCKID
300static PyObject *
301time_pthread_getcpuclockid(PyObject *self, PyObject *args)
302{
303 unsigned long thread_id;
304 int err;
305 clockid_t clk_id;
306 if (!PyArg_ParseTuple(args, "k:pthread_getcpuclockid", &thread_id)) {
307 return NULL;
308 }
309 err = pthread_getcpuclockid((pthread_t)thread_id, &clk_id);
310 if (err) {
311 errno = err;
312 PyErr_SetFromErrno(PyExc_OSError);
313 return NULL;
314 }
Gregory P. Smithb474e672018-12-30 17:05:36 -0800315#ifdef _Py_MEMORY_SANITIZER
316 __msan_unpoison(&clk_id, sizeof(clk_id));
317#endif
pdoxe14679c2017-10-05 00:01:56 -0700318 return PyLong_FromLong(clk_id);
319}
320
321PyDoc_STRVAR(pthread_getcpuclockid_doc,
322"pthread_getcpuclockid(thread_id) -> int\n\
323\n\
324Return the clk_id of a thread's CPU time clock.");
325#endif /* HAVE_PTHREAD_GETCPUCLOCKID */
326
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000327static PyObject *
Victor Stinnercb29f012015-03-27 13:31:18 +0100328time_sleep(PyObject *self, PyObject *obj)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000329{
Victor Stinnercb29f012015-03-27 13:31:18 +0100330 _PyTime_t secs;
Pablo Galindo59af94f2017-10-18 08:13:09 +0100331 if (_PyTime_FromSecondsObject(&secs, obj, _PyTime_ROUND_TIMEOUT))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000332 return NULL;
Victor Stinner7f53a502011-07-05 22:00:25 +0200333 if (secs < 0) {
334 PyErr_SetString(PyExc_ValueError,
335 "sleep length must be non-negative");
336 return NULL;
337 }
Victor Stinnercb29f012015-03-27 13:31:18 +0100338 if (pysleep(secs) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000339 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200340 Py_RETURN_NONE;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000341}
342
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000343PyDoc_STRVAR(sleep_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000344"sleep(seconds)\n\
345\n\
346Delay execution for a given number of seconds. The argument may be\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000347a floating point number for subsecond precision.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000348
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000349static PyStructSequence_Field struct_time_type_fields[] = {
Alexander Belopolsky69f3fd02010-06-05 15:04:51 +0000350 {"tm_year", "year, for example, 1993"},
351 {"tm_mon", "month of year, range [1, 12]"},
352 {"tm_mday", "day of month, range [1, 31]"},
353 {"tm_hour", "hours, range [0, 23]"},
354 {"tm_min", "minutes, range [0, 59]"},
355 {"tm_sec", "seconds, range [0, 61])"},
356 {"tm_wday", "day of week, range [0, 6], Monday is 0"},
357 {"tm_yday", "day of year, range [1, 366]"},
358 {"tm_isdst", "1 if summer time is in effect, 0 if not, and -1 if unknown"},
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400359 {"tm_zone", "abbreviation of timezone name"},
360 {"tm_gmtoff", "offset from UTC in seconds"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000361 {0}
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000362};
363
364static PyStructSequence_Desc struct_time_type_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000365 "time.struct_time",
Alexander Belopolsky69f3fd02010-06-05 15:04:51 +0000366 "The time value as returned by gmtime(), localtime(), and strptime(), and\n"
367 " accepted by asctime(), mktime() and strftime(). May be considered as a\n"
368 " sequence of 9 integers.\n\n"
369 " Note that several fields' values are not the same as those defined by\n"
370 " the C language standard for struct tm. For example, the value of the\n"
371 " field tm_year is the actual year, not year - 1900. See individual\n"
372 " fields' descriptions for details.",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000373 struct_time_type_fields,
374 9,
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000375};
Tim Peters9ad4b682002-02-13 05:14:18 +0000376
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000377static int initialized;
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000378static PyTypeObject StructTimeType;
379
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400380
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000381static PyObject *
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -0400382tmtotuple(struct tm *p
383#ifndef HAVE_STRUCT_TM_TM_ZONE
Victor Stinner0d659e52017-04-25 01:22:42 +0200384 , const char *zone, time_t gmtoff
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -0400385#endif
386)
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000387{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000388 PyObject *v = PyStructSequence_New(&StructTimeType);
389 if (v == NULL)
390 return NULL;
Tim Peters9ad4b682002-02-13 05:14:18 +0000391
Christian Heimes217cfd12007-12-02 14:31:20 +0000392#define SET(i,val) PyStructSequence_SET_ITEM(v, i, PyLong_FromLong((long) val))
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000393
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000394 SET(0, p->tm_year + 1900);
395 SET(1, p->tm_mon + 1); /* Want January == 1 */
396 SET(2, p->tm_mday);
397 SET(3, p->tm_hour);
398 SET(4, p->tm_min);
399 SET(5, p->tm_sec);
400 SET(6, (p->tm_wday + 6) % 7); /* Want Monday == 0 */
401 SET(7, p->tm_yday + 1); /* Want January, 1 == 1 */
402 SET(8, p->tm_isdst);
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400403#ifdef HAVE_STRUCT_TM_TM_ZONE
404 PyStructSequence_SET_ITEM(v, 9,
Victor Stinner7ed7aea2018-01-15 10:45:49 +0100405 PyUnicode_DecodeLocale(p->tm_zone, "surrogateescape"));
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400406 SET(10, p->tm_gmtoff);
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -0400407#else
408 PyStructSequence_SET_ITEM(v, 9,
Victor Stinner7ed7aea2018-01-15 10:45:49 +0100409 PyUnicode_DecodeLocale(zone, "surrogateescape"));
Victor Stinner0d659e52017-04-25 01:22:42 +0200410 PyStructSequence_SET_ITEM(v, 10, _PyLong_FromTime_t(gmtoff));
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400411#endif /* HAVE_STRUCT_TM_TM_ZONE */
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000412#undef SET
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000413 if (PyErr_Occurred()) {
414 Py_XDECREF(v);
415 return NULL;
416 }
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000417
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000418 return v;
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000419}
420
Fred Drakef901abd2004-08-03 17:58:55 +0000421/* Parse arg tuple that can contain an optional float-or-None value;
422 format needs to be "|O:name".
423 Returns non-zero on success (parallels PyArg_ParseTuple).
424*/
425static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +0200426parse_time_t_args(PyObject *args, const char *format, time_t *pwhen)
Fred Drakef901abd2004-08-03 17:58:55 +0000427{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000428 PyObject *ot = NULL;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100429 time_t whent;
Fred Drakef901abd2004-08-03 17:58:55 +0000430
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000431 if (!PyArg_ParseTuple(args, format, &ot))
432 return 0;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100433 if (ot == NULL || ot == Py_None) {
434 whent = time(NULL);
435 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000436 else {
Victor Stinner02937aa2015-03-28 05:02:39 +0100437 if (_PyTime_ObjectToTime_t(ot, &whent, _PyTime_ROUND_FLOOR) == -1)
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100438 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000439 }
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100440 *pwhen = whent;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000441 return 1;
Fred Drakef901abd2004-08-03 17:58:55 +0000442}
443
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000444static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000445time_gmtime(PyObject *self, PyObject *args)
Guido van Rossum234f9421993-06-17 12:35:49 +0000446{
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100447 time_t when;
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -0400448 struct tm buf;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100449
450 if (!parse_time_t_args(args, "|O:gmtime", &when))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000451 return NULL;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100452
453 errno = 0;
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -0400454 if (_PyTime_gmtime(when, &buf) != 0)
455 return NULL;
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -0400456#ifdef HAVE_STRUCT_TM_TM_ZONE
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100457 return tmtotuple(&buf);
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -0400458#else
459 return tmtotuple(&buf, "UTC", 0);
460#endif
Guido van Rossum234f9421993-06-17 12:35:49 +0000461}
462
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -0400463#ifndef HAVE_TIMEGM
464static time_t
465timegm(struct tm *p)
466{
467 /* XXX: the following implementation will not work for tm_year < 1970.
468 but it is likely that platforms that don't have timegm do not support
469 negative timestamps anyways. */
470 return p->tm_sec + p->tm_min*60 + p->tm_hour*3600 + p->tm_yday*86400 +
471 (p->tm_year-70)*31536000 + ((p->tm_year-69)/4)*86400 -
472 ((p->tm_year-1)/100)*86400 + ((p->tm_year+299)/400)*86400;
473}
474#endif
475
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000476PyDoc_STRVAR(gmtime_doc,
Christian Heimes9a371592007-12-28 14:08:13 +0000477"gmtime([seconds]) -> (tm_year, tm_mon, tm_mday, tm_hour, tm_min,\n\
Fred Drake193a3f62002-03-12 21:38:49 +0000478 tm_sec, tm_wday, tm_yday, tm_isdst)\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000479\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000480Convert seconds since the Epoch to a time tuple expressing UTC (a.k.a.\n\
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400481GMT). When 'seconds' is not passed in, convert the current time instead.\n\
482\n\
483If the platform supports the tm_gmtoff and tm_zone, they are available as\n\
484attributes only.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000485
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000486static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000487time_localtime(PyObject *self, PyObject *args)
Guido van Rossum234f9421993-06-17 12:35:49 +0000488{
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100489 time_t when;
490 struct tm buf;
491
492 if (!parse_time_t_args(args, "|O:localtime", &when))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000493 return NULL;
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -0400494 if (_PyTime_localtime(when, &buf) != 0)
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100495 return NULL;
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -0400496#ifdef HAVE_STRUCT_TM_TM_ZONE
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100497 return tmtotuple(&buf);
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -0400498#else
499 {
500 struct tm local = buf;
501 char zone[100];
Victor Stinner0d659e52017-04-25 01:22:42 +0200502 time_t gmtoff;
Steve Dowerc3c6f712016-12-14 11:22:05 -0800503 strftime(zone, sizeof(zone), "%Z", &buf);
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -0400504 gmtoff = timegm(&buf) - when;
505 return tmtotuple(&local, zone, gmtoff);
506 }
507#endif
Guido van Rossum234f9421993-06-17 12:35:49 +0000508}
509
Benjamin Peterson5633c4f2018-09-14 09:09:04 -0700510#if defined(__linux__) && !defined(__GLIBC__)
511static const char *utc_string = NULL;
512#endif
513
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000514PyDoc_STRVAR(localtime_doc,
Christian Heimes9a371592007-12-28 14:08:13 +0000515"localtime([seconds]) -> (tm_year,tm_mon,tm_mday,tm_hour,tm_min,\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000516 tm_sec,tm_wday,tm_yday,tm_isdst)\n\
Martin v. Löwisb3cfc1d2001-12-02 12:27:43 +0000517\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000518Convert seconds since the Epoch to a time tuple expressing local time.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000519When 'seconds' is not passed in, convert the current time instead.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000520
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000521/* Convert 9-item tuple to tm structure. Return 1 on success, set
522 * an exception and return 0 on error.
523 */
Guido van Rossum9e90a671993-06-24 11:10:19 +0000524static int
Oren Milman1d1d3e92017-08-20 18:35:36 +0300525gettmarg(PyObject *args, struct tm *p, const char *format)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000526{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000527 int y;
Guido van Rossumcfbaecc1998-08-25 14:51:12 +0000528
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000529 memset((void *) p, '\0', sizeof(struct tm));
Guido van Rossumb9081262007-08-25 03:14:09 +0000530
Alexander Belopolsky610e5442011-01-06 21:57:06 +0000531 if (!PyTuple_Check(args)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000532 PyErr_SetString(PyExc_TypeError,
533 "Tuple or struct_time argument required");
534 return 0;
535 }
Skip Montanaro41cfce92007-08-24 21:11:00 +0000536
Oren Milman1d1d3e92017-08-20 18:35:36 +0300537 if (!PyArg_ParseTuple(args, format,
Alexander Belopolsky610e5442011-01-06 21:57:06 +0000538 &y, &p->tm_mon, &p->tm_mday,
539 &p->tm_hour, &p->tm_min, &p->tm_sec,
540 &p->tm_wday, &p->tm_yday, &p->tm_isdst))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000541 return 0;
Gregory P. Smith76be0ff2018-08-24 18:08:50 -0700542
543 if (y < INT_MIN + 1900) {
544 PyErr_SetString(PyExc_OverflowError, "year out of range");
545 return 0;
546 }
547
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000548 p->tm_year = y - 1900;
549 p->tm_mon--;
550 p->tm_wday = (p->tm_wday + 1) % 7;
551 p->tm_yday--;
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400552#ifdef HAVE_STRUCT_TM_TM_ZONE
553 if (Py_TYPE(args) == &StructTimeType) {
554 PyObject *item;
Victor Stinner1cdfcfc2018-11-28 15:19:51 +0100555 item = PyStructSequence_GET_ITEM(args, 9);
Benjamin Peterson5633c4f2018-09-14 09:09:04 -0700556 if (item != Py_None) {
Xiang Zhang163eca32018-10-28 23:58:42 +0800557 p->tm_zone = (char *)PyUnicode_AsUTF8(item);
Benjamin Peterson5633c4f2018-09-14 09:09:04 -0700558 if (p->tm_zone == NULL) {
559 return 0;
560 }
561#if defined(__linux__) && !defined(__GLIBC__)
562 // Make an attempt to return the C library's own timezone strings to
563 // it. musl refuses to process a tm_zone field unless it produced
564 // it. See issue #34672.
565 if (utc_string && strcmp(p->tm_zone, utc_string) == 0) {
566 p->tm_zone = utc_string;
567 }
568 else if (tzname[0] && strcmp(p->tm_zone, tzname[0]) == 0) {
569 p->tm_zone = tzname[0];
570 }
571 else if (tzname[1] && strcmp(p->tm_zone, tzname[1]) == 0) {
572 p->tm_zone = tzname[1];
573 }
574#endif
575 }
Victor Stinner1cdfcfc2018-11-28 15:19:51 +0100576 item = PyStructSequence_GET_ITEM(args, 10);
Benjamin Peterson5633c4f2018-09-14 09:09:04 -0700577 if (item != Py_None) {
578 p->tm_gmtoff = PyLong_AsLong(item);
579 if (PyErr_Occurred())
580 return 0;
581 }
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400582 }
583#endif /* HAVE_STRUCT_TM_TM_ZONE */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000584 return 1;
Guido van Rossum9e90a671993-06-24 11:10:19 +0000585}
586
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000587/* Check values of the struct tm fields before it is passed to strftime() and
588 * asctime(). Return 1 if all values are valid, otherwise set an exception
589 * and returns 0.
590 */
Victor Stinneref128102010-10-07 01:00:52 +0000591static int
592checktm(struct tm* buf)
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000593{
Victor Stinneref128102010-10-07 01:00:52 +0000594 /* Checks added to make sure strftime() and asctime() does not crash Python by
595 indexing blindly into some array for a textual representation
596 by some bad index (fixes bug #897625 and #6608).
597
598 Also support values of zero from Python code for arguments in which
599 that is out of range by forcing that value to the lowest value that
600 is valid (fixed bug #1520914).
601
602 Valid ranges based on what is allowed in struct tm:
603
604 - tm_year: [0, max(int)] (1)
605 - tm_mon: [0, 11] (2)
606 - tm_mday: [1, 31]
607 - tm_hour: [0, 23]
608 - tm_min: [0, 59]
609 - tm_sec: [0, 60]
610 - tm_wday: [0, 6] (1)
611 - tm_yday: [0, 365] (2)
612 - tm_isdst: [-max(int), max(int)]
613
614 (1) gettmarg() handles bounds-checking.
615 (2) Python's acceptable range is one greater than the range in C,
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000616 thus need to check against automatic decrement by gettmarg().
617 */
618 if (buf->tm_mon == -1)
619 buf->tm_mon = 0;
620 else if (buf->tm_mon < 0 || buf->tm_mon > 11) {
621 PyErr_SetString(PyExc_ValueError, "month out of range");
622 return 0;
623 }
624 if (buf->tm_mday == 0)
625 buf->tm_mday = 1;
626 else if (buf->tm_mday < 0 || buf->tm_mday > 31) {
627 PyErr_SetString(PyExc_ValueError, "day of month out of range");
628 return 0;
629 }
630 if (buf->tm_hour < 0 || buf->tm_hour > 23) {
631 PyErr_SetString(PyExc_ValueError, "hour out of range");
632 return 0;
633 }
634 if (buf->tm_min < 0 || buf->tm_min > 59) {
635 PyErr_SetString(PyExc_ValueError, "minute out of range");
636 return 0;
637 }
638 if (buf->tm_sec < 0 || buf->tm_sec > 61) {
639 PyErr_SetString(PyExc_ValueError, "seconds out of range");
640 return 0;
641 }
642 /* tm_wday does not need checking of its upper-bound since taking
643 ``% 7`` in gettmarg() automatically restricts the range. */
644 if (buf->tm_wday < 0) {
645 PyErr_SetString(PyExc_ValueError, "day of week out of range");
646 return 0;
647 }
648 if (buf->tm_yday == -1)
649 buf->tm_yday = 0;
650 else if (buf->tm_yday < 0 || buf->tm_yday > 365) {
651 PyErr_SetString(PyExc_ValueError, "day of year out of range");
652 return 0;
653 }
654 return 1;
655}
656
Victor Stinnerc1f32ca2011-10-14 02:36:13 +0200657#ifdef MS_WINDOWS
658 /* wcsftime() doesn't format correctly time zones, see issue #10653 */
659# undef HAVE_WCSFTIME
660#endif
Alexander Belopolskycf774542012-10-02 18:39:16 -0400661#define STRFTIME_FORMAT_CODES \
662"Commonly used format codes:\n\
663\n\
664%Y Year with century as a decimal number.\n\
665%m Month as a decimal number [01,12].\n\
666%d Day of the month as a decimal number [01,31].\n\
667%H Hour (24-hour clock) as a decimal number [00,23].\n\
668%M Minute as a decimal number [00,59].\n\
669%S Second as a decimal number [00,61].\n\
670%z Time zone offset from UTC.\n\
671%a Locale's abbreviated weekday name.\n\
672%A Locale's full weekday name.\n\
673%b Locale's abbreviated month name.\n\
674%B Locale's full month name.\n\
675%c Locale's appropriate date and time representation.\n\
676%I Hour (12-hour clock) as a decimal number [01,12].\n\
677%p Locale's equivalent of either AM or PM.\n\
678\n\
679Other codes may be available on your platform. See documentation for\n\
680the C library strftime function.\n"
Victor Stinnerc1f32ca2011-10-14 02:36:13 +0200681
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000682#ifdef HAVE_STRFTIME
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000683#ifdef HAVE_WCSFTIME
684#define time_char wchar_t
685#define format_time wcsftime
686#define time_strlen wcslen
687#else
688#define time_char char
689#define format_time strftime
690#define time_strlen strlen
691#endif
692
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000693static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000694time_strftime(PyObject *self, PyObject *args)
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000695{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000696 PyObject *tup = NULL;
697 struct tm buf;
698 const time_char *fmt;
Victor Stinnerb2904782010-09-29 10:34:19 +0000699#ifdef HAVE_WCSFTIME
700 wchar_t *format;
701#else
702 PyObject *format;
703#endif
Victor Stinneref128102010-10-07 01:00:52 +0000704 PyObject *format_arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000705 size_t fmtlen, buflen;
Victor Stinnerb2904782010-09-29 10:34:19 +0000706 time_char *outbuf = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000707 size_t i;
Victor Stinnerb2904782010-09-29 10:34:19 +0000708 PyObject *ret = NULL;
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000709
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000710 memset((void *) &buf, '\0', sizeof(buf));
Guido van Rossum1f41f841998-04-27 19:04:26 +0000711
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000712 /* Will always expect a unicode string to be passed as format.
713 Given that there's no str type anymore in py3k this seems safe.
714 */
Victor Stinneref128102010-10-07 01:00:52 +0000715 if (!PyArg_ParseTuple(args, "U|O:strftime", &format_arg, &tup))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000716 return NULL;
Thomas Woutersfe385252001-01-19 23:16:56 +0000717
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000718 if (tup == NULL) {
719 time_t tt = time(NULL);
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -0400720 if (_PyTime_localtime(tt, &buf) != 0)
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100721 return NULL;
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000722 }
Oren Milman1d1d3e92017-08-20 18:35:36 +0300723 else if (!gettmarg(tup, &buf,
724 "iiiiiiiii;strftime(): illegal time tuple argument") ||
725 !checktm(&buf))
726 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000727 return NULL;
Oren Milman1d1d3e92017-08-20 18:35:36 +0300728 }
Guido van Rossum10b164a2001-09-25 13:59:01 +0000729
pxinwrf1464f42019-04-15 17:06:21 +0800730#if defined(_MSC_VER) || (defined(__sun) && defined(__SVR4)) || defined(_AIX) || defined(__VXWORKS__)
Victor Stinner73ea29c2011-01-08 01:56:31 +0000731 if (buf.tm_year + 1900 < 1 || 9999 < buf.tm_year + 1900) {
Victor Stinner6f0e4f92011-03-21 02:14:53 +0100732 PyErr_SetString(PyExc_ValueError,
733 "strftime() requires year in [1; 9999]");
Alexander Belopolsky0dd06f42011-01-08 01:23:02 +0000734 return NULL;
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000735 }
Victor Stinner73ea29c2011-01-08 01:56:31 +0000736#endif
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000737
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000738 /* Normalize tm_isdst just in case someone foolishly implements %Z
739 based on the assumption that tm_isdst falls within the range of
740 [-1, 1] */
741 if (buf.tm_isdst < -1)
742 buf.tm_isdst = -1;
743 else if (buf.tm_isdst > 1)
744 buf.tm_isdst = 1;
Brett Cannond1080a32004-03-02 04:38:10 +0000745
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000746#ifdef HAVE_WCSFTIME
Victor Stinnerbeb4135b2010-10-07 01:02:42 +0000747 format = PyUnicode_AsWideCharString(format_arg, NULL);
Victor Stinnerb2904782010-09-29 10:34:19 +0000748 if (format == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000749 return NULL;
Victor Stinnerb2904782010-09-29 10:34:19 +0000750 fmt = format;
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000751#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000752 /* Convert the unicode string to an ascii one */
Victor Stinner1b579672011-12-17 05:47:23 +0100753 format = PyUnicode_EncodeLocale(format_arg, "surrogateescape");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000754 if (format == NULL)
755 return NULL;
756 fmt = PyBytes_AS_STRING(format);
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000757#endif
Amaury Forgeot d'Arcb5be6d42009-03-02 23:52:57 +0000758
Stefan Krah4aea7d32012-02-27 16:30:26 +0100759#if defined(MS_WINDOWS) && !defined(HAVE_WCSFTIME)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000760 /* check that the format string contains only valid directives */
Steve Dowere5b58952015-09-06 19:20:51 -0700761 for (outbuf = strchr(fmt, '%');
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000762 outbuf != NULL;
Victor Stinner5a3ff792011-10-16 19:08:23 +0200763 outbuf = strchr(outbuf+2, '%'))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000764 {
Steve Dowere5b58952015-09-06 19:20:51 -0700765 if (outbuf[1] == '#')
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000766 ++outbuf; /* not documented by python, */
Steve Dowere5b58952015-09-06 19:20:51 -0700767 if (outbuf[1] == '\0')
768 break;
769 if ((outbuf[1] == 'y') && buf.tm_year < 0) {
Tim Golden6e51b8f2013-11-12 12:36:54 +0000770 PyErr_SetString(PyExc_ValueError,
771 "format %y requires year >= 1900 on Windows");
772 Py_DECREF(format);
773 return NULL;
774 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000775 }
Jakub Kulík6f9bc722018-12-31 03:16:40 +0100776#elif (defined(_AIX) || (defined(__sun) && defined(__SVR4))) && defined(HAVE_WCSFTIME)
Steve Dowere5b58952015-09-06 19:20:51 -0700777 for (outbuf = wcschr(fmt, '%');
Victor Stinner55329f82013-11-17 23:39:21 +0100778 outbuf != NULL;
779 outbuf = wcschr(outbuf+2, '%'))
780 {
Steve Dowere5b58952015-09-06 19:20:51 -0700781 if (outbuf[1] == L'\0')
782 break;
Victor Stinner55329f82013-11-17 23:39:21 +0100783 /* Issue #19634: On AIX, wcsftime("y", (1899, 1, 1, 0, 0, 0, 0, 0, 0))
784 returns "0/" instead of "99" */
785 if (outbuf[1] == L'y' && buf.tm_year < 0) {
786 PyErr_SetString(PyExc_ValueError,
787 "format %y requires year >= 1900 on AIX");
Zackery Spytz91e6c872018-09-21 00:09:48 -0600788 PyMem_Free(format);
Victor Stinner55329f82013-11-17 23:39:21 +0100789 return NULL;
790 }
791 }
Amaury Forgeot d'Arcb5be6d42009-03-02 23:52:57 +0000792#endif
793
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000794 fmtlen = time_strlen(fmt);
Guido van Rossumc222ec21999-02-23 00:00:10 +0000795
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000796 /* I hate these functions that presume you know how big the output
797 * will be ahead of time...
798 */
799 for (i = 1024; ; i += i) {
800 outbuf = (time_char *)PyMem_Malloc(i*sizeof(time_char));
801 if (outbuf == NULL) {
Victor Stinnerb2904782010-09-29 10:34:19 +0000802 PyErr_NoMemory();
803 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000804 }
Steve Dower57ab1cd2015-09-22 14:51:42 -0700805#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
806 errno = 0;
807#endif
Steve Dowerd9ef74e2015-05-22 15:08:34 -0700808 _Py_BEGIN_SUPPRESS_IPH
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000809 buflen = format_time(outbuf, i, fmt, &buf);
Steve Dowerd9ef74e2015-05-22 15:08:34 -0700810 _Py_END_SUPPRESS_IPH
Victor Stinner136ea492011-12-17 22:37:18 +0100811#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
Steve Dower97cded92015-09-08 19:12:51 -0700812 /* VisualStudio .NET 2005 does this properly */
813 if (buflen == 0 && errno == EINVAL) {
814 PyErr_SetString(PyExc_ValueError, "Invalid format string");
815 PyMem_Free(outbuf);
816 break;
817 }
Victor Stinner136ea492011-12-17 22:37:18 +0100818#endif
Steve Dower97cded92015-09-08 19:12:51 -0700819 if (buflen > 0 || i >= 256 * fmtlen) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000820 /* If the buffer is 256 times as long as the format,
821 it's probably not failing for lack of room!
822 More likely, the format yields an empty result,
823 e.g. an empty format, or %Z when the timezone
824 is unknown. */
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000825#ifdef HAVE_WCSFTIME
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000826 ret = PyUnicode_FromWideChar(outbuf, buflen);
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000827#else
Victor Stinner7ed7aea2018-01-15 10:45:49 +0100828 ret = PyUnicode_DecodeLocaleAndSize(outbuf, buflen, "surrogateescape");
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000829#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000830 PyMem_Free(outbuf);
Victor Stinnerb2904782010-09-29 10:34:19 +0000831 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000832 }
833 PyMem_Free(outbuf);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000834 }
Victor Stinnerb2904782010-09-29 10:34:19 +0000835#ifdef HAVE_WCSFTIME
836 PyMem_Free(format);
837#else
838 Py_DECREF(format);
839#endif
840 return ret;
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000841}
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000842
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000843#undef time_char
844#undef format_time
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000845PyDoc_STRVAR(strftime_doc,
Thomas Woutersfe385252001-01-19 23:16:56 +0000846"strftime(format[, tuple]) -> string\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000847\n\
848Convert a time tuple to a string according to a format specification.\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000849See the library reference manual for formatting codes. When the time tuple\n\
Alexander Belopolskycf774542012-10-02 18:39:16 -0400850is not present, current time as returned by localtime() is used.\n\
851\n" STRFTIME_FORMAT_CODES);
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000852#endif /* HAVE_STRFTIME */
853
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000854static PyObject *
855time_strptime(PyObject *self, PyObject *args)
856{
Victor Stinnerdbe28d22016-12-09 00:38:53 +0100857 PyObject *module, *func, *result;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200858 _Py_IDENTIFIER(_strptime_time);
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000859
Victor Stinnerdbe28d22016-12-09 00:38:53 +0100860 module = PyImport_ImportModuleNoBlock("_strptime");
861 if (!module)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000862 return NULL;
Victor Stinnerdbe28d22016-12-09 00:38:53 +0100863
864 func = _PyObject_GetAttrId(module, &PyId__strptime_time);
865 Py_DECREF(module);
866 if (!func) {
867 return NULL;
868 }
869
870 result = PyObject_Call(func, args, NULL);
871 Py_DECREF(func);
872 return result;
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000873}
874
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000875
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000876PyDoc_STRVAR(strptime_doc,
Brett Cannon20def8b2003-07-01 05:16:08 +0000877"strptime(string, format) -> struct_time\n\
Martin v. Löwisb3cfc1d2001-12-02 12:27:43 +0000878\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000879Parse a string to a time tuple according to a format specification.\n\
Alexander Belopolskycf774542012-10-02 18:39:16 -0400880See the library reference manual for formatting codes (same as\n\
881strftime()).\n\
882\n" STRFTIME_FORMAT_CODES);
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000883
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000884static PyObject *
885_asctime(struct tm *timeptr)
886{
887 /* Inspired by Open Group reference implementation available at
888 * http://pubs.opengroup.org/onlinepubs/009695399/functions/asctime.html */
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200889 static const char wday_name[7][4] = {
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000890 "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
891 };
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200892 static const char mon_name[12][4] = {
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000893 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
894 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
895 };
Victor Stinner499dfcf2011-03-21 13:26:24 +0100896 return PyUnicode_FromFormat(
897 "%s %s%3d %.2d:%.2d:%.2d %d",
898 wday_name[timeptr->tm_wday],
899 mon_name[timeptr->tm_mon],
900 timeptr->tm_mday, timeptr->tm_hour,
901 timeptr->tm_min, timeptr->tm_sec,
902 1900 + timeptr->tm_year);
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000903}
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000904
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000905static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000906time_asctime(PyObject *self, PyObject *args)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000907{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000908 PyObject *tup = NULL;
909 struct tm buf;
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000910
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000911 if (!PyArg_UnpackTuple(args, "asctime", 0, 1, &tup))
912 return NULL;
913 if (tup == NULL) {
914 time_t tt = time(NULL);
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -0400915 if (_PyTime_localtime(tt, &buf) != 0)
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100916 return NULL;
Oren Milman1d1d3e92017-08-20 18:35:36 +0300917 }
918 else if (!gettmarg(tup, &buf,
919 "iiiiiiiii;asctime(): illegal time tuple argument") ||
920 !checktm(&buf))
921 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000922 return NULL;
Oren Milman1d1d3e92017-08-20 18:35:36 +0300923 }
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000924 return _asctime(&buf);
Guido van Rossum9e90a671993-06-24 11:10:19 +0000925}
926
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000927PyDoc_STRVAR(asctime_doc,
Thomas Woutersfe385252001-01-19 23:16:56 +0000928"asctime([tuple]) -> string\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000929\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000930Convert a time tuple to a string, e.g. 'Sat Jun 06 16:26:11 1998'.\n\
931When the time tuple is not present, current time as returned by localtime()\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000932is used.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000933
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000934static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000935time_ctime(PyObject *self, PyObject *args)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000936{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000937 time_t tt;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100938 struct tm buf;
939 if (!parse_time_t_args(args, "|O:ctime", &tt))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000940 return NULL;
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -0400941 if (_PyTime_localtime(tt, &buf) != 0)
Alexander Belopolsky5da468f2011-01-04 17:15:52 +0000942 return NULL;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100943 return _asctime(&buf);
Guido van Rossum9e90a671993-06-24 11:10:19 +0000944}
945
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000946PyDoc_STRVAR(ctime_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000947"ctime(seconds) -> string\n\
948\n\
949Convert a time in seconds since the Epoch to a string in local time.\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000950This is equivalent to asctime(localtime(seconds)). When the time tuple is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000951not present, current time as returned by localtime() is used.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000952
Guido van Rossum60cd8131998-03-06 17:16:21 +0000953#ifdef HAVE_MKTIME
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000954static PyObject *
Victor Stinner87094902019-04-09 19:12:26 +0200955time_mktime(PyObject *self, PyObject *tm_tuple)
Guido van Rossum234f9421993-06-17 12:35:49 +0000956{
Victor Stinner87094902019-04-09 19:12:26 +0200957 struct tm tm;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000958 time_t tt;
Michael Felte2926b72018-12-28 14:57:37 +0100959
Victor Stinner87094902019-04-09 19:12:26 +0200960 if (!gettmarg(tm_tuple, &tm,
Oren Milman1d1d3e92017-08-20 18:35:36 +0300961 "iiiiiiiii;mktime(): illegal time tuple argument"))
962 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000963 return NULL;
Oren Milman1d1d3e92017-08-20 18:35:36 +0300964 }
Victor Stinner87094902019-04-09 19:12:26 +0200965
pxinwrf1464f42019-04-15 17:06:21 +0800966#if defined(_AIX) || (defined(__VXWORKS__) && !defined(_WRS_CONFIG_LP64))
Victor Stinner87094902019-04-09 19:12:26 +0200967 /* bpo-19748: AIX mktime() valid range is 00:00:00 UTC, January 1, 1970
968 to 03:14:07 UTC, January 19, 2038. Thanks to the workaround below,
969 it is possible to support years in range [1902; 2037] */
970 if (tm.tm_year < 2 || tm.tm_year > 137) {
971 /* bpo-19748: On AIX, mktime() does not report overflow error
pxinwrf1464f42019-04-15 17:06:21 +0800972 for timestamp < -2^31 or timestamp > 2**31-1. VxWorks has the
973 same issue when working in 32 bit mode. */
Victor Stinner1ac42612014-02-21 09:27:17 +0100974 PyErr_SetString(PyExc_OverflowError,
975 "mktime argument out of range");
976 return NULL;
977 }
pxinwrf1464f42019-04-15 17:06:21 +0800978#endif
Victor Stinner87094902019-04-09 19:12:26 +0200979
pxinwrf1464f42019-04-15 17:06:21 +0800980#ifdef _AIX
Victor Stinner87094902019-04-09 19:12:26 +0200981 /* bpo-34373: AIX mktime() has an integer overflow for years in range
982 [1902; 1969]. Workaround the issue by using a year greater or equal than
983 1970 (tm_year >= 70): mktime() behaves correctly in that case
984 (ex: properly report errors). tm_year and tm_wday are adjusted after
985 mktime() call. */
986 int orig_tm_year = tm.tm_year;
987 int delta_days = 0;
988 while (tm.tm_year < 70) {
989 /* Use 4 years to account properly leap years */
990 tm.tm_year += 4;
Michael Felte2926b72018-12-28 14:57:37 +0100991 delta_days -= (366 + (365 * 3));
992 }
Victor Stinner1ac42612014-02-21 09:27:17 +0100993#endif
Victor Stinner87094902019-04-09 19:12:26 +0200994
995 tm.tm_wday = -1; /* sentinel; original value ignored */
996 tt = mktime(&tm);
997
Alexander Belopolskyb7d40d12011-01-11 01:21:25 +0000998 /* Return value of -1 does not necessarily mean an error, but tm_wday
Ezio Melotti13925002011-03-16 11:05:33 +0200999 * cannot remain set to -1 if mktime succeeded. */
Victor Stinner93037492013-06-25 22:54:35 +02001000 if (tt == (time_t)(-1)
Victor Stinner93037492013-06-25 22:54:35 +02001001 /* Return value of -1 does not necessarily mean an error, but
1002 * tm_wday cannot remain set to -1 if mktime succeeded. */
Victor Stinner87094902019-04-09 19:12:26 +02001003 && tm.tm_wday == -1)
Victor Stinner93037492013-06-25 22:54:35 +02001004 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001005 PyErr_SetString(PyExc_OverflowError,
1006 "mktime argument out of range");
1007 return NULL;
1008 }
Victor Stinner87094902019-04-09 19:12:26 +02001009
1010#ifdef _AIX
1011 if (delta_days != 0) {
1012 tm.tm_year = orig_tm_year;
1013 if (tm.tm_wday != -1) {
1014 tm.tm_wday = (tm.tm_wday + delta_days) % 7;
1015 }
1016 tt += delta_days * (24 * 3600);
1017 }
1018#endif
1019
Victor Stinner4195b5c2012-02-08 23:03:19 +01001020 return PyFloat_FromDouble((double)tt);
Guido van Rossum234f9421993-06-17 12:35:49 +00001021}
Guido van Rossum0ef577b1998-06-27 20:38:36 +00001022
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001023PyDoc_STRVAR(mktime_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +00001024"mktime(tuple) -> floating point number\n\
1025\n\
Alexander Belopolskyc142bba2012-06-13 22:15:26 -04001026Convert a time tuple in local time to seconds since the Epoch.\n\
1027Note that mktime(gmtime(0)) will not generally return zero for most\n\
1028time zones; instead the returned value will either be equal to that\n\
1029of the timezone or altzone attributes on the time module.");
Guido van Rossum60cd8131998-03-06 17:16:21 +00001030#endif /* HAVE_MKTIME */
Guido van Rossum234f9421993-06-17 12:35:49 +00001031
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001032#ifdef HAVE_WORKING_TZSET
Victor Stinner3bb150d2018-12-03 13:45:38 +01001033static int init_timezone(PyObject *module);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001034
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001035static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001036time_tzset(PyObject *self, PyObject *unused)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001037{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001038 PyObject* m;
Fred Drake9bb74322002-04-01 14:49:59 +00001039
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001040 m = PyImport_ImportModuleNoBlock("time");
1041 if (m == NULL) {
1042 return NULL;
1043 }
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001044
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001045 tzset();
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001046
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001047 /* Reset timezone, altzone, daylight and tzname */
Victor Stinner3bb150d2018-12-03 13:45:38 +01001048 if (init_timezone(m) < 0) {
Victor Stinner503ce5c2018-12-01 00:39:36 +01001049 return NULL;
1050 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001051 Py_DECREF(m);
Victor Stinner2ff51b82013-07-17 21:42:45 +02001052 if (PyErr_Occurred())
1053 return NULL;
Tim Peters1b6f7a92004-06-20 02:50:16 +00001054
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001055 Py_RETURN_NONE;
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001056}
1057
1058PyDoc_STRVAR(tzset_doc,
R. David Murray4d55bf92010-12-14 00:55:46 +00001059"tzset()\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001060\n\
1061Initialize, or reinitialize, the local timezone to the value stored in\n\
1062os.environ['TZ']. The TZ environment variable should be specified in\n\
Neal Norwitzdc8e1942004-07-20 22:34:37 +00001063standard Unix timezone format as documented in the tzset man page\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001064(eg. 'US/Eastern', 'Europe/Amsterdam'). Unknown timezones will silently\n\
1065fall back to UTC. If the TZ environment variable is not set, the local\n\
1066timezone is set to the systems best guess of wallclock time.\n\
1067Changing the TZ environment variable without calling tzset *may* change\n\
1068the local timezone used by methods such as localtime, but this behaviour\n\
1069should not be relied on.");
1070#endif /* HAVE_WORKING_TZSET */
1071
Victor Stinnerae586492014-09-02 23:18:25 +02001072static PyObject *
Victor Stinnerec895392012-04-29 02:41:27 +02001073time_monotonic(PyObject *self, PyObject *unused)
Victor Stinner071eca32012-03-15 01:17:09 +01001074{
Victor Stinnerc29b5852017-11-02 07:28:27 -07001075 _PyTime_t t = _PyTime_GetMonotonicClock();
1076 return _PyFloat_FromPyTime(t);
Victor Stinner071eca32012-03-15 01:17:09 +01001077}
1078
Victor Stinnerec895392012-04-29 02:41:27 +02001079PyDoc_STRVAR(monotonic_doc,
1080"monotonic() -> float\n\
Victor Stinner8b302012012-02-07 23:29:46 +01001081\n\
Victor Stinnerec895392012-04-29 02:41:27 +02001082Monotonic clock, cannot go backward.");
Victor Stinnerec919cc2012-03-15 00:58:32 +01001083
Victor Stinnerec895392012-04-29 02:41:27 +02001084static PyObject *
Victor Stinnerc29b5852017-11-02 07:28:27 -07001085time_monotonic_ns(PyObject *self, PyObject *unused)
1086{
1087 _PyTime_t t = _PyTime_GetMonotonicClock();
1088 return _PyTime_AsNanosecondsObject(t);
1089}
1090
1091PyDoc_STRVAR(monotonic_ns_doc,
1092"monotonic_ns() -> int\n\
1093\n\
1094Monotonic clock, cannot go backward, as nanoseconds.");
1095
1096static PyObject *
Victor Stinnerec895392012-04-29 02:41:27 +02001097time_perf_counter(PyObject *self, PyObject *unused)
1098{
1099 return perf_counter(NULL);
1100}
1101
1102PyDoc_STRVAR(perf_counter_doc,
1103"perf_counter() -> float\n\
1104\n\
1105Performance counter for benchmarking.");
1106
Victor Stinnerc29b5852017-11-02 07:28:27 -07001107static PyObject *
1108time_perf_counter_ns(PyObject *self, PyObject *unused)
1109{
1110 _PyTime_t t = _PyTime_GetPerfCounter();
1111 return _PyTime_AsNanosecondsObject(t);
1112}
1113
1114PyDoc_STRVAR(perf_counter_ns_doc,
1115"perf_counter_ns() -> int\n\
1116\n\
1117Performance counter for benchmarking as nanoseconds.");
1118
1119static int
1120_PyTime_GetProcessTimeWithInfo(_PyTime_t *tp, _Py_clock_info_t *info)
Victor Stinnerec895392012-04-29 02:41:27 +02001121{
1122#if defined(MS_WINDOWS)
1123 HANDLE process;
1124 FILETIME creation_time, exit_time, kernel_time, user_time;
1125 ULARGE_INTEGER large;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001126 _PyTime_t ktime, utime, t;
Victor Stinnerec895392012-04-29 02:41:27 +02001127 BOOL ok;
1128
1129 process = GetCurrentProcess();
Victor Stinnerc29b5852017-11-02 07:28:27 -07001130 ok = GetProcessTimes(process, &creation_time, &exit_time,
1131 &kernel_time, &user_time);
1132 if (!ok) {
1133 PyErr_SetFromWindowsErr(0);
1134 return -1;
1135 }
Victor Stinnerec895392012-04-29 02:41:27 +02001136
Victor Stinnerec895392012-04-29 02:41:27 +02001137 if (info) {
1138 info->implementation = "GetProcessTimes()";
1139 info->resolution = 1e-7;
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001140 info->monotonic = 1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001141 info->adjustable = 0;
Victor Stinnerec895392012-04-29 02:41:27 +02001142 }
Victor Stinnerc29b5852017-11-02 07:28:27 -07001143
1144 large.u.LowPart = kernel_time.dwLowDateTime;
1145 large.u.HighPart = kernel_time.dwHighDateTime;
1146 ktime = large.QuadPart;
1147
1148 large.u.LowPart = user_time.dwLowDateTime;
1149 large.u.HighPart = user_time.dwHighDateTime;
1150 utime = large.QuadPart;
1151
1152 /* ktime and utime have a resolution of 100 nanoseconds */
1153 t = _PyTime_FromNanoseconds((ktime + utime) * 100);
1154 *tp = t;
1155 return 0;
Victor Stinnerec895392012-04-29 02:41:27 +02001156#else
1157
Victor Stinnerc29b5852017-11-02 07:28:27 -07001158 /* clock_gettime */
Victor Stinnerec895392012-04-29 02:41:27 +02001159#if defined(HAVE_CLOCK_GETTIME) \
1160 && (defined(CLOCK_PROCESS_CPUTIME_ID) || defined(CLOCK_PROF))
Victor Stinnerc29b5852017-11-02 07:28:27 -07001161 struct timespec ts;
Victor Stinnerec895392012-04-29 02:41:27 +02001162#ifdef CLOCK_PROF
1163 const clockid_t clk_id = CLOCK_PROF;
1164 const char *function = "clock_gettime(CLOCK_PROF)";
1165#else
1166 const clockid_t clk_id = CLOCK_PROCESS_CPUTIME_ID;
1167 const char *function = "clock_gettime(CLOCK_PROCESS_CPUTIME_ID)";
1168#endif
1169
Victor Stinnerc29b5852017-11-02 07:28:27 -07001170 if (clock_gettime(clk_id, &ts) == 0) {
Victor Stinnerec895392012-04-29 02:41:27 +02001171 if (info) {
1172 struct timespec res;
1173 info->implementation = function;
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001174 info->monotonic = 1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001175 info->adjustable = 0;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001176 if (clock_getres(clk_id, &res)) {
1177 PyErr_SetFromErrno(PyExc_OSError);
1178 return -1;
1179 }
1180 info->resolution = res.tv_sec + res.tv_nsec * 1e-9;
Victor Stinnerec895392012-04-29 02:41:27 +02001181 }
Victor Stinnerc29b5852017-11-02 07:28:27 -07001182
1183 if (_PyTime_FromTimespec(tp, &ts) < 0) {
1184 return -1;
1185 }
1186 return 0;
Victor Stinnerec895392012-04-29 02:41:27 +02001187 }
1188#endif
1189
Victor Stinnerc29b5852017-11-02 07:28:27 -07001190 /* getrusage(RUSAGE_SELF) */
Victor Stinnerec895392012-04-29 02:41:27 +02001191#if defined(HAVE_SYS_RESOURCE_H)
Victor Stinnerc29b5852017-11-02 07:28:27 -07001192 struct rusage ru;
1193
Victor Stinnerec895392012-04-29 02:41:27 +02001194 if (getrusage(RUSAGE_SELF, &ru) == 0) {
Victor Stinnerc29b5852017-11-02 07:28:27 -07001195 _PyTime_t utime, stime;
1196
Victor Stinnerec895392012-04-29 02:41:27 +02001197 if (info) {
1198 info->implementation = "getrusage(RUSAGE_SELF)";
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001199 info->monotonic = 1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001200 info->adjustable = 0;
Victor Stinnerec895392012-04-29 02:41:27 +02001201 info->resolution = 1e-6;
1202 }
Victor Stinnerc29b5852017-11-02 07:28:27 -07001203
1204 if (_PyTime_FromTimeval(&utime, &ru.ru_utime) < 0) {
1205 return -1;
1206 }
1207 if (_PyTime_FromTimeval(&stime, &ru.ru_stime) < 0) {
1208 return -1;
1209 }
1210
1211 _PyTime_t total = utime + utime;
1212 *tp = total;
1213 return 0;
Victor Stinnerec895392012-04-29 02:41:27 +02001214 }
1215#endif
1216
Victor Stinnerc29b5852017-11-02 07:28:27 -07001217 /* times() */
Victor Stinnerec895392012-04-29 02:41:27 +02001218#ifdef HAVE_TIMES
Victor Stinnerc29b5852017-11-02 07:28:27 -07001219 struct tms t;
1220
Victor Stinnerec895392012-04-29 02:41:27 +02001221 if (times(&t) != (clock_t)-1) {
Victor Stinnerc29b5852017-11-02 07:28:27 -07001222 static long ticks_per_second = -1;
Victor Stinnerec895392012-04-29 02:41:27 +02001223
1224 if (ticks_per_second == -1) {
Victor Stinnerc29b5852017-11-02 07:28:27 -07001225 long freq;
Victor Stinnerec895392012-04-29 02:41:27 +02001226#if defined(HAVE_SYSCONF) && defined(_SC_CLK_TCK)
Victor Stinnerc29b5852017-11-02 07:28:27 -07001227 freq = sysconf(_SC_CLK_TCK);
1228 if (freq < 1) {
1229 freq = -1;
1230 }
Victor Stinnerec895392012-04-29 02:41:27 +02001231#elif defined(HZ)
Victor Stinnerc29b5852017-11-02 07:28:27 -07001232 freq = HZ;
Victor Stinnerec895392012-04-29 02:41:27 +02001233#else
Victor Stinnerc29b5852017-11-02 07:28:27 -07001234 freq = 60; /* magic fallback value; may be bogus */
Victor Stinnerec895392012-04-29 02:41:27 +02001235#endif
Victor Stinnerc29b5852017-11-02 07:28:27 -07001236
1237 if (freq != -1) {
1238 /* check that _PyTime_MulDiv(t, SEC_TO_NS, ticks_per_second)
1239 cannot overflow below */
Serhiy Storchakabfe4fd52018-02-09 17:31:26 +02001240#if LONG_MAX > _PyTime_MAX / SEC_TO_NS
Victor Stinnerc29b5852017-11-02 07:28:27 -07001241 if ((_PyTime_t)freq > _PyTime_MAX / SEC_TO_NS) {
1242 PyErr_SetString(PyExc_OverflowError,
1243 "_SC_CLK_TCK is too large");
1244 return -1;
1245 }
Serhiy Storchakabfe4fd52018-02-09 17:31:26 +02001246#endif
Victor Stinnerc29b5852017-11-02 07:28:27 -07001247
1248 ticks_per_second = freq;
1249 }
Victor Stinnerec895392012-04-29 02:41:27 +02001250 }
1251
1252 if (ticks_per_second != -1) {
Victor Stinnerec895392012-04-29 02:41:27 +02001253 if (info) {
1254 info->implementation = "times()";
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001255 info->monotonic = 1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001256 info->adjustable = 0;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001257 info->resolution = 1.0 / (double)ticks_per_second;
Victor Stinnerec895392012-04-29 02:41:27 +02001258 }
Victor Stinnerc29b5852017-11-02 07:28:27 -07001259
1260 _PyTime_t total;
1261 total = _PyTime_MulDiv(t.tms_utime, SEC_TO_NS, ticks_per_second);
1262 total += _PyTime_MulDiv(t.tms_stime, SEC_TO_NS, ticks_per_second);
1263 *tp = total;
1264 return 0;
Victor Stinnerec895392012-04-29 02:41:27 +02001265 }
1266 }
1267#endif
1268
Victor Stinnerc29b5852017-11-02 07:28:27 -07001269 /* clock */
Victor Stinner53e22bf2016-07-08 17:55:01 +02001270 /* Currently, Python 3 requires clock() to build: see issue #22624 */
Victor Stinnerc29b5852017-11-02 07:28:27 -07001271 return _PyTime_GetClockWithInfo(tp, info);
Victor Stinnerec895392012-04-29 02:41:27 +02001272#endif
1273}
1274
1275static PyObject *
1276time_process_time(PyObject *self, PyObject *unused)
1277{
Victor Stinnerc29b5852017-11-02 07:28:27 -07001278 _PyTime_t t;
1279 if (_PyTime_GetProcessTimeWithInfo(&t, NULL) < 0) {
1280 return NULL;
1281 }
1282 return _PyFloat_FromPyTime(t);
Victor Stinnerec895392012-04-29 02:41:27 +02001283}
1284
1285PyDoc_STRVAR(process_time_doc,
1286"process_time() -> float\n\
1287\n\
1288Process time for profiling: sum of the kernel and user-space CPU time.");
1289
Victor Stinnerc29b5852017-11-02 07:28:27 -07001290static PyObject *
1291time_process_time_ns(PyObject *self, PyObject *unused)
1292{
1293 _PyTime_t t;
1294 if (_PyTime_GetProcessTimeWithInfo(&t, NULL) < 0) {
1295 return NULL;
1296 }
1297 return _PyTime_AsNanosecondsObject(t);
1298}
1299
1300PyDoc_STRVAR(process_time_ns_doc,
1301"process_time() -> int\n\
1302\n\
1303Process time for profiling as nanoseconds:\n\
1304sum of the kernel and user-space CPU time.");
1305
Victor Stinnerec895392012-04-29 02:41:27 +02001306
Antoine Pitrou4bd41c92017-11-15 22:52:21 +01001307#if defined(MS_WINDOWS)
1308#define HAVE_THREAD_TIME
1309static int
1310_PyTime_GetThreadTimeWithInfo(_PyTime_t *tp, _Py_clock_info_t *info)
1311{
1312 HANDLE thread;
1313 FILETIME creation_time, exit_time, kernel_time, user_time;
1314 ULARGE_INTEGER large;
1315 _PyTime_t ktime, utime, t;
1316 BOOL ok;
1317
1318 thread = GetCurrentThread();
1319 ok = GetThreadTimes(thread, &creation_time, &exit_time,
1320 &kernel_time, &user_time);
1321 if (!ok) {
1322 PyErr_SetFromWindowsErr(0);
1323 return -1;
1324 }
1325
1326 if (info) {
1327 info->implementation = "GetThreadTimes()";
1328 info->resolution = 1e-7;
1329 info->monotonic = 1;
1330 info->adjustable = 0;
1331 }
1332
1333 large.u.LowPart = kernel_time.dwLowDateTime;
1334 large.u.HighPart = kernel_time.dwHighDateTime;
1335 ktime = large.QuadPart;
1336
1337 large.u.LowPart = user_time.dwLowDateTime;
1338 large.u.HighPart = user_time.dwHighDateTime;
1339 utime = large.QuadPart;
1340
1341 /* ktime and utime have a resolution of 100 nanoseconds */
1342 t = _PyTime_FromNanoseconds((ktime + utime) * 100);
1343 *tp = t;
1344 return 0;
1345}
1346
1347#elif defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_PROCESS_CPUTIME_ID)
1348#define HAVE_THREAD_TIME
1349static int
1350_PyTime_GetThreadTimeWithInfo(_PyTime_t *tp, _Py_clock_info_t *info)
1351{
1352 struct timespec ts;
1353 const clockid_t clk_id = CLOCK_THREAD_CPUTIME_ID;
1354 const char *function = "clock_gettime(CLOCK_THREAD_CPUTIME_ID)";
1355
1356 if (clock_gettime(clk_id, &ts)) {
1357 PyErr_SetFromErrno(PyExc_OSError);
1358 return -1;
1359 }
1360 if (info) {
1361 struct timespec res;
1362 info->implementation = function;
1363 info->monotonic = 1;
1364 info->adjustable = 0;
1365 if (clock_getres(clk_id, &res)) {
1366 PyErr_SetFromErrno(PyExc_OSError);
1367 return -1;
1368 }
1369 info->resolution = res.tv_sec + res.tv_nsec * 1e-9;
1370 }
1371
1372 if (_PyTime_FromTimespec(tp, &ts) < 0) {
1373 return -1;
1374 }
1375 return 0;
1376}
1377#endif
1378
1379#ifdef HAVE_THREAD_TIME
1380static PyObject *
1381time_thread_time(PyObject *self, PyObject *unused)
1382{
1383 _PyTime_t t;
1384 if (_PyTime_GetThreadTimeWithInfo(&t, NULL) < 0) {
1385 return NULL;
1386 }
1387 return _PyFloat_FromPyTime(t);
1388}
1389
1390PyDoc_STRVAR(thread_time_doc,
1391"thread_time() -> float\n\
1392\n\
1393Thread time for profiling: sum of the kernel and user-space CPU time.");
1394
1395static PyObject *
1396time_thread_time_ns(PyObject *self, PyObject *unused)
1397{
1398 _PyTime_t t;
1399 if (_PyTime_GetThreadTimeWithInfo(&t, NULL) < 0) {
1400 return NULL;
1401 }
1402 return _PyTime_AsNanosecondsObject(t);
1403}
1404
1405PyDoc_STRVAR(thread_time_ns_doc,
1406"thread_time() -> int\n\
1407\n\
1408Thread time for profiling as nanoseconds:\n\
1409sum of the kernel and user-space CPU time.");
1410#endif
1411
1412
Victor Stinnerec895392012-04-29 02:41:27 +02001413static PyObject *
1414time_get_clock_info(PyObject *self, PyObject *args)
1415{
1416 char *name;
Victor Stinnerec895392012-04-29 02:41:27 +02001417 _Py_clock_info_t info;
Victor Stinnerbda4b882012-06-12 22:11:44 +02001418 PyObject *obj = NULL, *dict, *ns;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001419 _PyTime_t t;
Victor Stinnerec895392012-04-29 02:41:27 +02001420
Victor Stinnerc29b5852017-11-02 07:28:27 -07001421 if (!PyArg_ParseTuple(args, "s:get_clock_info", &name)) {
Victor Stinnerec895392012-04-29 02:41:27 +02001422 return NULL;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001423 }
Victor Stinnerec895392012-04-29 02:41:27 +02001424
1425#ifdef Py_DEBUG
1426 info.implementation = NULL;
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001427 info.monotonic = -1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001428 info.adjustable = -1;
Victor Stinnerec895392012-04-29 02:41:27 +02001429 info.resolution = -1.0;
1430#else
1431 info.implementation = "";
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001432 info.monotonic = 0;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001433 info.adjustable = 0;
Victor Stinnerec895392012-04-29 02:41:27 +02001434 info.resolution = 1.0;
1435#endif
1436
Victor Stinnerc29b5852017-11-02 07:28:27 -07001437 if (strcmp(name, "time") == 0) {
1438 if (_PyTime_GetSystemClockWithInfo(&t, &info) < 0) {
1439 return NULL;
1440 }
1441 }
Victor Stinnerc29b5852017-11-02 07:28:27 -07001442 else if (strcmp(name, "monotonic") == 0) {
1443 if (_PyTime_GetMonotonicClockWithInfo(&t, &info) < 0) {
1444 return NULL;
1445 }
1446 }
1447 else if (strcmp(name, "perf_counter") == 0) {
1448 if (_PyTime_GetPerfCounterWithInfo(&t, &info) < 0) {
1449 return NULL;
1450 }
1451 }
1452 else if (strcmp(name, "process_time") == 0) {
1453 if (_PyTime_GetProcessTimeWithInfo(&t, &info) < 0) {
1454 return NULL;
1455 }
1456 }
Antoine Pitrou4bd41c92017-11-15 22:52:21 +01001457#ifdef HAVE_THREAD_TIME
1458 else if (strcmp(name, "thread_time") == 0) {
1459 if (_PyTime_GetThreadTimeWithInfo(&t, &info) < 0) {
1460 return NULL;
1461 }
1462 }
1463#endif
Victor Stinnerec895392012-04-29 02:41:27 +02001464 else {
1465 PyErr_SetString(PyExc_ValueError, "unknown clock");
1466 return NULL;
1467 }
Victor Stinnerec895392012-04-29 02:41:27 +02001468
Victor Stinnerbda4b882012-06-12 22:11:44 +02001469 dict = PyDict_New();
Victor Stinnerc29b5852017-11-02 07:28:27 -07001470 if (dict == NULL) {
Victor Stinnerec895392012-04-29 02:41:27 +02001471 return NULL;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001472 }
Victor Stinnerec895392012-04-29 02:41:27 +02001473
1474 assert(info.implementation != NULL);
1475 obj = PyUnicode_FromString(info.implementation);
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, "implementation", 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
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001484 assert(info.monotonic != -1);
1485 obj = PyBool_FromLong(info.monotonic);
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, "monotonic", 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
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001494 assert(info.adjustable != -1);
1495 obj = PyBool_FromLong(info.adjustable);
Victor Stinnerc29b5852017-11-02 07:28:27 -07001496 if (obj == NULL) {
Victor Stinnerec895392012-04-29 02:41:27 +02001497 goto error;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001498 }
1499 if (PyDict_SetItemString(dict, "adjustable", obj) == -1) {
Victor Stinnerbda4b882012-06-12 22:11:44 +02001500 goto error;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001501 }
Victor Stinnerbda4b882012-06-12 22:11:44 +02001502 Py_CLEAR(obj);
Victor Stinnerec895392012-04-29 02:41:27 +02001503
1504 assert(info.resolution > 0.0);
1505 assert(info.resolution <= 1.0);
1506 obj = PyFloat_FromDouble(info.resolution);
Victor Stinnerc29b5852017-11-02 07:28:27 -07001507 if (obj == NULL) {
Victor Stinnerec895392012-04-29 02:41:27 +02001508 goto error;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001509 }
1510 if (PyDict_SetItemString(dict, "resolution", obj) == -1) {
Victor Stinnerbda4b882012-06-12 22:11:44 +02001511 goto error;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001512 }
Victor Stinnerbda4b882012-06-12 22:11:44 +02001513 Py_CLEAR(obj);
Victor Stinnerec895392012-04-29 02:41:27 +02001514
Victor Stinnerbda4b882012-06-12 22:11:44 +02001515 ns = _PyNamespace_New(dict);
1516 Py_DECREF(dict);
1517 return ns;
Victor Stinnerec895392012-04-29 02:41:27 +02001518
1519error:
Victor Stinnerbda4b882012-06-12 22:11:44 +02001520 Py_DECREF(dict);
1521 Py_XDECREF(obj);
Victor Stinnerec895392012-04-29 02:41:27 +02001522 return NULL;
1523}
1524
1525PyDoc_STRVAR(get_clock_info_doc,
1526"get_clock_info(name: str) -> dict\n\
1527\n\
1528Get information of the specified clock.");
Victor Stinner8b302012012-02-07 23:29:46 +01001529
Benjamin Petersonc510c6b2018-09-20 19:52:18 -07001530#ifndef HAVE_DECL_TZNAME
Victor Stinner1fb399b2018-09-17 13:56:17 -07001531static void
1532get_zone(char *zone, int n, struct tm *p)
1533{
1534#ifdef HAVE_STRUCT_TM_TM_ZONE
1535 strncpy(zone, p->tm_zone ? p->tm_zone : " ", n);
1536#else
1537 tzset();
1538 strftime(zone, n, "%Z", p);
1539#endif
1540}
1541
Victor Stinner503ce5c2018-12-01 00:39:36 +01001542static time_t
Victor Stinner1fb399b2018-09-17 13:56:17 -07001543get_gmtoff(time_t t, struct tm *p)
1544{
1545#ifdef HAVE_STRUCT_TM_TM_ZONE
1546 return p->tm_gmtoff;
1547#else
1548 return timegm(p) - t;
1549#endif
1550}
Benjamin Petersonc510c6b2018-09-20 19:52:18 -07001551#endif // !HAVE_DECL_TZNAME
Victor Stinner1fb399b2018-09-17 13:56:17 -07001552
Victor Stinner503ce5c2018-12-01 00:39:36 +01001553static int
Victor Stinner3bb150d2018-12-03 13:45:38 +01001554init_timezone(PyObject *m)
Victor Stinner503ce5c2018-12-01 00:39:36 +01001555{
1556 assert(!PyErr_Occurred());
1557
Martin v. Löwis1a214512008-06-11 05:26:20 +00001558 /* This code moved from PyInit_time wholesale to allow calling it from
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001559 time_tzset. In the future, some parts of it can be moved back
1560 (for platforms that don't HAVE_WORKING_TZSET, when we know what they
1561 are), and the extraneous calls to tzset(3) should be removed.
1562 I haven't done this yet, as I don't want to change this code as
1563 little as possible when introducing the time.tzset and time.tzsetwall
1564 methods. This should simply be a method of doing the following once,
1565 at the top of this function and removing the call to tzset() from
1566 time_tzset():
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001567
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001568 #ifdef HAVE_TZSET
1569 tzset()
1570 #endif
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001571
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001572 And I'm lazy and hate C so nyer.
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001573 */
Benjamin Petersonc510c6b2018-09-20 19:52:18 -07001574#ifdef HAVE_DECL_TZNAME
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001575 PyObject *otz0, *otz1;
1576 tzset();
Zackery Spytz6673dec2019-02-25 16:56:44 -07001577 PyModule_AddIntConstant(m, "timezone", _Py_timezone);
Guido van Rossumb6775db1994-08-01 11:34:53 +00001578#ifdef HAVE_ALTZONE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001579 PyModule_AddIntConstant(m, "altzone", altzone);
Guido van Rossumb6775db1994-08-01 11:34:53 +00001580#else
Zackery Spytz6673dec2019-02-25 16:56:44 -07001581 PyModule_AddIntConstant(m, "altzone", _Py_timezone-3600);
Guido van Rossumb6775db1994-08-01 11:34:53 +00001582#endif
Zackery Spytz6673dec2019-02-25 16:56:44 -07001583 PyModule_AddIntConstant(m, "daylight", _Py_daylight);
1584 otz0 = PyUnicode_DecodeLocale(_Py_tzname[0], "surrogateescape");
Benjamin Petersonc510c6b2018-09-20 19:52:18 -07001585 if (otz0 == NULL) {
Victor Stinnerab661492018-12-03 12:02:43 +01001586 return -1;
Victor Stinner1fb399b2018-09-17 13:56:17 -07001587 }
Zackery Spytz6673dec2019-02-25 16:56:44 -07001588 otz1 = PyUnicode_DecodeLocale(_Py_tzname[1], "surrogateescape");
Benjamin Petersonc510c6b2018-09-20 19:52:18 -07001589 if (otz1 == NULL) {
1590 Py_DECREF(otz0);
Victor Stinnerab661492018-12-03 12:02:43 +01001591 return -1;
Benjamin Petersonc510c6b2018-09-20 19:52:18 -07001592 }
1593 PyObject *tzname_obj = Py_BuildValue("(NN)", otz0, otz1);
Victor Stinnerab661492018-12-03 12:02:43 +01001594 if (tzname_obj == NULL) {
1595 return -1;
1596 }
Benjamin Petersonc510c6b2018-09-20 19:52:18 -07001597 PyModule_AddObject(m, "tzname", tzname_obj);
1598#else // !HAVE_DECL_TZNAME
1599 static const time_t YEAR = (365 * 24 + 6) * 3600;
1600 time_t t;
1601 struct tm p;
Victor Stinner503ce5c2018-12-01 00:39:36 +01001602 time_t janzone_t, julyzone_t;
Benjamin Petersonc510c6b2018-09-20 19:52:18 -07001603 char janname[10], julyname[10];
1604 t = (time((time_t *)0) / YEAR) * YEAR;
1605 _PyTime_localtime(t, &p);
1606 get_zone(janname, 9, &p);
Victor Stinner503ce5c2018-12-01 00:39:36 +01001607 janzone_t = -get_gmtoff(t, &p);
Benjamin Petersonc510c6b2018-09-20 19:52:18 -07001608 janname[9] = '\0';
1609 t += YEAR/2;
1610 _PyTime_localtime(t, &p);
1611 get_zone(julyname, 9, &p);
Victor Stinner503ce5c2018-12-01 00:39:36 +01001612 julyzone_t = -get_gmtoff(t, &p);
Benjamin Petersonc510c6b2018-09-20 19:52:18 -07001613 julyname[9] = '\0';
1614
Victor Stinner503ce5c2018-12-01 00:39:36 +01001615 /* Sanity check, don't check for the validity of timezones.
1616 In practice, it should be more in range -12 hours .. +14 hours. */
1617#define MAX_TIMEZONE (48 * 3600)
1618 if (janzone_t < -MAX_TIMEZONE || janzone_t > MAX_TIMEZONE
1619 || julyzone_t < -MAX_TIMEZONE || julyzone_t > MAX_TIMEZONE)
1620 {
1621 PyErr_SetString(PyExc_RuntimeError, "invalid GMT offset");
1622 return -1;
1623 }
1624 int janzone = (int)janzone_t;
1625 int julyzone = (int)julyzone_t;
1626
Benjamin Petersonc510c6b2018-09-20 19:52:18 -07001627 PyObject *tzname_obj;
1628 if (janzone < julyzone) {
1629 /* DST is reversed in the southern hemisphere */
1630 PyModule_AddIntConstant(m, "timezone", julyzone);
1631 PyModule_AddIntConstant(m, "altzone", janzone);
1632 PyModule_AddIntConstant(m, "daylight", janzone != julyzone);
1633 tzname_obj = Py_BuildValue("(zz)", julyname, janname);
1634 } else {
1635 PyModule_AddIntConstant(m, "timezone", janzone);
1636 PyModule_AddIntConstant(m, "altzone", julyzone);
1637 PyModule_AddIntConstant(m, "daylight", janzone != julyzone);
1638 tzname_obj = Py_BuildValue("(zz)", janname, julyname);
1639 }
Victor Stinner503ce5c2018-12-01 00:39:36 +01001640 if (tzname_obj == NULL) {
1641 return -1;
1642 }
Benjamin Petersonc510c6b2018-09-20 19:52:18 -07001643 PyModule_AddObject(m, "tzname", tzname_obj);
1644#endif // !HAVE_DECL_TZNAME
Victor Stinner503ce5c2018-12-01 00:39:36 +01001645
1646 if (PyErr_Occurred()) {
1647 return -1;
1648 }
1649 return 0;
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001650}
1651
1652
1653static PyMethodDef time_methods[] = {
Victor Stinner4195b5c2012-02-08 23:03:19 +01001654 {"time", time_time, METH_NOARGS, time_doc},
Victor Stinnerc29b5852017-11-02 07:28:27 -07001655 {"time_ns", time_time_ns, METH_NOARGS, time_ns_doc},
Victor Stinnere0be4232011-10-25 13:06:09 +02001656#ifdef HAVE_CLOCK_GETTIME
Victor Stinner4195b5c2012-02-08 23:03:19 +01001657 {"clock_gettime", time_clock_gettime, METH_VARARGS, clock_gettime_doc},
Victor Stinnerc29b5852017-11-02 07:28:27 -07001658 {"clock_gettime_ns",time_clock_gettime_ns, METH_VARARGS, clock_gettime_ns_doc},
Benjamin Peterson37098cd2016-09-13 22:55:09 -07001659#endif
1660#ifdef HAVE_CLOCK_SETTIME
Victor Stinner30d79472012-04-03 00:45:07 +02001661 {"clock_settime", time_clock_settime, METH_VARARGS, clock_settime_doc},
Victor Stinnerc29b5852017-11-02 07:28:27 -07001662 {"clock_settime_ns",time_clock_settime_ns, METH_VARARGS, clock_settime_ns_doc},
Benjamin Peterson37098cd2016-09-13 22:55:09 -07001663#endif
1664#ifdef HAVE_CLOCK_GETRES
Victor Stinner4195b5c2012-02-08 23:03:19 +01001665 {"clock_getres", time_clock_getres, METH_VARARGS, clock_getres_doc},
Victor Stinnere0be4232011-10-25 13:06:09 +02001666#endif
pdoxe14679c2017-10-05 00:01:56 -07001667#ifdef HAVE_PTHREAD_GETCPUCLOCKID
1668 {"pthread_getcpuclockid", time_pthread_getcpuclockid, METH_VARARGS, pthread_getcpuclockid_doc},
1669#endif
Victor Stinnercb29f012015-03-27 13:31:18 +01001670 {"sleep", time_sleep, METH_O, sleep_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001671 {"gmtime", time_gmtime, METH_VARARGS, gmtime_doc},
1672 {"localtime", time_localtime, METH_VARARGS, localtime_doc},
1673 {"asctime", time_asctime, METH_VARARGS, asctime_doc},
1674 {"ctime", time_ctime, METH_VARARGS, ctime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001675#ifdef HAVE_MKTIME
Victor Stinner4195b5c2012-02-08 23:03:19 +01001676 {"mktime", time_mktime, METH_O, mktime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001677#endif
1678#ifdef HAVE_STRFTIME
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001679 {"strftime", time_strftime, METH_VARARGS, strftime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001680#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001681 {"strptime", time_strptime, METH_VARARGS, strptime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001682#ifdef HAVE_WORKING_TZSET
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001683 {"tzset", time_tzset, METH_NOARGS, tzset_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001684#endif
Victor Stinnerec895392012-04-29 02:41:27 +02001685 {"monotonic", time_monotonic, METH_NOARGS, monotonic_doc},
Victor Stinnerc29b5852017-11-02 07:28:27 -07001686 {"monotonic_ns", time_monotonic_ns, METH_NOARGS, monotonic_ns_doc},
Victor Stinnerec895392012-04-29 02:41:27 +02001687 {"process_time", time_process_time, METH_NOARGS, process_time_doc},
Victor Stinnerc29b5852017-11-02 07:28:27 -07001688 {"process_time_ns", time_process_time_ns, METH_NOARGS, process_time_ns_doc},
Antoine Pitrou4bd41c92017-11-15 22:52:21 +01001689#ifdef HAVE_THREAD_TIME
1690 {"thread_time", time_thread_time, METH_NOARGS, thread_time_doc},
1691 {"thread_time_ns", time_thread_time_ns, METH_NOARGS, thread_time_ns_doc},
1692#endif
Victor Stinnerec895392012-04-29 02:41:27 +02001693 {"perf_counter", time_perf_counter, METH_NOARGS, perf_counter_doc},
Victor Stinnerc29b5852017-11-02 07:28:27 -07001694 {"perf_counter_ns", time_perf_counter_ns, METH_NOARGS, perf_counter_ns_doc},
Victor Stinnerec895392012-04-29 02:41:27 +02001695 {"get_clock_info", time_get_clock_info, METH_VARARGS, get_clock_info_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001696 {NULL, NULL} /* sentinel */
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001697};
1698
1699
1700PyDoc_STRVAR(module_doc,
1701"This module provides various functions to manipulate time values.\n\
1702\n\
1703There are two standard representations of time. One is the number\n\
1704of seconds since the Epoch, in UTC (a.k.a. GMT). It may be an integer\n\
1705or a floating point number (to represent fractions of seconds).\n\
1706The Epoch is system-defined; on Unix, it is generally January 1st, 1970.\n\
1707The actual value can be retrieved by calling gmtime(0).\n\
1708\n\
1709The other representation is a tuple of 9 integers giving local time.\n\
1710The tuple items are:\n\
Alexander Belopolsky03163ac2011-05-02 12:20:52 -04001711 year (including century, e.g. 1998)\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001712 month (1-12)\n\
1713 day (1-31)\n\
1714 hours (0-23)\n\
1715 minutes (0-59)\n\
1716 seconds (0-59)\n\
1717 weekday (0-6, Monday is 0)\n\
1718 Julian day (day in the year, 1-366)\n\
1719 DST (Daylight Savings Time) flag (-1, 0 or 1)\n\
1720If the DST flag is 0, the time is given in the regular time zone;\n\
1721if it is 1, the time is given in the DST time zone;\n\
Cheryl Sabella703ff382017-10-11 09:29:14 -04001722if it is -1, mktime() should guess based on the date and time.\n");
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001723
1724
Martin v. Löwis1a214512008-06-11 05:26:20 +00001725
1726static struct PyModuleDef timemodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001727 PyModuleDef_HEAD_INIT,
1728 "time",
1729 module_doc,
1730 -1,
1731 time_methods,
1732 NULL,
1733 NULL,
1734 NULL,
1735 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00001736};
1737
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001738PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00001739PyInit_time(void)
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001740{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001741 PyObject *m;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001742 m = PyModule_Create(&timemodule);
1743 if (m == NULL)
1744 return NULL;
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001745
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001746 /* Set, or reset, module variables like time.timezone */
Victor Stinner3bb150d2018-12-03 13:45:38 +01001747 if (init_timezone(m) < 0) {
Victor Stinner503ce5c2018-12-01 00:39:36 +01001748 return NULL;
1749 }
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001750
Max Bélanger94451182018-10-20 17:07:54 -07001751#if defined(HAVE_CLOCK_GETTIME) || defined(HAVE_CLOCK_SETTIME) || defined(HAVE_CLOCK_GETRES)
1752
Benjamin Peterson37098cd2016-09-13 22:55:09 -07001753#ifdef CLOCK_REALTIME
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -04001754 PyModule_AddIntMacro(m, CLOCK_REALTIME);
Benjamin Peterson37098cd2016-09-13 22:55:09 -07001755#endif
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -04001756#ifdef CLOCK_MONOTONIC
1757 PyModule_AddIntMacro(m, CLOCK_MONOTONIC);
1758#endif
1759#ifdef CLOCK_MONOTONIC_RAW
1760 PyModule_AddIntMacro(m, CLOCK_MONOTONIC_RAW);
1761#endif
1762#ifdef CLOCK_HIGHRES
1763 PyModule_AddIntMacro(m, CLOCK_HIGHRES);
1764#endif
1765#ifdef CLOCK_PROCESS_CPUTIME_ID
1766 PyModule_AddIntMacro(m, CLOCK_PROCESS_CPUTIME_ID);
1767#endif
1768#ifdef CLOCK_THREAD_CPUTIME_ID
1769 PyModule_AddIntMacro(m, CLOCK_THREAD_CPUTIME_ID);
1770#endif
Victor Stinnera64ce972017-11-02 04:19:19 -07001771#ifdef CLOCK_PROF
1772 PyModule_AddIntMacro(m, CLOCK_PROF);
1773#endif
1774#ifdef CLOCK_BOOTTIME
1775 PyModule_AddIntMacro(m, CLOCK_BOOTTIME);
1776#endif
1777#ifdef CLOCK_UPTIME
1778 PyModule_AddIntMacro(m, CLOCK_UPTIME);
1779#endif
Joannah Nanjekye572168a2019-01-10 19:56:38 +03001780#ifdef CLOCK_UPTIME_RAW
1781 PyModule_AddIntMacro(m, CLOCK_UPTIME_RAW);
1782#endif
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -04001783
Max Bélanger94451182018-10-20 17:07:54 -07001784#endif /* defined(HAVE_CLOCK_GETTIME) || defined(HAVE_CLOCK_SETTIME) || defined(HAVE_CLOCK_GETRES) */
1785
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001786 if (!initialized) {
Victor Stinner1c8f0592013-07-22 22:24:54 +02001787 if (PyStructSequence_InitType2(&StructTimeType,
1788 &struct_time_type_desc) < 0)
1789 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001790 }
1791 Py_INCREF(&StructTimeType);
Alexander Belopolskyc142bba2012-06-13 22:15:26 -04001792 PyModule_AddIntConstant(m, "_STRUCT_TM_ITEMS", 11);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001793 PyModule_AddObject(m, "struct_time", (PyObject*) &StructTimeType);
1794 initialized = 1;
Benjamin Peterson5633c4f2018-09-14 09:09:04 -07001795
1796#if defined(__linux__) && !defined(__GLIBC__)
1797 struct tm tm;
Benjamin Petersonb93062b2018-09-14 10:39:13 -07001798 const time_t zero = 0;
1799 if (gmtime_r(&zero, &tm) != NULL)
Benjamin Peterson5633c4f2018-09-14 09:09:04 -07001800 utc_string = tm.tm_zone;
1801#endif
1802
Victor Stinner3bb150d2018-12-03 13:45:38 +01001803 if (PyErr_Occurred()) {
1804 return NULL;
1805 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001806 return m;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001807}
1808
Victor Stinnercb29f012015-03-27 13:31:18 +01001809/* Implement pysleep() for various platforms.
Guido van Rossumb6775db1994-08-01 11:34:53 +00001810 When interrupted (or when another error occurs), return -1 and
1811 set an exception; else return 0. */
1812
1813static int
Victor Stinnercb29f012015-03-27 13:31:18 +01001814pysleep(_PyTime_t secs)
Guido van Rossum426035c1991-02-19 12:27:35 +00001815{
Victor Stinnercb29f012015-03-27 13:31:18 +01001816 _PyTime_t deadline, monotonic;
Victor Stinner79d68f92015-03-19 21:54:09 +01001817#ifndef MS_WINDOWS
1818 struct timeval timeout;
Victor Stinner79d68f92015-03-19 21:54:09 +01001819 int err = 0;
1820#else
Victor Stinnercb29f012015-03-27 13:31:18 +01001821 _PyTime_t millisecs;
Victor Stinner79d68f92015-03-19 21:54:09 +01001822 unsigned long ul_millis;
1823 DWORD rc;
1824 HANDLE hInterruptEvent;
Victor Stinner0c2fd892015-03-17 10:49:17 +01001825#endif
Victor Stinner79d68f92015-03-19 21:54:09 +01001826
Victor Stinnercb29f012015-03-27 13:31:18 +01001827 deadline = _PyTime_GetMonotonicClock() + secs;
Victor Stinner79d68f92015-03-19 21:54:09 +01001828
1829 do {
1830#ifndef MS_WINDOWS
Victor Stinner869e1772015-03-30 03:49:14 +02001831 if (_PyTime_AsTimeval(secs, &timeout, _PyTime_ROUND_CEILING) < 0)
Victor Stinnercb29f012015-03-27 13:31:18 +01001832 return -1;
Victor Stinner79d68f92015-03-19 21:54:09 +01001833
1834 Py_BEGIN_ALLOW_THREADS
1835 err = select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &timeout);
1836 Py_END_ALLOW_THREADS
1837
1838 if (err == 0)
1839 break;
1840
1841 if (errno != EINTR) {
Victor Stinner0c2fd892015-03-17 10:49:17 +01001842 PyErr_SetFromErrno(PyExc_OSError);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001843 return -1;
1844 }
Victor Stinner79d68f92015-03-19 21:54:09 +01001845#else
Victor Stinner869e1772015-03-30 03:49:14 +02001846 millisecs = _PyTime_AsMilliseconds(secs, _PyTime_ROUND_CEILING);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001847 if (millisecs > (double)ULONG_MAX) {
1848 PyErr_SetString(PyExc_OverflowError,
1849 "sleep length is too large");
1850 return -1;
1851 }
Victor Stinner79d68f92015-03-19 21:54:09 +01001852
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001853 /* Allow sleep(0) to maintain win32 semantics, and as decreed
1854 * by Guido, only the main thread can be interrupted.
1855 */
1856 ul_millis = (unsigned long)millisecs;
Victor Stinner79d68f92015-03-19 21:54:09 +01001857 if (ul_millis == 0 || !_PyOS_IsMainThread()) {
1858 Py_BEGIN_ALLOW_THREADS
Victor Stinner0eac1302015-03-20 03:06:12 +01001859 Sleep(ul_millis);
Victor Stinner79d68f92015-03-19 21:54:09 +01001860 Py_END_ALLOW_THREADS
1861 break;
Victor Stinner945c82e2015-03-12 16:19:01 +01001862 }
Victor Stinner79d68f92015-03-19 21:54:09 +01001863
1864 hInterruptEvent = _PyOS_SigintEvent();
1865 ResetEvent(hInterruptEvent);
1866
1867 Py_BEGIN_ALLOW_THREADS
1868 rc = WaitForSingleObjectEx(hInterruptEvent, ul_millis, FALSE);
Victor Stinner0c2fd892015-03-17 10:49:17 +01001869 Py_END_ALLOW_THREADS
Victor Stinner79d68f92015-03-19 21:54:09 +01001870
1871 if (rc != WAIT_OBJECT_0)
1872 break;
Victor Stinner945c82e2015-03-12 16:19:01 +01001873#endif
Victor Stinner0c2fd892015-03-17 10:49:17 +01001874
Victor Stinner79d68f92015-03-19 21:54:09 +01001875 /* sleep was interrupted by SIGINT */
1876 if (PyErr_CheckSignals())
1877 return -1;
1878
Victor Stinnercb29f012015-03-27 13:31:18 +01001879 monotonic = _PyTime_GetMonotonicClock();
1880 secs = deadline - monotonic;
Victor Stinner6aa446c2015-03-30 21:33:51 +02001881 if (secs < 0)
Victor Stinner79d68f92015-03-19 21:54:09 +01001882 break;
1883 /* retry with the recomputed delay */
1884 } while (1);
1885
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001886 return 0;
Guido van Rossum80c9d881991-04-16 08:47:51 +00001887}