blob: bbfb7db7abde93e3ce6fb10cd2409edb898c3395 [file] [log] [blame]
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001/* Time module */
2
Barry Warsaw9a2a8a81996-12-06 23:32:14 +00003#include "Python.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +00004
Guido van Rossum87ce7bb1998-06-09 16:30:31 +00005#include <ctype.h>
6
Victor Stinnerec895392012-04-29 02:41:27 +02007#ifdef HAVE_SYS_TIMES_H
8#include <sys/times.h>
9#endif
10
Thomas Wouters0e3f5912006-08-11 14:57:12 +000011#ifdef HAVE_SYS_TYPES_H
Guido van Rossumb6775db1994-08-01 11:34:53 +000012#include <sys/types.h>
Victor Stinnerec895392012-04-29 02:41:27 +020013#endif
14
15#if defined(HAVE_SYS_RESOURCE_H)
16#include <sys/resource.h>
17#endif
Guido van Rossum6d946f91992-08-14 13:49:30 +000018
Guido van Rossumb6775db1994-08-01 11:34:53 +000019#ifdef QUICKWIN
20#include <io.h>
21#endif
22
pdoxe14679c2017-10-05 00:01:56 -070023#if defined(HAVE_PTHREAD_H)
24# include <pthread.h>
25#endif
26
Guido van Rossum7bf22de1997-12-02 20:34:19 +000027#if defined(__WATCOMC__) && !defined(__QNX__)
Guido van Rossumbceeac81996-05-23 22:53:47 +000028#include <i86.h>
29#else
Guido van Rossumcac6c721996-09-06 13:34:02 +000030#ifdef MS_WINDOWS
Mark Hammond975e3922002-07-16 01:29:19 +000031#define WIN32_LEAN_AND_MEAN
Guido van Rossum258ccd42001-03-02 06:53:29 +000032#include <windows.h>
Mark Hammond975e3922002-07-16 01:29:19 +000033#include "pythread.h"
Guido van Rossumcac6c721996-09-06 13:34:02 +000034#endif /* MS_WINDOWS */
Guido van Rossum7bf22de1997-12-02 20:34:19 +000035#endif /* !__WATCOMC__ || __QNX__ */
Guido van Rossum234f9421993-06-17 12:35:49 +000036
Miss Islington (bot)01b96642018-12-30 17:59:19 -080037#ifdef _Py_MEMORY_SANITIZER
38# include <sanitizer/msan_interface.h>
39#endif
40
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 Stinnerb8d01692012-04-13 23:44:05 +0200181 int clk_id;
Victor Stinnere0be4232011-10-25 13:06:09 +0200182 struct timespec tp;
183
Victor Stinnerc29b5852017-11-02 07:28:27 -0700184 if (!PyArg_ParseTuple(args, "i:clock_gettime", &clk_id)) {
Victor Stinnere0be4232011-10-25 13:06:09 +0200185 return NULL;
Victor Stinnerc29b5852017-11-02 07:28:27 -0700186 }
Victor Stinnere0be4232011-10-25 13:06:09 +0200187
188 ret = clock_gettime((clockid_t)clk_id, &tp);
Antoine Pitrou2c085602012-01-18 01:41:44 +0100189 if (ret != 0) {
Victor Stinnera734af32014-07-31 13:07:17 +0200190 PyErr_SetFromErrno(PyExc_OSError);
Antoine Pitrou2c085602012-01-18 01:41:44 +0100191 return NULL;
192 }
Victor Stinner4195b5c2012-02-08 23:03:19 +0100193 return PyFloat_FromDouble(tp.tv_sec + tp.tv_nsec * 1e-9);
Victor Stinnere0be4232011-10-25 13:06:09 +0200194}
195
196PyDoc_STRVAR(clock_gettime_doc,
Victor Stinnerc29b5852017-11-02 07:28:27 -0700197"clock_gettime(clk_id) -> float\n\
Victor Stinnere0be4232011-10-25 13:06:09 +0200198\n\
199Return the time of the specified clock clk_id.");
Victor Stinnerc29b5852017-11-02 07:28:27 -0700200
201static PyObject *
202time_clock_gettime_ns(PyObject *self, PyObject *args)
203{
204 int ret;
205 int clk_id;
206 struct timespec ts;
207 _PyTime_t t;
208
209 if (!PyArg_ParseTuple(args, "i:clock_gettime", &clk_id)) {
210 return NULL;
211 }
212
213 ret = clock_gettime((clockid_t)clk_id, &ts);
214 if (ret != 0) {
215 PyErr_SetFromErrno(PyExc_OSError);
216 return NULL;
217 }
218 if (_PyTime_FromTimespec(&t, &ts) < 0) {
219 return NULL;
220 }
221 return _PyTime_AsNanosecondsObject(t);
222}
223
224PyDoc_STRVAR(clock_gettime_ns_doc,
225"clock_gettime_ns(clk_id) -> int\n\
226\n\
227Return the time of the specified clock clk_id as nanoseconds.");
Benjamin Peterson37098cd2016-09-13 22:55:09 -0700228#endif /* HAVE_CLOCK_GETTIME */
Victor Stinner30d79472012-04-03 00:45:07 +0200229
Benjamin Peterson37098cd2016-09-13 22:55:09 -0700230#ifdef HAVE_CLOCK_SETTIME
Victor Stinner30d79472012-04-03 00:45:07 +0200231static PyObject *
232time_clock_settime(PyObject *self, PyObject *args)
233{
Victor Stinnerb8d01692012-04-13 23:44:05 +0200234 int clk_id;
Victor Stinner30d79472012-04-03 00:45:07 +0200235 PyObject *obj;
Victor Stinnerb3b45442015-03-28 04:09:41 +0100236 _PyTime_t t;
Victor Stinner30d79472012-04-03 00:45:07 +0200237 struct timespec tp;
238 int ret;
239
240 if (!PyArg_ParseTuple(args, "iO:clock_settime", &clk_id, &obj))
241 return NULL;
242
Victor Stinner02937aa2015-03-28 05:02:39 +0100243 if (_PyTime_FromSecondsObject(&t, obj, _PyTime_ROUND_FLOOR) < 0)
Victor Stinner30d79472012-04-03 00:45:07 +0200244 return NULL;
Victor Stinnerb3b45442015-03-28 04:09:41 +0100245
246 if (_PyTime_AsTimespec(t, &tp) == -1)
247 return NULL;
Victor Stinner30d79472012-04-03 00:45:07 +0200248
249 ret = clock_settime((clockid_t)clk_id, &tp);
250 if (ret != 0) {
Victor Stinnera734af32014-07-31 13:07:17 +0200251 PyErr_SetFromErrno(PyExc_OSError);
Victor Stinner30d79472012-04-03 00:45:07 +0200252 return NULL;
253 }
254 Py_RETURN_NONE;
255}
256
257PyDoc_STRVAR(clock_settime_doc,
258"clock_settime(clk_id, time)\n\
259\n\
260Set the time of the specified clock clk_id.");
Victor Stinnerc29b5852017-11-02 07:28:27 -0700261
262static PyObject *
263time_clock_settime_ns(PyObject *self, PyObject *args)
264{
265 int clk_id;
266 PyObject *obj;
267 _PyTime_t t;
268 struct timespec ts;
269 int ret;
270
271 if (!PyArg_ParseTuple(args, "iO:clock_settime", &clk_id, &obj)) {
272 return NULL;
273 }
274
275 if (_PyTime_FromNanosecondsObject(&t, obj) < 0) {
276 return NULL;
277 }
278 if (_PyTime_AsTimespec(t, &ts) == -1) {
279 return NULL;
280 }
281
282 ret = clock_settime((clockid_t)clk_id, &ts);
283 if (ret != 0) {
284 PyErr_SetFromErrno(PyExc_OSError);
285 return NULL;
286 }
287 Py_RETURN_NONE;
288}
289
290PyDoc_STRVAR(clock_settime_ns_doc,
291"clock_settime_ns(clk_id, time)\n\
292\n\
293Set the time of the specified clock clk_id with nanoseconds.");
Benjamin Peterson37098cd2016-09-13 22:55:09 -0700294#endif /* HAVE_CLOCK_SETTIME */
Victor Stinnere0be4232011-10-25 13:06:09 +0200295
Benjamin Peterson37098cd2016-09-13 22:55:09 -0700296#ifdef HAVE_CLOCK_GETRES
Victor Stinnere0be4232011-10-25 13:06:09 +0200297static PyObject *
Victor Stinner4195b5c2012-02-08 23:03:19 +0100298time_clock_getres(PyObject *self, PyObject *args)
Victor Stinnere0be4232011-10-25 13:06:09 +0200299{
300 int ret;
Victor Stinnerb8d01692012-04-13 23:44:05 +0200301 int clk_id;
Victor Stinnere0be4232011-10-25 13:06:09 +0200302 struct timespec tp;
303
Victor Stinner4195b5c2012-02-08 23:03:19 +0100304 if (!PyArg_ParseTuple(args, "i:clock_getres", &clk_id))
Victor Stinnere0be4232011-10-25 13:06:09 +0200305 return NULL;
306
307 ret = clock_getres((clockid_t)clk_id, &tp);
Antoine Pitrou2c085602012-01-18 01:41:44 +0100308 if (ret != 0) {
Victor Stinnera734af32014-07-31 13:07:17 +0200309 PyErr_SetFromErrno(PyExc_OSError);
Antoine Pitrou2c085602012-01-18 01:41:44 +0100310 return NULL;
311 }
Victor Stinner4195b5c2012-02-08 23:03:19 +0100312
313 return PyFloat_FromDouble(tp.tv_sec + tp.tv_nsec * 1e-9);
Victor Stinnere0be4232011-10-25 13:06:09 +0200314}
315
316PyDoc_STRVAR(clock_getres_doc,
Victor Stinner4195b5c2012-02-08 23:03:19 +0100317"clock_getres(clk_id) -> floating point number\n\
Victor Stinnere0be4232011-10-25 13:06:09 +0200318\n\
319Return the resolution (precision) of the specified clock clk_id.");
Benjamin Peterson37098cd2016-09-13 22:55:09 -0700320#endif /* HAVE_CLOCK_GETRES */
Victor Stinnere0be4232011-10-25 13:06:09 +0200321
pdoxe14679c2017-10-05 00:01:56 -0700322#ifdef HAVE_PTHREAD_GETCPUCLOCKID
323static PyObject *
324time_pthread_getcpuclockid(PyObject *self, PyObject *args)
325{
326 unsigned long thread_id;
327 int err;
328 clockid_t clk_id;
329 if (!PyArg_ParseTuple(args, "k:pthread_getcpuclockid", &thread_id)) {
330 return NULL;
331 }
332 err = pthread_getcpuclockid((pthread_t)thread_id, &clk_id);
333 if (err) {
334 errno = err;
335 PyErr_SetFromErrno(PyExc_OSError);
336 return NULL;
337 }
Miss Islington (bot)01b96642018-12-30 17:59:19 -0800338#ifdef _Py_MEMORY_SANITIZER
339 __msan_unpoison(&clk_id, sizeof(clk_id));
340#endif
pdoxe14679c2017-10-05 00:01:56 -0700341 return PyLong_FromLong(clk_id);
342}
343
344PyDoc_STRVAR(pthread_getcpuclockid_doc,
345"pthread_getcpuclockid(thread_id) -> int\n\
346\n\
347Return the clk_id of a thread's CPU time clock.");
348#endif /* HAVE_PTHREAD_GETCPUCLOCKID */
349
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000350static PyObject *
Victor Stinnercb29f012015-03-27 13:31:18 +0100351time_sleep(PyObject *self, PyObject *obj)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000352{
Victor Stinnercb29f012015-03-27 13:31:18 +0100353 _PyTime_t secs;
Pablo Galindo59af94f2017-10-18 08:13:09 +0100354 if (_PyTime_FromSecondsObject(&secs, obj, _PyTime_ROUND_TIMEOUT))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000355 return NULL;
Victor Stinner7f53a502011-07-05 22:00:25 +0200356 if (secs < 0) {
357 PyErr_SetString(PyExc_ValueError,
358 "sleep length must be non-negative");
359 return NULL;
360 }
Victor Stinnercb29f012015-03-27 13:31:18 +0100361 if (pysleep(secs) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000362 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200363 Py_RETURN_NONE;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000364}
365
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000366PyDoc_STRVAR(sleep_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000367"sleep(seconds)\n\
368\n\
369Delay execution for a given number of seconds. The argument may be\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000370a floating point number for subsecond precision.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000371
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000372static PyStructSequence_Field struct_time_type_fields[] = {
Alexander Belopolsky69f3fd02010-06-05 15:04:51 +0000373 {"tm_year", "year, for example, 1993"},
374 {"tm_mon", "month of year, range [1, 12]"},
375 {"tm_mday", "day of month, range [1, 31]"},
376 {"tm_hour", "hours, range [0, 23]"},
377 {"tm_min", "minutes, range [0, 59]"},
378 {"tm_sec", "seconds, range [0, 61])"},
379 {"tm_wday", "day of week, range [0, 6], Monday is 0"},
380 {"tm_yday", "day of year, range [1, 366]"},
381 {"tm_isdst", "1 if summer time is in effect, 0 if not, and -1 if unknown"},
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400382 {"tm_zone", "abbreviation of timezone name"},
383 {"tm_gmtoff", "offset from UTC in seconds"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000384 {0}
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000385};
386
387static PyStructSequence_Desc struct_time_type_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000388 "time.struct_time",
Alexander Belopolsky69f3fd02010-06-05 15:04:51 +0000389 "The time value as returned by gmtime(), localtime(), and strptime(), and\n"
390 " accepted by asctime(), mktime() and strftime(). May be considered as a\n"
391 " sequence of 9 integers.\n\n"
392 " Note that several fields' values are not the same as those defined by\n"
393 " the C language standard for struct tm. For example, the value of the\n"
394 " field tm_year is the actual year, not year - 1900. See individual\n"
395 " fields' descriptions for details.",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000396 struct_time_type_fields,
397 9,
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000398};
Tim Peters9ad4b682002-02-13 05:14:18 +0000399
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000400static int initialized;
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000401static PyTypeObject StructTimeType;
402
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400403
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000404static PyObject *
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -0400405tmtotuple(struct tm *p
406#ifndef HAVE_STRUCT_TM_TM_ZONE
Victor Stinner0d659e52017-04-25 01:22:42 +0200407 , const char *zone, time_t gmtoff
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -0400408#endif
409)
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000410{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000411 PyObject *v = PyStructSequence_New(&StructTimeType);
412 if (v == NULL)
413 return NULL;
Tim Peters9ad4b682002-02-13 05:14:18 +0000414
Christian Heimes217cfd12007-12-02 14:31:20 +0000415#define SET(i,val) PyStructSequence_SET_ITEM(v, i, PyLong_FromLong((long) val))
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000416
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000417 SET(0, p->tm_year + 1900);
418 SET(1, p->tm_mon + 1); /* Want January == 1 */
419 SET(2, p->tm_mday);
420 SET(3, p->tm_hour);
421 SET(4, p->tm_min);
422 SET(5, p->tm_sec);
423 SET(6, (p->tm_wday + 6) % 7); /* Want Monday == 0 */
424 SET(7, p->tm_yday + 1); /* Want January, 1 == 1 */
425 SET(8, p->tm_isdst);
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400426#ifdef HAVE_STRUCT_TM_TM_ZONE
427 PyStructSequence_SET_ITEM(v, 9,
Victor Stinner7ed7aea2018-01-15 10:45:49 +0100428 PyUnicode_DecodeLocale(p->tm_zone, "surrogateescape"));
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400429 SET(10, p->tm_gmtoff);
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -0400430#else
431 PyStructSequence_SET_ITEM(v, 9,
Victor Stinner7ed7aea2018-01-15 10:45:49 +0100432 PyUnicode_DecodeLocale(zone, "surrogateescape"));
Victor Stinner0d659e52017-04-25 01:22:42 +0200433 PyStructSequence_SET_ITEM(v, 10, _PyLong_FromTime_t(gmtoff));
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400434#endif /* HAVE_STRUCT_TM_TM_ZONE */
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000435#undef SET
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000436 if (PyErr_Occurred()) {
437 Py_XDECREF(v);
438 return NULL;
439 }
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000440
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000441 return v;
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000442}
443
Fred Drakef901abd2004-08-03 17:58:55 +0000444/* Parse arg tuple that can contain an optional float-or-None value;
445 format needs to be "|O:name".
446 Returns non-zero on success (parallels PyArg_ParseTuple).
447*/
448static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +0200449parse_time_t_args(PyObject *args, const char *format, time_t *pwhen)
Fred Drakef901abd2004-08-03 17:58:55 +0000450{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000451 PyObject *ot = NULL;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100452 time_t whent;
Fred Drakef901abd2004-08-03 17:58:55 +0000453
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000454 if (!PyArg_ParseTuple(args, format, &ot))
455 return 0;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100456 if (ot == NULL || ot == Py_None) {
457 whent = time(NULL);
458 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000459 else {
Victor Stinner02937aa2015-03-28 05:02:39 +0100460 if (_PyTime_ObjectToTime_t(ot, &whent, _PyTime_ROUND_FLOOR) == -1)
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100461 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000462 }
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100463 *pwhen = whent;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000464 return 1;
Fred Drakef901abd2004-08-03 17:58:55 +0000465}
466
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000467static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000468time_gmtime(PyObject *self, PyObject *args)
Guido van Rossum234f9421993-06-17 12:35:49 +0000469{
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100470 time_t when;
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -0400471 struct tm buf;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100472
473 if (!parse_time_t_args(args, "|O:gmtime", &when))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000474 return NULL;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100475
476 errno = 0;
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -0400477 if (_PyTime_gmtime(when, &buf) != 0)
478 return NULL;
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -0400479#ifdef HAVE_STRUCT_TM_TM_ZONE
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100480 return tmtotuple(&buf);
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -0400481#else
482 return tmtotuple(&buf, "UTC", 0);
483#endif
Guido van Rossum234f9421993-06-17 12:35:49 +0000484}
485
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -0400486#ifndef HAVE_TIMEGM
487static time_t
488timegm(struct tm *p)
489{
490 /* XXX: the following implementation will not work for tm_year < 1970.
491 but it is likely that platforms that don't have timegm do not support
492 negative timestamps anyways. */
493 return p->tm_sec + p->tm_min*60 + p->tm_hour*3600 + p->tm_yday*86400 +
494 (p->tm_year-70)*31536000 + ((p->tm_year-69)/4)*86400 -
495 ((p->tm_year-1)/100)*86400 + ((p->tm_year+299)/400)*86400;
496}
497#endif
498
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000499PyDoc_STRVAR(gmtime_doc,
Christian Heimes9a371592007-12-28 14:08:13 +0000500"gmtime([seconds]) -> (tm_year, tm_mon, tm_mday, tm_hour, tm_min,\n\
Fred Drake193a3f62002-03-12 21:38:49 +0000501 tm_sec, tm_wday, tm_yday, tm_isdst)\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000502\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000503Convert seconds since the Epoch to a time tuple expressing UTC (a.k.a.\n\
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400504GMT). When 'seconds' is not passed in, convert the current time instead.\n\
505\n\
506If the platform supports the tm_gmtoff and tm_zone, they are available as\n\
507attributes only.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000508
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000509static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000510time_localtime(PyObject *self, PyObject *args)
Guido van Rossum234f9421993-06-17 12:35:49 +0000511{
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100512 time_t when;
513 struct tm buf;
514
515 if (!parse_time_t_args(args, "|O:localtime", &when))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000516 return NULL;
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -0400517 if (_PyTime_localtime(when, &buf) != 0)
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100518 return NULL;
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -0400519#ifdef HAVE_STRUCT_TM_TM_ZONE
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100520 return tmtotuple(&buf);
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -0400521#else
522 {
523 struct tm local = buf;
524 char zone[100];
Victor Stinner0d659e52017-04-25 01:22:42 +0200525 time_t gmtoff;
Steve Dowerc3c6f712016-12-14 11:22:05 -0800526 strftime(zone, sizeof(zone), "%Z", &buf);
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -0400527 gmtoff = timegm(&buf) - when;
528 return tmtotuple(&local, zone, gmtoff);
529 }
530#endif
Guido van Rossum234f9421993-06-17 12:35:49 +0000531}
532
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000533PyDoc_STRVAR(localtime_doc,
Christian Heimes9a371592007-12-28 14:08:13 +0000534"localtime([seconds]) -> (tm_year,tm_mon,tm_mday,tm_hour,tm_min,\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000535 tm_sec,tm_wday,tm_yday,tm_isdst)\n\
Martin v. Löwisb3cfc1d2001-12-02 12:27:43 +0000536\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000537Convert seconds since the Epoch to a time tuple expressing local time.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000538When 'seconds' is not passed in, convert the current time instead.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000539
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000540/* Convert 9-item tuple to tm structure. Return 1 on success, set
541 * an exception and return 0 on error.
542 */
Guido van Rossum9e90a671993-06-24 11:10:19 +0000543static int
Oren Milman1d1d3e92017-08-20 18:35:36 +0300544gettmarg(PyObject *args, struct tm *p, const char *format)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000545{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000546 int y;
Guido van Rossumcfbaecc1998-08-25 14:51:12 +0000547
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000548 memset((void *) p, '\0', sizeof(struct tm));
Guido van Rossumb9081262007-08-25 03:14:09 +0000549
Alexander Belopolsky610e5442011-01-06 21:57:06 +0000550 if (!PyTuple_Check(args)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000551 PyErr_SetString(PyExc_TypeError,
552 "Tuple or struct_time argument required");
553 return 0;
554 }
Skip Montanaro41cfce92007-08-24 21:11:00 +0000555
Oren Milman1d1d3e92017-08-20 18:35:36 +0300556 if (!PyArg_ParseTuple(args, format,
Alexander Belopolsky610e5442011-01-06 21:57:06 +0000557 &y, &p->tm_mon, &p->tm_mday,
558 &p->tm_hour, &p->tm_min, &p->tm_sec,
559 &p->tm_wday, &p->tm_yday, &p->tm_isdst))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000560 return 0;
Miss Islington (bot)d5f017b2018-08-25 01:53:00 -0400561
562 if (y < INT_MIN + 1900) {
563 PyErr_SetString(PyExc_OverflowError, "year out of range");
564 return 0;
565 }
566
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000567 p->tm_year = y - 1900;
568 p->tm_mon--;
569 p->tm_wday = (p->tm_wday + 1) % 7;
570 p->tm_yday--;
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400571#ifdef HAVE_STRUCT_TM_TM_ZONE
572 if (Py_TYPE(args) == &StructTimeType) {
573 PyObject *item;
574 item = PyTuple_GET_ITEM(args, 9);
Victor Stinner6e676952017-04-26 13:51:48 +0200575 p->tm_zone = item == Py_None ? NULL : (char*)PyUnicode_AsUTF8(item);
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400576 item = PyTuple_GET_ITEM(args, 10);
577 p->tm_gmtoff = item == Py_None ? 0 : PyLong_AsLong(item);
578 if (PyErr_Occurred())
579 return 0;
580 }
581#endif /* HAVE_STRUCT_TM_TM_ZONE */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000582 return 1;
Guido van Rossum9e90a671993-06-24 11:10:19 +0000583}
584
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000585/* Check values of the struct tm fields before it is passed to strftime() and
586 * asctime(). Return 1 if all values are valid, otherwise set an exception
587 * and returns 0.
588 */
Victor Stinneref128102010-10-07 01:00:52 +0000589static int
590checktm(struct tm* buf)
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000591{
Victor Stinneref128102010-10-07 01:00:52 +0000592 /* Checks added to make sure strftime() and asctime() does not crash Python by
593 indexing blindly into some array for a textual representation
594 by some bad index (fixes bug #897625 and #6608).
595
596 Also support values of zero from Python code for arguments in which
597 that is out of range by forcing that value to the lowest value that
598 is valid (fixed bug #1520914).
599
600 Valid ranges based on what is allowed in struct tm:
601
602 - tm_year: [0, max(int)] (1)
603 - tm_mon: [0, 11] (2)
604 - tm_mday: [1, 31]
605 - tm_hour: [0, 23]
606 - tm_min: [0, 59]
607 - tm_sec: [0, 60]
608 - tm_wday: [0, 6] (1)
609 - tm_yday: [0, 365] (2)
610 - tm_isdst: [-max(int), max(int)]
611
612 (1) gettmarg() handles bounds-checking.
613 (2) Python's acceptable range is one greater than the range in C,
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000614 thus need to check against automatic decrement by gettmarg().
615 */
616 if (buf->tm_mon == -1)
617 buf->tm_mon = 0;
618 else if (buf->tm_mon < 0 || buf->tm_mon > 11) {
619 PyErr_SetString(PyExc_ValueError, "month out of range");
620 return 0;
621 }
622 if (buf->tm_mday == 0)
623 buf->tm_mday = 1;
624 else if (buf->tm_mday < 0 || buf->tm_mday > 31) {
625 PyErr_SetString(PyExc_ValueError, "day of month out of range");
626 return 0;
627 }
628 if (buf->tm_hour < 0 || buf->tm_hour > 23) {
629 PyErr_SetString(PyExc_ValueError, "hour out of range");
630 return 0;
631 }
632 if (buf->tm_min < 0 || buf->tm_min > 59) {
633 PyErr_SetString(PyExc_ValueError, "minute out of range");
634 return 0;
635 }
636 if (buf->tm_sec < 0 || buf->tm_sec > 61) {
637 PyErr_SetString(PyExc_ValueError, "seconds out of range");
638 return 0;
639 }
640 /* tm_wday does not need checking of its upper-bound since taking
641 ``% 7`` in gettmarg() automatically restricts the range. */
642 if (buf->tm_wday < 0) {
643 PyErr_SetString(PyExc_ValueError, "day of week out of range");
644 return 0;
645 }
646 if (buf->tm_yday == -1)
647 buf->tm_yday = 0;
648 else if (buf->tm_yday < 0 || buf->tm_yday > 365) {
649 PyErr_SetString(PyExc_ValueError, "day of year out of range");
650 return 0;
651 }
652 return 1;
653}
654
Victor Stinnerc1f32ca2011-10-14 02:36:13 +0200655#ifdef MS_WINDOWS
656 /* wcsftime() doesn't format correctly time zones, see issue #10653 */
657# undef HAVE_WCSFTIME
658#endif
Alexander Belopolskycf774542012-10-02 18:39:16 -0400659#define STRFTIME_FORMAT_CODES \
660"Commonly used format codes:\n\
661\n\
662%Y Year with century as a decimal number.\n\
663%m Month as a decimal number [01,12].\n\
664%d Day of the month as a decimal number [01,31].\n\
665%H Hour (24-hour clock) as a decimal number [00,23].\n\
666%M Minute as a decimal number [00,59].\n\
667%S Second as a decimal number [00,61].\n\
668%z Time zone offset from UTC.\n\
669%a Locale's abbreviated weekday name.\n\
670%A Locale's full weekday name.\n\
671%b Locale's abbreviated month name.\n\
672%B Locale's full month name.\n\
673%c Locale's appropriate date and time representation.\n\
674%I Hour (12-hour clock) as a decimal number [01,12].\n\
675%p Locale's equivalent of either AM or PM.\n\
676\n\
677Other codes may be available on your platform. See documentation for\n\
678the C library strftime function.\n"
Victor Stinnerc1f32ca2011-10-14 02:36:13 +0200679
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000680#ifdef HAVE_STRFTIME
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000681#ifdef HAVE_WCSFTIME
682#define time_char wchar_t
683#define format_time wcsftime
684#define time_strlen wcslen
685#else
686#define time_char char
687#define format_time strftime
688#define time_strlen strlen
689#endif
690
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000691static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000692time_strftime(PyObject *self, PyObject *args)
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000693{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000694 PyObject *tup = NULL;
695 struct tm buf;
696 const time_char *fmt;
Victor Stinnerb2904782010-09-29 10:34:19 +0000697#ifdef HAVE_WCSFTIME
698 wchar_t *format;
699#else
700 PyObject *format;
701#endif
Victor Stinneref128102010-10-07 01:00:52 +0000702 PyObject *format_arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000703 size_t fmtlen, buflen;
Victor Stinnerb2904782010-09-29 10:34:19 +0000704 time_char *outbuf = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000705 size_t i;
Victor Stinnerb2904782010-09-29 10:34:19 +0000706 PyObject *ret = NULL;
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000707
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000708 memset((void *) &buf, '\0', sizeof(buf));
Guido van Rossum1f41f841998-04-27 19:04:26 +0000709
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000710 /* Will always expect a unicode string to be passed as format.
711 Given that there's no str type anymore in py3k this seems safe.
712 */
Victor Stinneref128102010-10-07 01:00:52 +0000713 if (!PyArg_ParseTuple(args, "U|O:strftime", &format_arg, &tup))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000714 return NULL;
Thomas Woutersfe385252001-01-19 23:16:56 +0000715
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000716 if (tup == NULL) {
717 time_t tt = time(NULL);
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -0400718 if (_PyTime_localtime(tt, &buf) != 0)
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100719 return NULL;
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000720 }
Oren Milman1d1d3e92017-08-20 18:35:36 +0300721 else if (!gettmarg(tup, &buf,
722 "iiiiiiiii;strftime(): illegal time tuple argument") ||
723 !checktm(&buf))
724 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000725 return NULL;
Oren Milman1d1d3e92017-08-20 18:35:36 +0300726 }
Guido van Rossum10b164a2001-09-25 13:59:01 +0000727
Miss Islington (bot)d8234432018-12-30 18:39:00 -0800728#if defined(_MSC_VER) || (defined(__sun) && defined(__SVR4)) || defined(_AIX)
Victor Stinner73ea29c2011-01-08 01:56:31 +0000729 if (buf.tm_year + 1900 < 1 || 9999 < buf.tm_year + 1900) {
Victor Stinner6f0e4f92011-03-21 02:14:53 +0100730 PyErr_SetString(PyExc_ValueError,
731 "strftime() requires year in [1; 9999]");
Alexander Belopolsky0dd06f42011-01-08 01:23:02 +0000732 return NULL;
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000733 }
Victor Stinner73ea29c2011-01-08 01:56:31 +0000734#endif
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000735
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000736 /* Normalize tm_isdst just in case someone foolishly implements %Z
737 based on the assumption that tm_isdst falls within the range of
738 [-1, 1] */
739 if (buf.tm_isdst < -1)
740 buf.tm_isdst = -1;
741 else if (buf.tm_isdst > 1)
742 buf.tm_isdst = 1;
Brett Cannond1080a32004-03-02 04:38:10 +0000743
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000744#ifdef HAVE_WCSFTIME
Victor Stinnerbeb4135b2010-10-07 01:02:42 +0000745 format = PyUnicode_AsWideCharString(format_arg, NULL);
Victor Stinnerb2904782010-09-29 10:34:19 +0000746 if (format == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000747 return NULL;
Victor Stinnerb2904782010-09-29 10:34:19 +0000748 fmt = format;
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000749#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000750 /* Convert the unicode string to an ascii one */
Victor Stinner1b579672011-12-17 05:47:23 +0100751 format = PyUnicode_EncodeLocale(format_arg, "surrogateescape");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000752 if (format == NULL)
753 return NULL;
754 fmt = PyBytes_AS_STRING(format);
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000755#endif
Amaury Forgeot d'Arcb5be6d42009-03-02 23:52:57 +0000756
Stefan Krah4aea7d32012-02-27 16:30:26 +0100757#if defined(MS_WINDOWS) && !defined(HAVE_WCSFTIME)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000758 /* check that the format string contains only valid directives */
Steve Dowere5b58952015-09-06 19:20:51 -0700759 for (outbuf = strchr(fmt, '%');
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000760 outbuf != NULL;
Victor Stinner5a3ff792011-10-16 19:08:23 +0200761 outbuf = strchr(outbuf+2, '%'))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000762 {
Steve Dowere5b58952015-09-06 19:20:51 -0700763 if (outbuf[1] == '#')
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000764 ++outbuf; /* not documented by python, */
Steve Dowere5b58952015-09-06 19:20:51 -0700765 if (outbuf[1] == '\0')
766 break;
767 if ((outbuf[1] == 'y') && buf.tm_year < 0) {
Tim Golden6e51b8f2013-11-12 12:36:54 +0000768 PyErr_SetString(PyExc_ValueError,
769 "format %y requires year >= 1900 on Windows");
770 Py_DECREF(format);
771 return NULL;
772 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000773 }
Miss Islington (bot)d8234432018-12-30 18:39:00 -0800774#elif (defined(_AIX) || (defined(__sun) && defined(__SVR4))) && defined(HAVE_WCSFTIME)
Steve Dowere5b58952015-09-06 19:20:51 -0700775 for (outbuf = wcschr(fmt, '%');
Victor Stinner55329f82013-11-17 23:39:21 +0100776 outbuf != NULL;
777 outbuf = wcschr(outbuf+2, '%'))
778 {
Steve Dowere5b58952015-09-06 19:20:51 -0700779 if (outbuf[1] == L'\0')
780 break;
Victor Stinner55329f82013-11-17 23:39:21 +0100781 /* Issue #19634: On AIX, wcsftime("y", (1899, 1, 1, 0, 0, 0, 0, 0, 0))
782 returns "0/" instead of "99" */
783 if (outbuf[1] == L'y' && buf.tm_year < 0) {
784 PyErr_SetString(PyExc_ValueError,
785 "format %y requires year >= 1900 on AIX");
Miss Islington (bot)975f3cb2018-09-21 00:41:50 -0700786 PyMem_Free(format);
Victor Stinner55329f82013-11-17 23:39:21 +0100787 return NULL;
788 }
789 }
Amaury Forgeot d'Arcb5be6d42009-03-02 23:52:57 +0000790#endif
791
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000792 fmtlen = time_strlen(fmt);
Guido van Rossumc222ec21999-02-23 00:00:10 +0000793
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000794 /* I hate these functions that presume you know how big the output
795 * will be ahead of time...
796 */
797 for (i = 1024; ; i += i) {
798 outbuf = (time_char *)PyMem_Malloc(i*sizeof(time_char));
799 if (outbuf == NULL) {
Victor Stinnerb2904782010-09-29 10:34:19 +0000800 PyErr_NoMemory();
801 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000802 }
Steve Dower57ab1cd2015-09-22 14:51:42 -0700803#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
804 errno = 0;
805#endif
Steve Dowerd9ef74e2015-05-22 15:08:34 -0700806 _Py_BEGIN_SUPPRESS_IPH
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000807 buflen = format_time(outbuf, i, fmt, &buf);
Steve Dowerd9ef74e2015-05-22 15:08:34 -0700808 _Py_END_SUPPRESS_IPH
Victor Stinner136ea492011-12-17 22:37:18 +0100809#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
Steve Dower97cded92015-09-08 19:12:51 -0700810 /* VisualStudio .NET 2005 does this properly */
811 if (buflen == 0 && errno == EINVAL) {
812 PyErr_SetString(PyExc_ValueError, "Invalid format string");
813 PyMem_Free(outbuf);
814 break;
815 }
Victor Stinner136ea492011-12-17 22:37:18 +0100816#endif
Steve Dower97cded92015-09-08 19:12:51 -0700817 if (buflen > 0 || i >= 256 * fmtlen) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000818 /* If the buffer is 256 times as long as the format,
819 it's probably not failing for lack of room!
820 More likely, the format yields an empty result,
821 e.g. an empty format, or %Z when the timezone
822 is unknown. */
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000823#ifdef HAVE_WCSFTIME
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000824 ret = PyUnicode_FromWideChar(outbuf, buflen);
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000825#else
Victor Stinner7ed7aea2018-01-15 10:45:49 +0100826 ret = PyUnicode_DecodeLocaleAndSize(outbuf, buflen, "surrogateescape");
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000827#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000828 PyMem_Free(outbuf);
Victor Stinnerb2904782010-09-29 10:34:19 +0000829 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000830 }
831 PyMem_Free(outbuf);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000832 }
Victor Stinnerb2904782010-09-29 10:34:19 +0000833#ifdef HAVE_WCSFTIME
834 PyMem_Free(format);
835#else
836 Py_DECREF(format);
837#endif
838 return ret;
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000839}
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000840
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000841#undef time_char
842#undef format_time
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000843PyDoc_STRVAR(strftime_doc,
Thomas Woutersfe385252001-01-19 23:16:56 +0000844"strftime(format[, tuple]) -> string\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000845\n\
846Convert a time tuple to a string according to a format specification.\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000847See the library reference manual for formatting codes. When the time tuple\n\
Alexander Belopolskycf774542012-10-02 18:39:16 -0400848is not present, current time as returned by localtime() is used.\n\
849\n" STRFTIME_FORMAT_CODES);
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000850#endif /* HAVE_STRFTIME */
851
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000852static PyObject *
853time_strptime(PyObject *self, PyObject *args)
854{
Victor Stinnerdbe28d22016-12-09 00:38:53 +0100855 PyObject *module, *func, *result;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200856 _Py_IDENTIFIER(_strptime_time);
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000857
Victor Stinnerdbe28d22016-12-09 00:38:53 +0100858 module = PyImport_ImportModuleNoBlock("_strptime");
859 if (!module)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000860 return NULL;
Victor Stinnerdbe28d22016-12-09 00:38:53 +0100861
862 func = _PyObject_GetAttrId(module, &PyId__strptime_time);
863 Py_DECREF(module);
864 if (!func) {
865 return NULL;
866 }
867
868 result = PyObject_Call(func, args, NULL);
869 Py_DECREF(func);
870 return result;
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000871}
872
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000873
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000874PyDoc_STRVAR(strptime_doc,
Brett Cannon20def8b2003-07-01 05:16:08 +0000875"strptime(string, format) -> struct_time\n\
Martin v. Löwisb3cfc1d2001-12-02 12:27:43 +0000876\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000877Parse a string to a time tuple according to a format specification.\n\
Alexander Belopolskycf774542012-10-02 18:39:16 -0400878See the library reference manual for formatting codes (same as\n\
879strftime()).\n\
880\n" STRFTIME_FORMAT_CODES);
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000881
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000882static PyObject *
883_asctime(struct tm *timeptr)
884{
885 /* Inspired by Open Group reference implementation available at
886 * http://pubs.opengroup.org/onlinepubs/009695399/functions/asctime.html */
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200887 static const char wday_name[7][4] = {
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000888 "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
889 };
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200890 static const char mon_name[12][4] = {
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000891 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
892 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
893 };
Victor Stinner499dfcf2011-03-21 13:26:24 +0100894 return PyUnicode_FromFormat(
895 "%s %s%3d %.2d:%.2d:%.2d %d",
896 wday_name[timeptr->tm_wday],
897 mon_name[timeptr->tm_mon],
898 timeptr->tm_mday, timeptr->tm_hour,
899 timeptr->tm_min, timeptr->tm_sec,
900 1900 + timeptr->tm_year);
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000901}
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000902
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000903static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000904time_asctime(PyObject *self, PyObject *args)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000905{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000906 PyObject *tup = NULL;
907 struct tm buf;
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000908
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000909 if (!PyArg_UnpackTuple(args, "asctime", 0, 1, &tup))
910 return NULL;
911 if (tup == NULL) {
912 time_t tt = time(NULL);
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -0400913 if (_PyTime_localtime(tt, &buf) != 0)
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100914 return NULL;
Oren Milman1d1d3e92017-08-20 18:35:36 +0300915 }
916 else if (!gettmarg(tup, &buf,
917 "iiiiiiiii;asctime(): illegal time tuple argument") ||
918 !checktm(&buf))
919 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000920 return NULL;
Oren Milman1d1d3e92017-08-20 18:35:36 +0300921 }
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000922 return _asctime(&buf);
Guido van Rossum9e90a671993-06-24 11:10:19 +0000923}
924
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000925PyDoc_STRVAR(asctime_doc,
Thomas Woutersfe385252001-01-19 23:16:56 +0000926"asctime([tuple]) -> string\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000927\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000928Convert a time tuple to a string, e.g. 'Sat Jun 06 16:26:11 1998'.\n\
929When the time tuple is not present, current time as returned by localtime()\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000930is used.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000931
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000932static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000933time_ctime(PyObject *self, PyObject *args)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000934{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000935 time_t tt;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100936 struct tm buf;
937 if (!parse_time_t_args(args, "|O:ctime", &tt))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000938 return NULL;
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -0400939 if (_PyTime_localtime(tt, &buf) != 0)
Alexander Belopolsky5da468f2011-01-04 17:15:52 +0000940 return NULL;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100941 return _asctime(&buf);
Guido van Rossum9e90a671993-06-24 11:10:19 +0000942}
943
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000944PyDoc_STRVAR(ctime_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000945"ctime(seconds) -> string\n\
946\n\
947Convert a time in seconds since the Epoch to a string in local time.\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000948This is equivalent to asctime(localtime(seconds)). When the time tuple is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000949not present, current time as returned by localtime() is used.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000950
Guido van Rossum60cd8131998-03-06 17:16:21 +0000951#ifdef HAVE_MKTIME
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000952static PyObject *
Victor Stinner4195b5c2012-02-08 23:03:19 +0100953time_mktime(PyObject *self, PyObject *tup)
Guido van Rossum234f9421993-06-17 12:35:49 +0000954{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000955 struct tm buf;
956 time_t tt;
Oren Milman1d1d3e92017-08-20 18:35:36 +0300957 if (!gettmarg(tup, &buf,
958 "iiiiiiiii;mktime(): illegal time tuple argument"))
959 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000960 return NULL;
Oren Milman1d1d3e92017-08-20 18:35:36 +0300961 }
Victor Stinner1ac42612014-02-21 09:27:17 +0100962#ifdef _AIX
963 /* year < 1902 or year > 2037 */
964 if (buf.tm_year < 2 || buf.tm_year > 137) {
965 /* Issue #19748: On AIX, mktime() doesn't report overflow error for
966 * timestamp < -2^31 or timestamp > 2**31-1. */
967 PyErr_SetString(PyExc_OverflowError,
968 "mktime argument out of range");
969 return NULL;
970 }
971#else
Alexander Belopolskyb7d40d12011-01-11 01:21:25 +0000972 buf.tm_wday = -1; /* sentinel; original value ignored */
Victor Stinner1ac42612014-02-21 09:27:17 +0100973#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000974 tt = mktime(&buf);
Alexander Belopolskyb7d40d12011-01-11 01:21:25 +0000975 /* Return value of -1 does not necessarily mean an error, but tm_wday
Ezio Melotti13925002011-03-16 11:05:33 +0200976 * cannot remain set to -1 if mktime succeeded. */
Victor Stinner93037492013-06-25 22:54:35 +0200977 if (tt == (time_t)(-1)
978#ifndef _AIX
979 /* Return value of -1 does not necessarily mean an error, but
980 * tm_wday cannot remain set to -1 if mktime succeeded. */
981 && buf.tm_wday == -1
982#else
983 /* on AIX, tm_wday is always sets, even on error */
984#endif
985 )
986 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000987 PyErr_SetString(PyExc_OverflowError,
988 "mktime argument out of range");
989 return NULL;
990 }
Victor Stinner4195b5c2012-02-08 23:03:19 +0100991 return PyFloat_FromDouble((double)tt);
Guido van Rossum234f9421993-06-17 12:35:49 +0000992}
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000993
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000994PyDoc_STRVAR(mktime_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000995"mktime(tuple) -> floating point number\n\
996\n\
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400997Convert a time tuple in local time to seconds since the Epoch.\n\
998Note that mktime(gmtime(0)) will not generally return zero for most\n\
999time zones; instead the returned value will either be equal to that\n\
1000of the timezone or altzone attributes on the time module.");
Guido van Rossum60cd8131998-03-06 17:16:21 +00001001#endif /* HAVE_MKTIME */
Guido van Rossum234f9421993-06-17 12:35:49 +00001002
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001003#ifdef HAVE_WORKING_TZSET
Victor Stinner5eb78c72018-12-04 00:09:02 +01001004static int init_timezone(PyObject *module);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001005
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001006static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001007time_tzset(PyObject *self, PyObject *unused)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001008{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001009 PyObject* m;
Fred Drake9bb74322002-04-01 14:49:59 +00001010
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001011 m = PyImport_ImportModuleNoBlock("time");
1012 if (m == NULL) {
1013 return NULL;
1014 }
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001015
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001016 tzset();
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001017
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001018 /* Reset timezone, altzone, daylight and tzname */
Victor Stinner5eb78c72018-12-04 00:09:02 +01001019 if (init_timezone(m) < 0) {
Victor Stinner38c06d92018-12-01 01:24:21 +01001020 return NULL;
1021 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001022 Py_DECREF(m);
Victor Stinner2ff51b82013-07-17 21:42:45 +02001023 if (PyErr_Occurred())
1024 return NULL;
Tim Peters1b6f7a92004-06-20 02:50:16 +00001025
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001026 Py_RETURN_NONE;
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001027}
1028
1029PyDoc_STRVAR(tzset_doc,
R. David Murray4d55bf92010-12-14 00:55:46 +00001030"tzset()\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001031\n\
1032Initialize, or reinitialize, the local timezone to the value stored in\n\
1033os.environ['TZ']. The TZ environment variable should be specified in\n\
Neal Norwitzdc8e1942004-07-20 22:34:37 +00001034standard Unix timezone format as documented in the tzset man page\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001035(eg. 'US/Eastern', 'Europe/Amsterdam'). Unknown timezones will silently\n\
1036fall back to UTC. If the TZ environment variable is not set, the local\n\
1037timezone is set to the systems best guess of wallclock time.\n\
1038Changing the TZ environment variable without calling tzset *may* change\n\
1039the local timezone used by methods such as localtime, but this behaviour\n\
1040should not be relied on.");
1041#endif /* HAVE_WORKING_TZSET */
1042
Victor Stinnerae586492014-09-02 23:18:25 +02001043static PyObject *
Victor Stinnerec895392012-04-29 02:41:27 +02001044time_monotonic(PyObject *self, PyObject *unused)
Victor Stinner071eca32012-03-15 01:17:09 +01001045{
Victor Stinnerc29b5852017-11-02 07:28:27 -07001046 _PyTime_t t = _PyTime_GetMonotonicClock();
1047 return _PyFloat_FromPyTime(t);
Victor Stinner071eca32012-03-15 01:17:09 +01001048}
1049
Victor Stinnerec895392012-04-29 02:41:27 +02001050PyDoc_STRVAR(monotonic_doc,
1051"monotonic() -> float\n\
Victor Stinner8b302012012-02-07 23:29:46 +01001052\n\
Victor Stinnerec895392012-04-29 02:41:27 +02001053Monotonic clock, cannot go backward.");
Victor Stinnerec919cc2012-03-15 00:58:32 +01001054
Victor Stinnerec895392012-04-29 02:41:27 +02001055static PyObject *
Victor Stinnerc29b5852017-11-02 07:28:27 -07001056time_monotonic_ns(PyObject *self, PyObject *unused)
1057{
1058 _PyTime_t t = _PyTime_GetMonotonicClock();
1059 return _PyTime_AsNanosecondsObject(t);
1060}
1061
1062PyDoc_STRVAR(monotonic_ns_doc,
1063"monotonic_ns() -> int\n\
1064\n\
1065Monotonic clock, cannot go backward, as nanoseconds.");
1066
1067static PyObject *
Victor Stinnerec895392012-04-29 02:41:27 +02001068time_perf_counter(PyObject *self, PyObject *unused)
1069{
1070 return perf_counter(NULL);
1071}
1072
1073PyDoc_STRVAR(perf_counter_doc,
1074"perf_counter() -> float\n\
1075\n\
1076Performance counter for benchmarking.");
1077
Victor Stinnerc29b5852017-11-02 07:28:27 -07001078static PyObject *
1079time_perf_counter_ns(PyObject *self, PyObject *unused)
1080{
1081 _PyTime_t t = _PyTime_GetPerfCounter();
1082 return _PyTime_AsNanosecondsObject(t);
1083}
1084
1085PyDoc_STRVAR(perf_counter_ns_doc,
1086"perf_counter_ns() -> int\n\
1087\n\
1088Performance counter for benchmarking as nanoseconds.");
1089
1090static int
1091_PyTime_GetProcessTimeWithInfo(_PyTime_t *tp, _Py_clock_info_t *info)
Victor Stinnerec895392012-04-29 02:41:27 +02001092{
1093#if defined(MS_WINDOWS)
1094 HANDLE process;
1095 FILETIME creation_time, exit_time, kernel_time, user_time;
1096 ULARGE_INTEGER large;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001097 _PyTime_t ktime, utime, t;
Victor Stinnerec895392012-04-29 02:41:27 +02001098 BOOL ok;
1099
1100 process = GetCurrentProcess();
Victor Stinnerc29b5852017-11-02 07:28:27 -07001101 ok = GetProcessTimes(process, &creation_time, &exit_time,
1102 &kernel_time, &user_time);
1103 if (!ok) {
1104 PyErr_SetFromWindowsErr(0);
1105 return -1;
1106 }
Victor Stinnerec895392012-04-29 02:41:27 +02001107
Victor Stinnerec895392012-04-29 02:41:27 +02001108 if (info) {
1109 info->implementation = "GetProcessTimes()";
1110 info->resolution = 1e-7;
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001111 info->monotonic = 1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001112 info->adjustable = 0;
Victor Stinnerec895392012-04-29 02:41:27 +02001113 }
Victor Stinnerc29b5852017-11-02 07:28:27 -07001114
1115 large.u.LowPart = kernel_time.dwLowDateTime;
1116 large.u.HighPart = kernel_time.dwHighDateTime;
1117 ktime = large.QuadPart;
1118
1119 large.u.LowPart = user_time.dwLowDateTime;
1120 large.u.HighPart = user_time.dwHighDateTime;
1121 utime = large.QuadPart;
1122
1123 /* ktime and utime have a resolution of 100 nanoseconds */
1124 t = _PyTime_FromNanoseconds((ktime + utime) * 100);
1125 *tp = t;
1126 return 0;
Victor Stinnerec895392012-04-29 02:41:27 +02001127#else
1128
Victor Stinnerc29b5852017-11-02 07:28:27 -07001129 /* clock_gettime */
Victor Stinnerec895392012-04-29 02:41:27 +02001130#if defined(HAVE_CLOCK_GETTIME) \
1131 && (defined(CLOCK_PROCESS_CPUTIME_ID) || defined(CLOCK_PROF))
Victor Stinnerc29b5852017-11-02 07:28:27 -07001132 struct timespec ts;
Victor Stinnerec895392012-04-29 02:41:27 +02001133#ifdef CLOCK_PROF
1134 const clockid_t clk_id = CLOCK_PROF;
1135 const char *function = "clock_gettime(CLOCK_PROF)";
1136#else
1137 const clockid_t clk_id = CLOCK_PROCESS_CPUTIME_ID;
1138 const char *function = "clock_gettime(CLOCK_PROCESS_CPUTIME_ID)";
1139#endif
1140
Victor Stinnerc29b5852017-11-02 07:28:27 -07001141 if (clock_gettime(clk_id, &ts) == 0) {
Victor Stinnerec895392012-04-29 02:41:27 +02001142 if (info) {
1143 struct timespec res;
1144 info->implementation = function;
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001145 info->monotonic = 1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001146 info->adjustable = 0;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001147 if (clock_getres(clk_id, &res)) {
1148 PyErr_SetFromErrno(PyExc_OSError);
1149 return -1;
1150 }
1151 info->resolution = res.tv_sec + res.tv_nsec * 1e-9;
Victor Stinnerec895392012-04-29 02:41:27 +02001152 }
Victor Stinnerc29b5852017-11-02 07:28:27 -07001153
1154 if (_PyTime_FromTimespec(tp, &ts) < 0) {
1155 return -1;
1156 }
1157 return 0;
Victor Stinnerec895392012-04-29 02:41:27 +02001158 }
1159#endif
1160
Victor Stinnerc29b5852017-11-02 07:28:27 -07001161 /* getrusage(RUSAGE_SELF) */
Victor Stinnerec895392012-04-29 02:41:27 +02001162#if defined(HAVE_SYS_RESOURCE_H)
Victor Stinnerc29b5852017-11-02 07:28:27 -07001163 struct rusage ru;
1164
Victor Stinnerec895392012-04-29 02:41:27 +02001165 if (getrusage(RUSAGE_SELF, &ru) == 0) {
Victor Stinnerc29b5852017-11-02 07:28:27 -07001166 _PyTime_t utime, stime;
1167
Victor Stinnerec895392012-04-29 02:41:27 +02001168 if (info) {
1169 info->implementation = "getrusage(RUSAGE_SELF)";
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001170 info->monotonic = 1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001171 info->adjustable = 0;
Victor Stinnerec895392012-04-29 02:41:27 +02001172 info->resolution = 1e-6;
1173 }
Victor Stinnerc29b5852017-11-02 07:28:27 -07001174
1175 if (_PyTime_FromTimeval(&utime, &ru.ru_utime) < 0) {
1176 return -1;
1177 }
1178 if (_PyTime_FromTimeval(&stime, &ru.ru_stime) < 0) {
1179 return -1;
1180 }
1181
1182 _PyTime_t total = utime + utime;
1183 *tp = total;
1184 return 0;
Victor Stinnerec895392012-04-29 02:41:27 +02001185 }
1186#endif
1187
Victor Stinnerc29b5852017-11-02 07:28:27 -07001188 /* times() */
Victor Stinnerec895392012-04-29 02:41:27 +02001189#ifdef HAVE_TIMES
Victor Stinnerc29b5852017-11-02 07:28:27 -07001190 struct tms t;
1191
Victor Stinnerec895392012-04-29 02:41:27 +02001192 if (times(&t) != (clock_t)-1) {
Victor Stinnerc29b5852017-11-02 07:28:27 -07001193 static long ticks_per_second = -1;
Victor Stinnerec895392012-04-29 02:41:27 +02001194
1195 if (ticks_per_second == -1) {
Victor Stinnerc29b5852017-11-02 07:28:27 -07001196 long freq;
Victor Stinnerec895392012-04-29 02:41:27 +02001197#if defined(HAVE_SYSCONF) && defined(_SC_CLK_TCK)
Victor Stinnerc29b5852017-11-02 07:28:27 -07001198 freq = sysconf(_SC_CLK_TCK);
1199 if (freq < 1) {
1200 freq = -1;
1201 }
Victor Stinnerec895392012-04-29 02:41:27 +02001202#elif defined(HZ)
Victor Stinnerc29b5852017-11-02 07:28:27 -07001203 freq = HZ;
Victor Stinnerec895392012-04-29 02:41:27 +02001204#else
Victor Stinnerc29b5852017-11-02 07:28:27 -07001205 freq = 60; /* magic fallback value; may be bogus */
Victor Stinnerec895392012-04-29 02:41:27 +02001206#endif
Victor Stinnerc29b5852017-11-02 07:28:27 -07001207
1208 if (freq != -1) {
1209 /* check that _PyTime_MulDiv(t, SEC_TO_NS, ticks_per_second)
1210 cannot overflow below */
Miss Islington (bot)7df80492018-02-09 07:56:34 -08001211#if LONG_MAX > _PyTime_MAX / SEC_TO_NS
Victor Stinnerc29b5852017-11-02 07:28:27 -07001212 if ((_PyTime_t)freq > _PyTime_MAX / SEC_TO_NS) {
1213 PyErr_SetString(PyExc_OverflowError,
1214 "_SC_CLK_TCK is too large");
1215 return -1;
1216 }
Miss Islington (bot)7df80492018-02-09 07:56:34 -08001217#endif
Victor Stinnerc29b5852017-11-02 07:28:27 -07001218
1219 ticks_per_second = freq;
1220 }
Victor Stinnerec895392012-04-29 02:41:27 +02001221 }
1222
1223 if (ticks_per_second != -1) {
Victor Stinnerec895392012-04-29 02:41:27 +02001224 if (info) {
1225 info->implementation = "times()";
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001226 info->monotonic = 1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001227 info->adjustable = 0;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001228 info->resolution = 1.0 / (double)ticks_per_second;
Victor Stinnerec895392012-04-29 02:41:27 +02001229 }
Victor Stinnerc29b5852017-11-02 07:28:27 -07001230
1231 _PyTime_t total;
1232 total = _PyTime_MulDiv(t.tms_utime, SEC_TO_NS, ticks_per_second);
1233 total += _PyTime_MulDiv(t.tms_stime, SEC_TO_NS, ticks_per_second);
1234 *tp = total;
1235 return 0;
Victor Stinnerec895392012-04-29 02:41:27 +02001236 }
1237 }
1238#endif
1239
Victor Stinnerc29b5852017-11-02 07:28:27 -07001240 /* clock */
Victor Stinner53e22bf2016-07-08 17:55:01 +02001241 /* Currently, Python 3 requires clock() to build: see issue #22624 */
Victor Stinnerc29b5852017-11-02 07:28:27 -07001242 return _PyTime_GetClockWithInfo(tp, info);
Victor Stinnerec895392012-04-29 02:41:27 +02001243#endif
1244}
1245
1246static PyObject *
1247time_process_time(PyObject *self, PyObject *unused)
1248{
Victor Stinnerc29b5852017-11-02 07:28:27 -07001249 _PyTime_t t;
1250 if (_PyTime_GetProcessTimeWithInfo(&t, NULL) < 0) {
1251 return NULL;
1252 }
1253 return _PyFloat_FromPyTime(t);
Victor Stinnerec895392012-04-29 02:41:27 +02001254}
1255
1256PyDoc_STRVAR(process_time_doc,
1257"process_time() -> float\n\
1258\n\
1259Process time for profiling: sum of the kernel and user-space CPU time.");
1260
Victor Stinnerc29b5852017-11-02 07:28:27 -07001261static PyObject *
1262time_process_time_ns(PyObject *self, PyObject *unused)
1263{
1264 _PyTime_t t;
1265 if (_PyTime_GetProcessTimeWithInfo(&t, NULL) < 0) {
1266 return NULL;
1267 }
1268 return _PyTime_AsNanosecondsObject(t);
1269}
1270
1271PyDoc_STRVAR(process_time_ns_doc,
1272"process_time() -> int\n\
1273\n\
1274Process time for profiling as nanoseconds:\n\
1275sum of the kernel and user-space CPU time.");
1276
Victor Stinnerec895392012-04-29 02:41:27 +02001277
Antoine Pitrou4bd41c92017-11-15 22:52:21 +01001278#if defined(MS_WINDOWS)
1279#define HAVE_THREAD_TIME
1280static int
1281_PyTime_GetThreadTimeWithInfo(_PyTime_t *tp, _Py_clock_info_t *info)
1282{
1283 HANDLE thread;
1284 FILETIME creation_time, exit_time, kernel_time, user_time;
1285 ULARGE_INTEGER large;
1286 _PyTime_t ktime, utime, t;
1287 BOOL ok;
1288
1289 thread = GetCurrentThread();
1290 ok = GetThreadTimes(thread, &creation_time, &exit_time,
1291 &kernel_time, &user_time);
1292 if (!ok) {
1293 PyErr_SetFromWindowsErr(0);
1294 return -1;
1295 }
1296
1297 if (info) {
1298 info->implementation = "GetThreadTimes()";
1299 info->resolution = 1e-7;
1300 info->monotonic = 1;
1301 info->adjustable = 0;
1302 }
1303
1304 large.u.LowPart = kernel_time.dwLowDateTime;
1305 large.u.HighPart = kernel_time.dwHighDateTime;
1306 ktime = large.QuadPart;
1307
1308 large.u.LowPart = user_time.dwLowDateTime;
1309 large.u.HighPart = user_time.dwHighDateTime;
1310 utime = large.QuadPart;
1311
1312 /* ktime and utime have a resolution of 100 nanoseconds */
1313 t = _PyTime_FromNanoseconds((ktime + utime) * 100);
1314 *tp = t;
1315 return 0;
1316}
1317
1318#elif defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_PROCESS_CPUTIME_ID)
1319#define HAVE_THREAD_TIME
1320static int
1321_PyTime_GetThreadTimeWithInfo(_PyTime_t *tp, _Py_clock_info_t *info)
1322{
1323 struct timespec ts;
1324 const clockid_t clk_id = CLOCK_THREAD_CPUTIME_ID;
1325 const char *function = "clock_gettime(CLOCK_THREAD_CPUTIME_ID)";
1326
1327 if (clock_gettime(clk_id, &ts)) {
1328 PyErr_SetFromErrno(PyExc_OSError);
1329 return -1;
1330 }
1331 if (info) {
1332 struct timespec res;
1333 info->implementation = function;
1334 info->monotonic = 1;
1335 info->adjustable = 0;
1336 if (clock_getres(clk_id, &res)) {
1337 PyErr_SetFromErrno(PyExc_OSError);
1338 return -1;
1339 }
1340 info->resolution = res.tv_sec + res.tv_nsec * 1e-9;
1341 }
1342
1343 if (_PyTime_FromTimespec(tp, &ts) < 0) {
1344 return -1;
1345 }
1346 return 0;
1347}
1348#endif
1349
1350#ifdef HAVE_THREAD_TIME
1351static PyObject *
1352time_thread_time(PyObject *self, PyObject *unused)
1353{
1354 _PyTime_t t;
1355 if (_PyTime_GetThreadTimeWithInfo(&t, NULL) < 0) {
1356 return NULL;
1357 }
1358 return _PyFloat_FromPyTime(t);
1359}
1360
1361PyDoc_STRVAR(thread_time_doc,
1362"thread_time() -> float\n\
1363\n\
1364Thread time for profiling: sum of the kernel and user-space CPU time.");
1365
1366static PyObject *
1367time_thread_time_ns(PyObject *self, PyObject *unused)
1368{
1369 _PyTime_t t;
1370 if (_PyTime_GetThreadTimeWithInfo(&t, NULL) < 0) {
1371 return NULL;
1372 }
1373 return _PyTime_AsNanosecondsObject(t);
1374}
1375
1376PyDoc_STRVAR(thread_time_ns_doc,
1377"thread_time() -> int\n\
1378\n\
1379Thread time for profiling as nanoseconds:\n\
1380sum of the kernel and user-space CPU time.");
1381#endif
1382
1383
Victor Stinnerec895392012-04-29 02:41:27 +02001384static PyObject *
1385time_get_clock_info(PyObject *self, PyObject *args)
1386{
1387 char *name;
Victor Stinnerec895392012-04-29 02:41:27 +02001388 _Py_clock_info_t info;
Victor Stinnerbda4b882012-06-12 22:11:44 +02001389 PyObject *obj = NULL, *dict, *ns;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001390 _PyTime_t t;
Victor Stinnerec895392012-04-29 02:41:27 +02001391
Victor Stinnerc29b5852017-11-02 07:28:27 -07001392 if (!PyArg_ParseTuple(args, "s:get_clock_info", &name)) {
Victor Stinnerec895392012-04-29 02:41:27 +02001393 return NULL;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001394 }
Victor Stinnerec895392012-04-29 02:41:27 +02001395
1396#ifdef Py_DEBUG
1397 info.implementation = NULL;
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001398 info.monotonic = -1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001399 info.adjustable = -1;
Victor Stinnerec895392012-04-29 02:41:27 +02001400 info.resolution = -1.0;
1401#else
1402 info.implementation = "";
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001403 info.monotonic = 0;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001404 info.adjustable = 0;
Victor Stinnerec895392012-04-29 02:41:27 +02001405 info.resolution = 1.0;
1406#endif
1407
Victor Stinnerc29b5852017-11-02 07:28:27 -07001408 if (strcmp(name, "time") == 0) {
1409 if (_PyTime_GetSystemClockWithInfo(&t, &info) < 0) {
1410 return NULL;
1411 }
1412 }
Victor Stinnerec895392012-04-29 02:41:27 +02001413#ifdef PYCLOCK
Victor Stinnerc29b5852017-11-02 07:28:27 -07001414 else if (strcmp(name, "clock") == 0) {
Victor Stinnerec895392012-04-29 02:41:27 +02001415 obj = pyclock(&info);
Victor Stinnerc29b5852017-11-02 07:28:27 -07001416 if (obj == NULL) {
1417 return NULL;
1418 }
1419 Py_DECREF(obj);
1420 }
Victor Stinnerec895392012-04-29 02:41:27 +02001421#endif
Victor Stinnerc29b5852017-11-02 07:28:27 -07001422 else if (strcmp(name, "monotonic") == 0) {
1423 if (_PyTime_GetMonotonicClockWithInfo(&t, &info) < 0) {
1424 return NULL;
1425 }
1426 }
1427 else if (strcmp(name, "perf_counter") == 0) {
1428 if (_PyTime_GetPerfCounterWithInfo(&t, &info) < 0) {
1429 return NULL;
1430 }
1431 }
1432 else if (strcmp(name, "process_time") == 0) {
1433 if (_PyTime_GetProcessTimeWithInfo(&t, &info) < 0) {
1434 return NULL;
1435 }
1436 }
Antoine Pitrou4bd41c92017-11-15 22:52:21 +01001437#ifdef HAVE_THREAD_TIME
1438 else if (strcmp(name, "thread_time") == 0) {
1439 if (_PyTime_GetThreadTimeWithInfo(&t, &info) < 0) {
1440 return NULL;
1441 }
1442 }
1443#endif
Victor Stinnerec895392012-04-29 02:41:27 +02001444 else {
1445 PyErr_SetString(PyExc_ValueError, "unknown clock");
1446 return NULL;
1447 }
Victor Stinnerec895392012-04-29 02:41:27 +02001448
Victor Stinnerbda4b882012-06-12 22:11:44 +02001449 dict = PyDict_New();
Victor Stinnerc29b5852017-11-02 07:28:27 -07001450 if (dict == NULL) {
Victor Stinnerec895392012-04-29 02:41:27 +02001451 return NULL;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001452 }
Victor Stinnerec895392012-04-29 02:41:27 +02001453
1454 assert(info.implementation != NULL);
1455 obj = PyUnicode_FromString(info.implementation);
Victor Stinnerc29b5852017-11-02 07:28:27 -07001456 if (obj == NULL) {
Victor Stinnerec895392012-04-29 02:41:27 +02001457 goto error;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001458 }
1459 if (PyDict_SetItemString(dict, "implementation", obj) == -1) {
Victor Stinnerbda4b882012-06-12 22:11:44 +02001460 goto error;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001461 }
Victor Stinnerbda4b882012-06-12 22:11:44 +02001462 Py_CLEAR(obj);
Victor Stinnerec895392012-04-29 02:41:27 +02001463
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001464 assert(info.monotonic != -1);
1465 obj = PyBool_FromLong(info.monotonic);
Victor Stinnerc29b5852017-11-02 07:28:27 -07001466 if (obj == NULL) {
Victor Stinnerec895392012-04-29 02:41:27 +02001467 goto error;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001468 }
1469 if (PyDict_SetItemString(dict, "monotonic", obj) == -1) {
Victor Stinnerbda4b882012-06-12 22:11:44 +02001470 goto error;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001471 }
Victor Stinnerbda4b882012-06-12 22:11:44 +02001472 Py_CLEAR(obj);
Victor Stinnerec895392012-04-29 02:41:27 +02001473
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001474 assert(info.adjustable != -1);
1475 obj = PyBool_FromLong(info.adjustable);
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, "adjustable", 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
1484 assert(info.resolution > 0.0);
1485 assert(info.resolution <= 1.0);
1486 obj = PyFloat_FromDouble(info.resolution);
Victor Stinnerc29b5852017-11-02 07:28:27 -07001487 if (obj == NULL) {
Victor Stinnerec895392012-04-29 02:41:27 +02001488 goto error;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001489 }
1490 if (PyDict_SetItemString(dict, "resolution", obj) == -1) {
Victor Stinnerbda4b882012-06-12 22:11:44 +02001491 goto error;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001492 }
Victor Stinnerbda4b882012-06-12 22:11:44 +02001493 Py_CLEAR(obj);
Victor Stinnerec895392012-04-29 02:41:27 +02001494
Victor Stinnerbda4b882012-06-12 22:11:44 +02001495 ns = _PyNamespace_New(dict);
1496 Py_DECREF(dict);
1497 return ns;
Victor Stinnerec895392012-04-29 02:41:27 +02001498
1499error:
Victor Stinnerbda4b882012-06-12 22:11:44 +02001500 Py_DECREF(dict);
1501 Py_XDECREF(obj);
Victor Stinnerec895392012-04-29 02:41:27 +02001502 return NULL;
1503}
1504
1505PyDoc_STRVAR(get_clock_info_doc,
1506"get_clock_info(name: str) -> dict\n\
1507\n\
1508Get information of the specified clock.");
Victor Stinner8b302012012-02-07 23:29:46 +01001509
Victor Stinner8f5cdfa2017-04-20 13:41:09 +02001510#if !defined(HAVE_TZNAME) || defined(__GLIBC__) || defined(__CYGWIN__)
Martin v. Löwisd218dc12008-04-07 03:17:54 +00001511static void
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -04001512get_zone(char *zone, int n, struct tm *p)
1513{
1514#ifdef HAVE_STRUCT_TM_TM_ZONE
1515 strncpy(zone, p->tm_zone ? p->tm_zone : " ", n);
1516#else
1517 tzset();
1518 strftime(zone, n, "%Z", p);
1519#endif
1520}
1521
Victor Stinner38c06d92018-12-01 01:24:21 +01001522static time_t
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -04001523get_gmtoff(time_t t, struct tm *p)
1524{
1525#ifdef HAVE_STRUCT_TM_TM_ZONE
1526 return p->tm_gmtoff;
1527#else
1528 return timegm(p) - t;
1529#endif
1530}
Victor Stinner8f5cdfa2017-04-20 13:41:09 +02001531#endif /* !defined(HAVE_TZNAME) || defined(__GLIBC__) || defined(__CYGWIN__) */
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -04001532
Victor Stinner38c06d92018-12-01 01:24:21 +01001533static int
Victor Stinner5eb78c72018-12-04 00:09:02 +01001534init_timezone(PyObject *m)
Victor Stinner38c06d92018-12-01 01:24:21 +01001535{
1536 assert(!PyErr_Occurred());
1537
Martin v. Löwis1a214512008-06-11 05:26:20 +00001538 /* This code moved from PyInit_time wholesale to allow calling it from
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001539 time_tzset. In the future, some parts of it can be moved back
1540 (for platforms that don't HAVE_WORKING_TZSET, when we know what they
1541 are), and the extraneous calls to tzset(3) should be removed.
1542 I haven't done this yet, as I don't want to change this code as
1543 little as possible when introducing the time.tzset and time.tzsetwall
1544 methods. This should simply be a method of doing the following once,
1545 at the top of this function and removing the call to tzset() from
1546 time_tzset():
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001547
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001548 #ifdef HAVE_TZSET
1549 tzset()
1550 #endif
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001551
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001552 And I'm lazy and hate C so nyer.
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001553 */
Guido van Rossum10b164a2001-09-25 13:59:01 +00001554#if defined(HAVE_TZNAME) && !defined(__GLIBC__) && !defined(__CYGWIN__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001555 PyObject *otz0, *otz1;
1556 tzset();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001557 PyModule_AddIntConstant(m, "timezone", timezone);
Guido van Rossumb6775db1994-08-01 11:34:53 +00001558#ifdef HAVE_ALTZONE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001559 PyModule_AddIntConstant(m, "altzone", altzone);
Guido van Rossumb6775db1994-08-01 11:34:53 +00001560#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001561 PyModule_AddIntConstant(m, "altzone", timezone-3600);
Guido van Rossumb6775db1994-08-01 11:34:53 +00001562#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001563 PyModule_AddIntConstant(m, "daylight", daylight);
Victor Stinner7ed7aea2018-01-15 10:45:49 +01001564 otz0 = PyUnicode_DecodeLocale(tzname[0], "surrogateescape");
Victor Stinner5eb78c72018-12-04 00:09:02 +01001565 if (otz0 == NULL) {
1566 return -1;
1567 }
Victor Stinner7ed7aea2018-01-15 10:45:49 +01001568 otz1 = PyUnicode_DecodeLocale(tzname[1], "surrogateescape");
Victor Stinner5eb78c72018-12-04 00:09:02 +01001569 if (otz1 == NULL) {
1570 Py_DECREF(otz0);
1571 return -1;
1572 }
1573 PyObject *tzname_obj = Py_BuildValue("(NN)", otz0, otz1);
1574 if (tzname_obj == NULL) {
1575 return -1;
1576 }
1577 PyModule_AddObject(m, "tzname", tzname_obj);
Guido van Rossum10b164a2001-09-25 13:59:01 +00001578#else /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001579 {
Guido van Rossum234f9421993-06-17 12:35:49 +00001580#define YEAR ((time_t)((365 * 24 + 6) * 3600))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001581 time_t t;
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -04001582 struct tm p;
Victor Stinner38c06d92018-12-01 01:24:21 +01001583 time_t janzone_t, julyzone_t;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001584 char janname[10], julyname[10];
1585 t = (time((time_t *)0) / YEAR) * YEAR;
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -04001586 _PyTime_localtime(t, &p);
1587 get_zone(janname, 9, &p);
Victor Stinner38c06d92018-12-01 01:24:21 +01001588 janzone_t = -get_gmtoff(t, &p);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001589 janname[9] = '\0';
1590 t += YEAR/2;
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -04001591 _PyTime_localtime(t, &p);
1592 get_zone(julyname, 9, &p);
Victor Stinner38c06d92018-12-01 01:24:21 +01001593 julyzone_t = -get_gmtoff(t, &p);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001594 julyname[9] = '\0';
Guido van Rossum10b164a2001-09-25 13:59:01 +00001595
Victor Stinner38c06d92018-12-01 01:24:21 +01001596 /* Sanity check, don't check for the validity of timezones.
1597 In practice, it should be more in range -12 hours .. +14 hours. */
1598#define MAX_TIMEZONE (48 * 3600)
1599 if (janzone_t < -MAX_TIMEZONE || janzone_t > MAX_TIMEZONE
1600 || julyzone_t < -MAX_TIMEZONE || julyzone_t > MAX_TIMEZONE)
1601 {
1602 PyErr_SetString(PyExc_RuntimeError, "invalid GMT offset");
1603 return -1;
1604 }
1605 int janzone = (int)janzone_t;
1606 int julyzone = (int)julyzone_t;
1607
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001608 if( janzone < julyzone ) {
1609 /* DST is reversed in the southern hemisphere */
1610 PyModule_AddIntConstant(m, "timezone", julyzone);
1611 PyModule_AddIntConstant(m, "altzone", janzone);
1612 PyModule_AddIntConstant(m, "daylight",
1613 janzone != julyzone);
1614 PyModule_AddObject(m, "tzname",
1615 Py_BuildValue("(zz)",
1616 julyname, janname));
1617 } else {
1618 PyModule_AddIntConstant(m, "timezone", janzone);
1619 PyModule_AddIntConstant(m, "altzone", julyzone);
1620 PyModule_AddIntConstant(m, "daylight",
1621 janzone != julyzone);
1622 PyModule_AddObject(m, "tzname",
1623 Py_BuildValue("(zz)",
1624 janname, julyname));
1625 }
1626 }
Tim Peters26ae7cd2001-03-20 03:26:49 +00001627#ifdef __CYGWIN__
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001628 tzset();
1629 PyModule_AddIntConstant(m, "timezone", _timezone);
1630 PyModule_AddIntConstant(m, "altzone", _timezone-3600);
1631 PyModule_AddIntConstant(m, "daylight", _daylight);
1632 PyModule_AddObject(m, "tzname",
1633 Py_BuildValue("(zz)", _tzname[0], _tzname[1]));
Tim Peters26ae7cd2001-03-20 03:26:49 +00001634#endif /* __CYGWIN__ */
Guido van Rossum10b164a2001-09-25 13:59:01 +00001635#endif /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/
Victor Stinner5eb78c72018-12-04 00:09:02 +01001636
1637 if (PyErr_Occurred()) {
1638 return -1;
1639 }
Victor Stinner38c06d92018-12-01 01:24:21 +01001640 return 0;
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001641}
1642
1643
1644static PyMethodDef time_methods[] = {
Victor Stinner4195b5c2012-02-08 23:03:19 +01001645 {"time", time_time, METH_NOARGS, time_doc},
Victor Stinnerc29b5852017-11-02 07:28:27 -07001646 {"time_ns", time_time_ns, METH_NOARGS, time_ns_doc},
Victor Stinnerec895392012-04-29 02:41:27 +02001647#ifdef PYCLOCK
Victor Stinner4195b5c2012-02-08 23:03:19 +01001648 {"clock", time_clock, METH_NOARGS, clock_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001649#endif
Victor Stinnere0be4232011-10-25 13:06:09 +02001650#ifdef HAVE_CLOCK_GETTIME
Victor Stinner4195b5c2012-02-08 23:03:19 +01001651 {"clock_gettime", time_clock_gettime, METH_VARARGS, clock_gettime_doc},
Victor Stinnerc29b5852017-11-02 07:28:27 -07001652 {"clock_gettime_ns",time_clock_gettime_ns, METH_VARARGS, clock_gettime_ns_doc},
Benjamin Peterson37098cd2016-09-13 22:55:09 -07001653#endif
1654#ifdef HAVE_CLOCK_SETTIME
Victor Stinner30d79472012-04-03 00:45:07 +02001655 {"clock_settime", time_clock_settime, METH_VARARGS, clock_settime_doc},
Victor Stinnerc29b5852017-11-02 07:28:27 -07001656 {"clock_settime_ns",time_clock_settime_ns, METH_VARARGS, clock_settime_ns_doc},
Benjamin Peterson37098cd2016-09-13 22:55:09 -07001657#endif
1658#ifdef HAVE_CLOCK_GETRES
Victor Stinner4195b5c2012-02-08 23:03:19 +01001659 {"clock_getres", time_clock_getres, METH_VARARGS, clock_getres_doc},
Victor Stinnere0be4232011-10-25 13:06:09 +02001660#endif
pdoxe14679c2017-10-05 00:01:56 -07001661#ifdef HAVE_PTHREAD_GETCPUCLOCKID
1662 {"pthread_getcpuclockid", time_pthread_getcpuclockid, METH_VARARGS, pthread_getcpuclockid_doc},
1663#endif
Victor Stinnercb29f012015-03-27 13:31:18 +01001664 {"sleep", time_sleep, METH_O, sleep_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001665 {"gmtime", time_gmtime, METH_VARARGS, gmtime_doc},
1666 {"localtime", time_localtime, METH_VARARGS, localtime_doc},
1667 {"asctime", time_asctime, METH_VARARGS, asctime_doc},
1668 {"ctime", time_ctime, METH_VARARGS, ctime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001669#ifdef HAVE_MKTIME
Victor Stinner4195b5c2012-02-08 23:03:19 +01001670 {"mktime", time_mktime, METH_O, mktime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001671#endif
1672#ifdef HAVE_STRFTIME
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001673 {"strftime", time_strftime, METH_VARARGS, strftime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001674#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001675 {"strptime", time_strptime, METH_VARARGS, strptime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001676#ifdef HAVE_WORKING_TZSET
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001677 {"tzset", time_tzset, METH_NOARGS, tzset_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001678#endif
Victor Stinnerec895392012-04-29 02:41:27 +02001679 {"monotonic", time_monotonic, METH_NOARGS, monotonic_doc},
Victor Stinnerc29b5852017-11-02 07:28:27 -07001680 {"monotonic_ns", time_monotonic_ns, METH_NOARGS, monotonic_ns_doc},
Victor Stinnerec895392012-04-29 02:41:27 +02001681 {"process_time", time_process_time, METH_NOARGS, process_time_doc},
Victor Stinnerc29b5852017-11-02 07:28:27 -07001682 {"process_time_ns", time_process_time_ns, METH_NOARGS, process_time_ns_doc},
Antoine Pitrou4bd41c92017-11-15 22:52:21 +01001683#ifdef HAVE_THREAD_TIME
1684 {"thread_time", time_thread_time, METH_NOARGS, thread_time_doc},
1685 {"thread_time_ns", time_thread_time_ns, METH_NOARGS, thread_time_ns_doc},
1686#endif
Victor Stinnerec895392012-04-29 02:41:27 +02001687 {"perf_counter", time_perf_counter, METH_NOARGS, perf_counter_doc},
Victor Stinnerc29b5852017-11-02 07:28:27 -07001688 {"perf_counter_ns", time_perf_counter_ns, METH_NOARGS, perf_counter_ns_doc},
Victor Stinnerec895392012-04-29 02:41:27 +02001689 {"get_clock_info", time_get_clock_info, METH_VARARGS, get_clock_info_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001690 {NULL, NULL} /* sentinel */
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001691};
1692
1693
1694PyDoc_STRVAR(module_doc,
1695"This module provides various functions to manipulate time values.\n\
1696\n\
1697There are two standard representations of time. One is the number\n\
1698of seconds since the Epoch, in UTC (a.k.a. GMT). It may be an integer\n\
1699or a floating point number (to represent fractions of seconds).\n\
1700The Epoch is system-defined; on Unix, it is generally January 1st, 1970.\n\
1701The actual value can be retrieved by calling gmtime(0).\n\
1702\n\
1703The other representation is a tuple of 9 integers giving local time.\n\
1704The tuple items are:\n\
Alexander Belopolsky03163ac2011-05-02 12:20:52 -04001705 year (including century, e.g. 1998)\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001706 month (1-12)\n\
1707 day (1-31)\n\
1708 hours (0-23)\n\
1709 minutes (0-59)\n\
1710 seconds (0-59)\n\
1711 weekday (0-6, Monday is 0)\n\
1712 Julian day (day in the year, 1-366)\n\
1713 DST (Daylight Savings Time) flag (-1, 0 or 1)\n\
1714If the DST flag is 0, the time is given in the regular time zone;\n\
1715if it is 1, the time is given in the DST time zone;\n\
Cheryl Sabella703ff382017-10-11 09:29:14 -04001716if it is -1, mktime() should guess based on the date and time.\n");
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001717
1718
Martin v. Löwis1a214512008-06-11 05:26:20 +00001719
1720static struct PyModuleDef timemodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001721 PyModuleDef_HEAD_INIT,
1722 "time",
1723 module_doc,
1724 -1,
1725 time_methods,
1726 NULL,
1727 NULL,
1728 NULL,
1729 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00001730};
1731
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001732PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00001733PyInit_time(void)
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001734{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001735 PyObject *m;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001736 m = PyModule_Create(&timemodule);
1737 if (m == NULL)
1738 return NULL;
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001739
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001740 /* Set, or reset, module variables like time.timezone */
Victor Stinner5eb78c72018-12-04 00:09:02 +01001741 if (init_timezone(m) < 0) {
Victor Stinner38c06d92018-12-01 01:24:21 +01001742 return NULL;
1743 }
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001744
Miss Islington (bot)002aef32018-10-20 17:41:38 -07001745#if defined(HAVE_CLOCK_GETTIME) || defined(HAVE_CLOCK_SETTIME) || defined(HAVE_CLOCK_GETRES)
1746
Benjamin Peterson37098cd2016-09-13 22:55:09 -07001747#ifdef CLOCK_REALTIME
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -04001748 PyModule_AddIntMacro(m, CLOCK_REALTIME);
Benjamin Peterson37098cd2016-09-13 22:55:09 -07001749#endif
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -04001750#ifdef CLOCK_MONOTONIC
1751 PyModule_AddIntMacro(m, CLOCK_MONOTONIC);
1752#endif
1753#ifdef CLOCK_MONOTONIC_RAW
1754 PyModule_AddIntMacro(m, CLOCK_MONOTONIC_RAW);
1755#endif
1756#ifdef CLOCK_HIGHRES
1757 PyModule_AddIntMacro(m, CLOCK_HIGHRES);
1758#endif
1759#ifdef CLOCK_PROCESS_CPUTIME_ID
1760 PyModule_AddIntMacro(m, CLOCK_PROCESS_CPUTIME_ID);
1761#endif
1762#ifdef CLOCK_THREAD_CPUTIME_ID
1763 PyModule_AddIntMacro(m, CLOCK_THREAD_CPUTIME_ID);
1764#endif
Victor Stinnera64ce972017-11-02 04:19:19 -07001765#ifdef CLOCK_PROF
1766 PyModule_AddIntMacro(m, CLOCK_PROF);
1767#endif
1768#ifdef CLOCK_BOOTTIME
1769 PyModule_AddIntMacro(m, CLOCK_BOOTTIME);
1770#endif
1771#ifdef CLOCK_UPTIME
1772 PyModule_AddIntMacro(m, CLOCK_UPTIME);
1773#endif
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -04001774
Miss Islington (bot)002aef32018-10-20 17:41:38 -07001775#endif /* defined(HAVE_CLOCK_GETTIME) || defined(HAVE_CLOCK_SETTIME) || defined(HAVE_CLOCK_GETRES) */
1776
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001777 if (!initialized) {
Victor Stinner1c8f0592013-07-22 22:24:54 +02001778 if (PyStructSequence_InitType2(&StructTimeType,
1779 &struct_time_type_desc) < 0)
1780 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001781 }
1782 Py_INCREF(&StructTimeType);
Alexander Belopolskyc142bba2012-06-13 22:15:26 -04001783 PyModule_AddIntConstant(m, "_STRUCT_TM_ITEMS", 11);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001784 PyModule_AddObject(m, "struct_time", (PyObject*) &StructTimeType);
1785 initialized = 1;
Victor Stinner5eb78c72018-12-04 00:09:02 +01001786
1787 if (PyErr_Occurred()) {
1788 return NULL;
1789 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001790 return m;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001791}
1792
Victor Stinnercb29f012015-03-27 13:31:18 +01001793/* Implement pysleep() for various platforms.
Guido van Rossumb6775db1994-08-01 11:34:53 +00001794 When interrupted (or when another error occurs), return -1 and
1795 set an exception; else return 0. */
1796
1797static int
Victor Stinnercb29f012015-03-27 13:31:18 +01001798pysleep(_PyTime_t secs)
Guido van Rossum426035c1991-02-19 12:27:35 +00001799{
Victor Stinnercb29f012015-03-27 13:31:18 +01001800 _PyTime_t deadline, monotonic;
Victor Stinner79d68f92015-03-19 21:54:09 +01001801#ifndef MS_WINDOWS
1802 struct timeval timeout;
Victor Stinner79d68f92015-03-19 21:54:09 +01001803 int err = 0;
1804#else
Victor Stinnercb29f012015-03-27 13:31:18 +01001805 _PyTime_t millisecs;
Victor Stinner79d68f92015-03-19 21:54:09 +01001806 unsigned long ul_millis;
1807 DWORD rc;
1808 HANDLE hInterruptEvent;
Victor Stinner0c2fd892015-03-17 10:49:17 +01001809#endif
Victor Stinner79d68f92015-03-19 21:54:09 +01001810
Victor Stinnercb29f012015-03-27 13:31:18 +01001811 deadline = _PyTime_GetMonotonicClock() + secs;
Victor Stinner79d68f92015-03-19 21:54:09 +01001812
1813 do {
1814#ifndef MS_WINDOWS
Victor Stinner869e1772015-03-30 03:49:14 +02001815 if (_PyTime_AsTimeval(secs, &timeout, _PyTime_ROUND_CEILING) < 0)
Victor Stinnercb29f012015-03-27 13:31:18 +01001816 return -1;
Victor Stinner79d68f92015-03-19 21:54:09 +01001817
1818 Py_BEGIN_ALLOW_THREADS
1819 err = select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &timeout);
1820 Py_END_ALLOW_THREADS
1821
1822 if (err == 0)
1823 break;
1824
1825 if (errno != EINTR) {
Victor Stinner0c2fd892015-03-17 10:49:17 +01001826 PyErr_SetFromErrno(PyExc_OSError);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001827 return -1;
1828 }
Victor Stinner79d68f92015-03-19 21:54:09 +01001829#else
Victor Stinner869e1772015-03-30 03:49:14 +02001830 millisecs = _PyTime_AsMilliseconds(secs, _PyTime_ROUND_CEILING);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001831 if (millisecs > (double)ULONG_MAX) {
1832 PyErr_SetString(PyExc_OverflowError,
1833 "sleep length is too large");
1834 return -1;
1835 }
Victor Stinner79d68f92015-03-19 21:54:09 +01001836
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001837 /* Allow sleep(0) to maintain win32 semantics, and as decreed
1838 * by Guido, only the main thread can be interrupted.
1839 */
1840 ul_millis = (unsigned long)millisecs;
Victor Stinner79d68f92015-03-19 21:54:09 +01001841 if (ul_millis == 0 || !_PyOS_IsMainThread()) {
1842 Py_BEGIN_ALLOW_THREADS
Victor Stinner0eac1302015-03-20 03:06:12 +01001843 Sleep(ul_millis);
Victor Stinner79d68f92015-03-19 21:54:09 +01001844 Py_END_ALLOW_THREADS
1845 break;
Victor Stinner945c82e2015-03-12 16:19:01 +01001846 }
Victor Stinner79d68f92015-03-19 21:54:09 +01001847
1848 hInterruptEvent = _PyOS_SigintEvent();
1849 ResetEvent(hInterruptEvent);
1850
1851 Py_BEGIN_ALLOW_THREADS
1852 rc = WaitForSingleObjectEx(hInterruptEvent, ul_millis, FALSE);
Victor Stinner0c2fd892015-03-17 10:49:17 +01001853 Py_END_ALLOW_THREADS
Victor Stinner79d68f92015-03-19 21:54:09 +01001854
1855 if (rc != WAIT_OBJECT_0)
1856 break;
Victor Stinner945c82e2015-03-12 16:19:01 +01001857#endif
Victor Stinner0c2fd892015-03-17 10:49:17 +01001858
Victor Stinner79d68f92015-03-19 21:54:09 +01001859 /* sleep was interrupted by SIGINT */
1860 if (PyErr_CheckSignals())
1861 return -1;
1862
Victor Stinnercb29f012015-03-27 13:31:18 +01001863 monotonic = _PyTime_GetMonotonicClock();
1864 secs = deadline - monotonic;
Victor Stinner6aa446c2015-03-30 21:33:51 +02001865 if (secs < 0)
Victor Stinner79d68f92015-03-19 21:54:09 +01001866 break;
1867 /* retry with the recomputed delay */
1868 } while (1);
1869
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001870 return 0;
Guido van Rossum80c9d881991-04-16 08:47:51 +00001871}