blob: eca67d9e28694b4ef4b3159e661240a09b2a9698 [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
Guido van Rossum7bf22de1997-12-02 20:34:19 +000023#if defined(__WATCOMC__) && !defined(__QNX__)
Guido van Rossumbceeac81996-05-23 22:53:47 +000024#include <i86.h>
25#else
Guido van Rossumcac6c721996-09-06 13:34:02 +000026#ifdef MS_WINDOWS
Mark Hammond975e3922002-07-16 01:29:19 +000027#define WIN32_LEAN_AND_MEAN
Guido van Rossum258ccd42001-03-02 06:53:29 +000028#include <windows.h>
Mark Hammond975e3922002-07-16 01:29:19 +000029#include "pythread.h"
Guido van Rossumcac6c721996-09-06 13:34:02 +000030#endif /* MS_WINDOWS */
Guido van Rossum7bf22de1997-12-02 20:34:19 +000031#endif /* !__WATCOMC__ || __QNX__ */
Guido van Rossum234f9421993-06-17 12:35:49 +000032
33/* Forward declarations */
Victor Stinnercb29f012015-03-27 13:31:18 +010034static int pysleep(_PyTime_t);
Victor Stinnerec895392012-04-29 02:41:27 +020035static PyObject* floattime(_Py_clock_info_t *info);
36
Barry Warsaw9a2a8a81996-12-06 23:32:14 +000037static PyObject *
Victor Stinner4195b5c2012-02-08 23:03:19 +010038time_time(PyObject *self, PyObject *unused)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000039{
Victor Stinnerec895392012-04-29 02:41:27 +020040 return floattime(NULL);
Guido van Rossumb6775db1994-08-01 11:34:53 +000041}
42
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000043PyDoc_STRVAR(time_doc,
Victor Stinner4195b5c2012-02-08 23:03:19 +010044"time() -> floating point number\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +000045\n\
46Return the current time in seconds since the Epoch.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000047Fractions of a second may be present if the system clock provides them.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +000048
Victor Stinner85fdfa82012-01-27 00:38:48 +010049#if defined(HAVE_CLOCK)
50
51#ifndef CLOCKS_PER_SEC
52#ifdef CLK_TCK
53#define CLOCKS_PER_SEC CLK_TCK
54#else
55#define CLOCKS_PER_SEC 1000000
56#endif
57#endif
58
Victor Stinner4195b5c2012-02-08 23:03:19 +010059static PyObject *
Victor Stinnerec895392012-04-29 02:41:27 +020060floatclock(_Py_clock_info_t *info)
Victor Stinner85fdfa82012-01-27 00:38:48 +010061{
Victor Stinner4195b5c2012-02-08 23:03:19 +010062 clock_t value;
63 value = clock();
64 if (value == (clock_t)-1) {
Victor Stinner85fdfa82012-01-27 00:38:48 +010065 PyErr_SetString(PyExc_RuntimeError,
66 "the processor time used is not available "
67 "or its value cannot be represented");
Victor Stinner4195b5c2012-02-08 23:03:19 +010068 return NULL;
Victor Stinner85fdfa82012-01-27 00:38:48 +010069 }
Victor Stinnerec895392012-04-29 02:41:27 +020070 if (info) {
71 info->implementation = "clock()";
72 info->resolution = 1.0 / (double)CLOCKS_PER_SEC;
Benjamin Peterson49a69e42012-05-01 09:38:34 -040073 info->monotonic = 1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +020074 info->adjustable = 0;
Victor Stinnerec895392012-04-29 02:41:27 +020075 }
Victor Stinner4195b5c2012-02-08 23:03:19 +010076 return PyFloat_FromDouble((double)value / CLOCKS_PER_SEC);
Victor Stinner85fdfa82012-01-27 00:38:48 +010077}
78#endif /* HAVE_CLOCK */
79
Victor Stinnerf427a142014-10-22 12:33:23 +020080#ifdef MS_WINDOWS
Victor Stinnerec895392012-04-29 02:41:27 +020081#define WIN32_PERF_COUNTER
Victor Stinner9122fdd2011-07-04 13:55:40 +020082/* Win32 has better clock replacement; we have our own version, due to Mark
83 Hammond and Tim Peters */
Victor Stinner54884492014-08-29 16:51:33 +020084static PyObject*
85win_perf_counter(_Py_clock_info_t *info)
Guido van Rossum3917c221997-04-02 05:35:28 +000086{
Victor Stinner8b302012012-02-07 23:29:46 +010087 static LONGLONG cpu_frequency = 0;
Victor Stinner4195b5c2012-02-08 23:03:19 +010088 static LONGLONG ctrStart;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000089 LARGE_INTEGER now;
Victor Stinner4195b5c2012-02-08 23:03:19 +010090 double diff;
Guido van Rossum3917c221997-04-02 05:35:28 +000091
Victor Stinner8b302012012-02-07 23:29:46 +010092 if (cpu_frequency == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000093 LARGE_INTEGER freq;
Victor Stinner8b302012012-02-07 23:29:46 +010094 QueryPerformanceCounter(&now);
Victor Stinner4195b5c2012-02-08 23:03:19 +010095 ctrStart = now.QuadPart;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000096 if (!QueryPerformanceFrequency(&freq) || freq.QuadPart == 0) {
Victor Stinner54884492014-08-29 16:51:33 +020097 PyErr_SetFromWindowsErr(0);
98 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000099 }
Victor Stinner8b302012012-02-07 23:29:46 +0100100 cpu_frequency = freq.QuadPart;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000101 }
102 QueryPerformanceCounter(&now);
Victor Stinner4195b5c2012-02-08 23:03:19 +0100103 diff = (double)(now.QuadPart - ctrStart);
Victor Stinnerec895392012-04-29 02:41:27 +0200104 if (info) {
105 info->implementation = "QueryPerformanceCounter()";
106 info->resolution = 1.0 / (double)cpu_frequency;
Benjamin Peterson49a69e42012-05-01 09:38:34 -0400107 info->monotonic = 1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +0200108 info->adjustable = 0;
Victor Stinnerec895392012-04-29 02:41:27 +0200109 }
Victor Stinner54884492014-08-29 16:51:33 +0200110 return PyFloat_FromDouble(diff / (double)cpu_frequency);
Guido van Rossum3917c221997-04-02 05:35:28 +0000111}
Victor Stinnerf427a142014-10-22 12:33:23 +0200112#endif /* MS_WINDOWS */
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000113
Victor Stinnerec895392012-04-29 02:41:27 +0200114#if defined(WIN32_PERF_COUNTER) || defined(HAVE_CLOCK)
115#define PYCLOCK
116static PyObject*
117pyclock(_Py_clock_info_t *info)
118{
119#ifdef WIN32_PERF_COUNTER
Victor Stinner54884492014-08-29 16:51:33 +0200120 return win_perf_counter(info);
121#else
Victor Stinnerec895392012-04-29 02:41:27 +0200122 return floatclock(info);
Victor Stinner54884492014-08-29 16:51:33 +0200123#endif
Victor Stinnerec895392012-04-29 02:41:27 +0200124}
125
Victor Stinner9122fdd2011-07-04 13:55:40 +0200126static PyObject *
Victor Stinner4195b5c2012-02-08 23:03:19 +0100127time_clock(PyObject *self, PyObject *unused)
Victor Stinner9122fdd2011-07-04 13:55:40 +0200128{
Victor Stinnerec895392012-04-29 02:41:27 +0200129 return pyclock(NULL);
Victor Stinner9122fdd2011-07-04 13:55:40 +0200130}
Victor Stinner9122fdd2011-07-04 13:55:40 +0200131
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000132PyDoc_STRVAR(clock_doc,
Victor Stinner4195b5c2012-02-08 23:03:19 +0100133"clock() -> floating point number\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000134\n\
135Return the CPU time or real time since the start of the process or since\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000136the first call to clock(). This has as much precision as the system\n\
137records.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000138#endif
139
Victor Stinnere0be4232011-10-25 13:06:09 +0200140#ifdef HAVE_CLOCK_GETTIME
141static PyObject *
Victor Stinner4195b5c2012-02-08 23:03:19 +0100142time_clock_gettime(PyObject *self, PyObject *args)
Victor Stinnere0be4232011-10-25 13:06:09 +0200143{
144 int ret;
Victor Stinnerb8d01692012-04-13 23:44:05 +0200145 int clk_id;
Victor Stinnere0be4232011-10-25 13:06:09 +0200146 struct timespec tp;
147
Victor Stinner4195b5c2012-02-08 23:03:19 +0100148 if (!PyArg_ParseTuple(args, "i:clock_gettime", &clk_id))
Victor Stinnere0be4232011-10-25 13:06:09 +0200149 return NULL;
150
151 ret = clock_gettime((clockid_t)clk_id, &tp);
Antoine Pitrou2c085602012-01-18 01:41:44 +0100152 if (ret != 0) {
Victor Stinnera734af32014-07-31 13:07:17 +0200153 PyErr_SetFromErrno(PyExc_OSError);
Antoine Pitrou2c085602012-01-18 01:41:44 +0100154 return NULL;
155 }
Victor Stinner4195b5c2012-02-08 23:03:19 +0100156 return PyFloat_FromDouble(tp.tv_sec + tp.tv_nsec * 1e-9);
Victor Stinnere0be4232011-10-25 13:06:09 +0200157}
158
159PyDoc_STRVAR(clock_gettime_doc,
Victor Stinner4195b5c2012-02-08 23:03:19 +0100160"clock_gettime(clk_id) -> floating point number\n\
Victor Stinnere0be4232011-10-25 13:06:09 +0200161\n\
162Return the time of the specified clock clk_id.");
Victor Stinner30d79472012-04-03 00:45:07 +0200163
164static PyObject *
165time_clock_settime(PyObject *self, PyObject *args)
166{
Victor Stinnerb8d01692012-04-13 23:44:05 +0200167 int clk_id;
Victor Stinner30d79472012-04-03 00:45:07 +0200168 PyObject *obj;
Victor Stinnerb3b45442015-03-28 04:09:41 +0100169 _PyTime_t t;
Victor Stinner30d79472012-04-03 00:45:07 +0200170 struct timespec tp;
171 int ret;
172
173 if (!PyArg_ParseTuple(args, "iO:clock_settime", &clk_id, &obj))
174 return NULL;
175
Victor Stinner02937aa2015-03-28 05:02:39 +0100176 if (_PyTime_FromSecondsObject(&t, obj, _PyTime_ROUND_FLOOR) < 0)
Victor Stinner30d79472012-04-03 00:45:07 +0200177 return NULL;
Victor Stinnerb3b45442015-03-28 04:09:41 +0100178
179 if (_PyTime_AsTimespec(t, &tp) == -1)
180 return NULL;
Victor Stinner30d79472012-04-03 00:45:07 +0200181
182 ret = clock_settime((clockid_t)clk_id, &tp);
183 if (ret != 0) {
Victor Stinnera734af32014-07-31 13:07:17 +0200184 PyErr_SetFromErrno(PyExc_OSError);
Victor Stinner30d79472012-04-03 00:45:07 +0200185 return NULL;
186 }
187 Py_RETURN_NONE;
188}
189
190PyDoc_STRVAR(clock_settime_doc,
191"clock_settime(clk_id, time)\n\
192\n\
193Set the time of the specified clock clk_id.");
Victor Stinnere0be4232011-10-25 13:06:09 +0200194
Victor Stinnere0be4232011-10-25 13:06:09 +0200195static PyObject *
Victor Stinner4195b5c2012-02-08 23:03:19 +0100196time_clock_getres(PyObject *self, PyObject *args)
Victor Stinnere0be4232011-10-25 13:06:09 +0200197{
198 int ret;
Victor Stinnerb8d01692012-04-13 23:44:05 +0200199 int clk_id;
Victor Stinnere0be4232011-10-25 13:06:09 +0200200 struct timespec tp;
201
Victor Stinner4195b5c2012-02-08 23:03:19 +0100202 if (!PyArg_ParseTuple(args, "i:clock_getres", &clk_id))
Victor Stinnere0be4232011-10-25 13:06:09 +0200203 return NULL;
204
205 ret = clock_getres((clockid_t)clk_id, &tp);
Antoine Pitrou2c085602012-01-18 01:41:44 +0100206 if (ret != 0) {
Victor Stinnera734af32014-07-31 13:07:17 +0200207 PyErr_SetFromErrno(PyExc_OSError);
Antoine Pitrou2c085602012-01-18 01:41:44 +0100208 return NULL;
209 }
Victor Stinner4195b5c2012-02-08 23:03:19 +0100210
211 return PyFloat_FromDouble(tp.tv_sec + tp.tv_nsec * 1e-9);
Victor Stinnere0be4232011-10-25 13:06:09 +0200212}
213
214PyDoc_STRVAR(clock_getres_doc,
Victor Stinner4195b5c2012-02-08 23:03:19 +0100215"clock_getres(clk_id) -> floating point number\n\
Victor Stinnere0be4232011-10-25 13:06:09 +0200216\n\
217Return the resolution (precision) of the specified clock clk_id.");
Victor Stinnerb8d01692012-04-13 23:44:05 +0200218#endif /* HAVE_CLOCK_GETTIME */
Victor Stinnere0be4232011-10-25 13:06:09 +0200219
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000220static PyObject *
Victor Stinnercb29f012015-03-27 13:31:18 +0100221time_sleep(PyObject *self, PyObject *obj)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000222{
Victor Stinnercb29f012015-03-27 13:31:18 +0100223 _PyTime_t secs;
Victor Stinner869e1772015-03-30 03:49:14 +0200224 if (_PyTime_FromSecondsObject(&secs, obj, _PyTime_ROUND_CEILING))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000225 return NULL;
Victor Stinner7f53a502011-07-05 22:00:25 +0200226 if (secs < 0) {
227 PyErr_SetString(PyExc_ValueError,
228 "sleep length must be non-negative");
229 return NULL;
230 }
Victor Stinnercb29f012015-03-27 13:31:18 +0100231 if (pysleep(secs) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000232 return NULL;
233 Py_INCREF(Py_None);
234 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000235}
236
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000237PyDoc_STRVAR(sleep_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000238"sleep(seconds)\n\
239\n\
240Delay execution for a given number of seconds. The argument may be\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000241a floating point number for subsecond precision.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000242
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000243static PyStructSequence_Field struct_time_type_fields[] = {
Alexander Belopolsky69f3fd02010-06-05 15:04:51 +0000244 {"tm_year", "year, for example, 1993"},
245 {"tm_mon", "month of year, range [1, 12]"},
246 {"tm_mday", "day of month, range [1, 31]"},
247 {"tm_hour", "hours, range [0, 23]"},
248 {"tm_min", "minutes, range [0, 59]"},
249 {"tm_sec", "seconds, range [0, 61])"},
250 {"tm_wday", "day of week, range [0, 6], Monday is 0"},
251 {"tm_yday", "day of year, range [1, 366]"},
252 {"tm_isdst", "1 if summer time is in effect, 0 if not, and -1 if unknown"},
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400253#ifdef HAVE_STRUCT_TM_TM_ZONE
254 {"tm_zone", "abbreviation of timezone name"},
255 {"tm_gmtoff", "offset from UTC in seconds"},
256#endif /* HAVE_STRUCT_TM_TM_ZONE */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000257 {0}
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000258};
259
260static PyStructSequence_Desc struct_time_type_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000261 "time.struct_time",
Alexander Belopolsky69f3fd02010-06-05 15:04:51 +0000262 "The time value as returned by gmtime(), localtime(), and strptime(), and\n"
263 " accepted by asctime(), mktime() and strftime(). May be considered as a\n"
264 " sequence of 9 integers.\n\n"
265 " Note that several fields' values are not the same as those defined by\n"
266 " the C language standard for struct tm. For example, the value of the\n"
267 " field tm_year is the actual year, not year - 1900. See individual\n"
268 " fields' descriptions for details.",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000269 struct_time_type_fields,
270 9,
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000271};
Tim Peters9ad4b682002-02-13 05:14:18 +0000272
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000273static int initialized;
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000274static PyTypeObject StructTimeType;
275
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400276
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000277static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000278tmtotuple(struct tm *p)
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000279{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000280 PyObject *v = PyStructSequence_New(&StructTimeType);
281 if (v == NULL)
282 return NULL;
Tim Peters9ad4b682002-02-13 05:14:18 +0000283
Christian Heimes217cfd12007-12-02 14:31:20 +0000284#define SET(i,val) PyStructSequence_SET_ITEM(v, i, PyLong_FromLong((long) val))
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000285
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000286 SET(0, p->tm_year + 1900);
287 SET(1, p->tm_mon + 1); /* Want January == 1 */
288 SET(2, p->tm_mday);
289 SET(3, p->tm_hour);
290 SET(4, p->tm_min);
291 SET(5, p->tm_sec);
292 SET(6, (p->tm_wday + 6) % 7); /* Want Monday == 0 */
293 SET(7, p->tm_yday + 1); /* Want January, 1 == 1 */
294 SET(8, p->tm_isdst);
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400295#ifdef HAVE_STRUCT_TM_TM_ZONE
296 PyStructSequence_SET_ITEM(v, 9,
297 PyUnicode_DecodeLocale(p->tm_zone, "surrogateescape"));
298 SET(10, p->tm_gmtoff);
299#endif /* HAVE_STRUCT_TM_TM_ZONE */
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000300#undef SET
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000301 if (PyErr_Occurred()) {
302 Py_XDECREF(v);
303 return NULL;
304 }
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000305
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000306 return v;
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000307}
308
Fred Drakef901abd2004-08-03 17:58:55 +0000309/* Parse arg tuple that can contain an optional float-or-None value;
310 format needs to be "|O:name".
311 Returns non-zero on success (parallels PyArg_ParseTuple).
312*/
313static int
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100314parse_time_t_args(PyObject *args, char *format, time_t *pwhen)
Fred Drakef901abd2004-08-03 17:58:55 +0000315{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000316 PyObject *ot = NULL;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100317 time_t whent;
Fred Drakef901abd2004-08-03 17:58:55 +0000318
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000319 if (!PyArg_ParseTuple(args, format, &ot))
320 return 0;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100321 if (ot == NULL || ot == Py_None) {
322 whent = time(NULL);
323 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000324 else {
Victor Stinner02937aa2015-03-28 05:02:39 +0100325 if (_PyTime_ObjectToTime_t(ot, &whent, _PyTime_ROUND_FLOOR) == -1)
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100326 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000327 }
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100328 *pwhen = whent;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000329 return 1;
Fred Drakef901abd2004-08-03 17:58:55 +0000330}
331
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000332static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000333time_gmtime(PyObject *self, PyObject *args)
Guido van Rossum234f9421993-06-17 12:35:49 +0000334{
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100335 time_t when;
336 struct tm buf, *local;
337
338 if (!parse_time_t_args(args, "|O:gmtime", &when))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000339 return NULL;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100340
341 errno = 0;
342 local = gmtime(&when);
343 if (local == NULL) {
344#ifdef EINVAL
345 if (errno == 0)
346 errno = EINVAL;
347#endif
348 return PyErr_SetFromErrno(PyExc_OSError);
349 }
350 buf = *local;
351 return tmtotuple(&buf);
Guido van Rossum234f9421993-06-17 12:35:49 +0000352}
353
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000354PyDoc_STRVAR(gmtime_doc,
Christian Heimes9a371592007-12-28 14:08:13 +0000355"gmtime([seconds]) -> (tm_year, tm_mon, tm_mday, tm_hour, tm_min,\n\
Fred Drake193a3f62002-03-12 21:38:49 +0000356 tm_sec, tm_wday, tm_yday, tm_isdst)\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000357\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000358Convert seconds since the Epoch to a time tuple expressing UTC (a.k.a.\n\
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400359GMT). When 'seconds' is not passed in, convert the current time instead.\n\
360\n\
361If the platform supports the tm_gmtoff and tm_zone, they are available as\n\
362attributes only.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000363
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100364static int
365pylocaltime(time_t *timep, struct tm *result)
366{
367 struct tm *local;
368
369 assert (timep != NULL);
370 local = localtime(timep);
371 if (local == NULL) {
372 /* unconvertible time */
373#ifdef EINVAL
374 if (errno == 0)
375 errno = EINVAL;
376#endif
377 PyErr_SetFromErrno(PyExc_OSError);
378 return -1;
379 }
380 *result = *local;
381 return 0;
382}
383
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000384static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000385time_localtime(PyObject *self, PyObject *args)
Guido van Rossum234f9421993-06-17 12:35:49 +0000386{
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100387 time_t when;
388 struct tm buf;
389
390 if (!parse_time_t_args(args, "|O:localtime", &when))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000391 return NULL;
Alexander Belopolskyd9738242012-06-12 16:14:17 -0400392 if (pylocaltime(&when, &buf) == -1)
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100393 return NULL;
394 return tmtotuple(&buf);
Guido van Rossum234f9421993-06-17 12:35:49 +0000395}
396
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000397PyDoc_STRVAR(localtime_doc,
Christian Heimes9a371592007-12-28 14:08:13 +0000398"localtime([seconds]) -> (tm_year,tm_mon,tm_mday,tm_hour,tm_min,\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000399 tm_sec,tm_wday,tm_yday,tm_isdst)\n\
Martin v. Löwisb3cfc1d2001-12-02 12:27:43 +0000400\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000401Convert seconds since the Epoch to a time tuple expressing local time.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000402When 'seconds' is not passed in, convert the current time instead.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000403
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000404/* Convert 9-item tuple to tm structure. Return 1 on success, set
405 * an exception and return 0 on error.
406 */
Guido van Rossum9e90a671993-06-24 11:10:19 +0000407static int
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000408gettmarg(PyObject *args, struct tm *p)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000409{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000410 int y;
Guido van Rossumcfbaecc1998-08-25 14:51:12 +0000411
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000412 memset((void *) p, '\0', sizeof(struct tm));
Guido van Rossumb9081262007-08-25 03:14:09 +0000413
Alexander Belopolsky610e5442011-01-06 21:57:06 +0000414 if (!PyTuple_Check(args)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000415 PyErr_SetString(PyExc_TypeError,
416 "Tuple or struct_time argument required");
417 return 0;
418 }
Skip Montanaro41cfce92007-08-24 21:11:00 +0000419
Alexander Belopolsky610e5442011-01-06 21:57:06 +0000420 if (!PyArg_ParseTuple(args, "iiiiiiiii",
421 &y, &p->tm_mon, &p->tm_mday,
422 &p->tm_hour, &p->tm_min, &p->tm_sec,
423 &p->tm_wday, &p->tm_yday, &p->tm_isdst))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000424 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000425 p->tm_year = y - 1900;
426 p->tm_mon--;
427 p->tm_wday = (p->tm_wday + 1) % 7;
428 p->tm_yday--;
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400429#ifdef HAVE_STRUCT_TM_TM_ZONE
430 if (Py_TYPE(args) == &StructTimeType) {
431 PyObject *item;
432 item = PyTuple_GET_ITEM(args, 9);
433 p->tm_zone = item == Py_None ? NULL : _PyUnicode_AsString(item);
434 item = PyTuple_GET_ITEM(args, 10);
435 p->tm_gmtoff = item == Py_None ? 0 : PyLong_AsLong(item);
436 if (PyErr_Occurred())
437 return 0;
438 }
439#endif /* HAVE_STRUCT_TM_TM_ZONE */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000440 return 1;
Guido van Rossum9e90a671993-06-24 11:10:19 +0000441}
442
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000443/* Check values of the struct tm fields before it is passed to strftime() and
444 * asctime(). Return 1 if all values are valid, otherwise set an exception
445 * and returns 0.
446 */
Victor Stinneref128102010-10-07 01:00:52 +0000447static int
448checktm(struct tm* buf)
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000449{
Victor Stinneref128102010-10-07 01:00:52 +0000450 /* Checks added to make sure strftime() and asctime() does not crash Python by
451 indexing blindly into some array for a textual representation
452 by some bad index (fixes bug #897625 and #6608).
453
454 Also support values of zero from Python code for arguments in which
455 that is out of range by forcing that value to the lowest value that
456 is valid (fixed bug #1520914).
457
458 Valid ranges based on what is allowed in struct tm:
459
460 - tm_year: [0, max(int)] (1)
461 - tm_mon: [0, 11] (2)
462 - tm_mday: [1, 31]
463 - tm_hour: [0, 23]
464 - tm_min: [0, 59]
465 - tm_sec: [0, 60]
466 - tm_wday: [0, 6] (1)
467 - tm_yday: [0, 365] (2)
468 - tm_isdst: [-max(int), max(int)]
469
470 (1) gettmarg() handles bounds-checking.
471 (2) Python's acceptable range is one greater than the range in C,
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000472 thus need to check against automatic decrement by gettmarg().
473 */
474 if (buf->tm_mon == -1)
475 buf->tm_mon = 0;
476 else if (buf->tm_mon < 0 || buf->tm_mon > 11) {
477 PyErr_SetString(PyExc_ValueError, "month out of range");
478 return 0;
479 }
480 if (buf->tm_mday == 0)
481 buf->tm_mday = 1;
482 else if (buf->tm_mday < 0 || buf->tm_mday > 31) {
483 PyErr_SetString(PyExc_ValueError, "day of month out of range");
484 return 0;
485 }
486 if (buf->tm_hour < 0 || buf->tm_hour > 23) {
487 PyErr_SetString(PyExc_ValueError, "hour out of range");
488 return 0;
489 }
490 if (buf->tm_min < 0 || buf->tm_min > 59) {
491 PyErr_SetString(PyExc_ValueError, "minute out of range");
492 return 0;
493 }
494 if (buf->tm_sec < 0 || buf->tm_sec > 61) {
495 PyErr_SetString(PyExc_ValueError, "seconds out of range");
496 return 0;
497 }
498 /* tm_wday does not need checking of its upper-bound since taking
499 ``% 7`` in gettmarg() automatically restricts the range. */
500 if (buf->tm_wday < 0) {
501 PyErr_SetString(PyExc_ValueError, "day of week out of range");
502 return 0;
503 }
504 if (buf->tm_yday == -1)
505 buf->tm_yday = 0;
506 else if (buf->tm_yday < 0 || buf->tm_yday > 365) {
507 PyErr_SetString(PyExc_ValueError, "day of year out of range");
508 return 0;
509 }
510 return 1;
511}
512
Victor Stinnerc1f32ca2011-10-14 02:36:13 +0200513#ifdef MS_WINDOWS
514 /* wcsftime() doesn't format correctly time zones, see issue #10653 */
515# undef HAVE_WCSFTIME
516#endif
Alexander Belopolskycf774542012-10-02 18:39:16 -0400517#define STRFTIME_FORMAT_CODES \
518"Commonly used format codes:\n\
519\n\
520%Y Year with century as a decimal number.\n\
521%m Month as a decimal number [01,12].\n\
522%d Day of the month as a decimal number [01,31].\n\
523%H Hour (24-hour clock) as a decimal number [00,23].\n\
524%M Minute as a decimal number [00,59].\n\
525%S Second as a decimal number [00,61].\n\
526%z Time zone offset from UTC.\n\
527%a Locale's abbreviated weekday name.\n\
528%A Locale's full weekday name.\n\
529%b Locale's abbreviated month name.\n\
530%B Locale's full month name.\n\
531%c Locale's appropriate date and time representation.\n\
532%I Hour (12-hour clock) as a decimal number [01,12].\n\
533%p Locale's equivalent of either AM or PM.\n\
534\n\
535Other codes may be available on your platform. See documentation for\n\
536the C library strftime function.\n"
Victor Stinnerc1f32ca2011-10-14 02:36:13 +0200537
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000538#ifdef HAVE_STRFTIME
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000539#ifdef HAVE_WCSFTIME
540#define time_char wchar_t
541#define format_time wcsftime
542#define time_strlen wcslen
543#else
544#define time_char char
545#define format_time strftime
546#define time_strlen strlen
547#endif
548
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000549static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000550time_strftime(PyObject *self, PyObject *args)
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000551{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000552 PyObject *tup = NULL;
553 struct tm buf;
554 const time_char *fmt;
Victor Stinnerb2904782010-09-29 10:34:19 +0000555#ifdef HAVE_WCSFTIME
556 wchar_t *format;
557#else
558 PyObject *format;
559#endif
Victor Stinneref128102010-10-07 01:00:52 +0000560 PyObject *format_arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000561 size_t fmtlen, buflen;
Victor Stinnerb2904782010-09-29 10:34:19 +0000562 time_char *outbuf = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000563 size_t i;
Victor Stinnerb2904782010-09-29 10:34:19 +0000564 PyObject *ret = NULL;
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000565
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000566 memset((void *) &buf, '\0', sizeof(buf));
Guido van Rossum1f41f841998-04-27 19:04:26 +0000567
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000568 /* Will always expect a unicode string to be passed as format.
569 Given that there's no str type anymore in py3k this seems safe.
570 */
Victor Stinneref128102010-10-07 01:00:52 +0000571 if (!PyArg_ParseTuple(args, "U|O:strftime", &format_arg, &tup))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000572 return NULL;
Thomas Woutersfe385252001-01-19 23:16:56 +0000573
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000574 if (tup == NULL) {
575 time_t tt = time(NULL);
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100576 if (pylocaltime(&tt, &buf) == -1)
577 return NULL;
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000578 }
579 else if (!gettmarg(tup, &buf) || !checktm(&buf))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000580 return NULL;
Guido van Rossum10b164a2001-09-25 13:59:01 +0000581
Victor Stinner36b82d82013-06-25 02:33:53 +0200582#if defined(_MSC_VER) || defined(sun) || defined(_AIX)
Victor Stinner73ea29c2011-01-08 01:56:31 +0000583 if (buf.tm_year + 1900 < 1 || 9999 < buf.tm_year + 1900) {
Victor Stinner6f0e4f92011-03-21 02:14:53 +0100584 PyErr_SetString(PyExc_ValueError,
585 "strftime() requires year in [1; 9999]");
Alexander Belopolsky0dd06f42011-01-08 01:23:02 +0000586 return NULL;
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000587 }
Victor Stinner73ea29c2011-01-08 01:56:31 +0000588#endif
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000589
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000590 /* Normalize tm_isdst just in case someone foolishly implements %Z
591 based on the assumption that tm_isdst falls within the range of
592 [-1, 1] */
593 if (buf.tm_isdst < -1)
594 buf.tm_isdst = -1;
595 else if (buf.tm_isdst > 1)
596 buf.tm_isdst = 1;
Brett Cannond1080a32004-03-02 04:38:10 +0000597
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000598#ifdef HAVE_WCSFTIME
Victor Stinnerbeb4135b2010-10-07 01:02:42 +0000599 format = PyUnicode_AsWideCharString(format_arg, NULL);
Victor Stinnerb2904782010-09-29 10:34:19 +0000600 if (format == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000601 return NULL;
Victor Stinnerb2904782010-09-29 10:34:19 +0000602 fmt = format;
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000603#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000604 /* Convert the unicode string to an ascii one */
Victor Stinner1b579672011-12-17 05:47:23 +0100605 format = PyUnicode_EncodeLocale(format_arg, "surrogateescape");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000606 if (format == NULL)
607 return NULL;
608 fmt = PyBytes_AS_STRING(format);
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000609#endif
Amaury Forgeot d'Arcb5be6d42009-03-02 23:52:57 +0000610
Stefan Krah4aea7d32012-02-27 16:30:26 +0100611#if defined(MS_WINDOWS) && !defined(HAVE_WCSFTIME)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000612 /* check that the format string contains only valid directives */
Steve Dowere5b58952015-09-06 19:20:51 -0700613 for (outbuf = strchr(fmt, '%');
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000614 outbuf != NULL;
Victor Stinner5a3ff792011-10-16 19:08:23 +0200615 outbuf = strchr(outbuf+2, '%'))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000616 {
Steve Dowere5b58952015-09-06 19:20:51 -0700617 if (outbuf[1] == '#')
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000618 ++outbuf; /* not documented by python, */
Steve Dowere5b58952015-09-06 19:20:51 -0700619 if (outbuf[1] == '\0')
620 break;
621 if ((outbuf[1] == 'y') && buf.tm_year < 0) {
Tim Golden6e51b8f2013-11-12 12:36:54 +0000622 PyErr_SetString(PyExc_ValueError,
623 "format %y requires year >= 1900 on Windows");
624 Py_DECREF(format);
625 return NULL;
626 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000627 }
Victor Stinner93965f72013-11-23 14:59:33 +0100628#elif (defined(_AIX) || defined(sun)) && defined(HAVE_WCSFTIME)
Steve Dowere5b58952015-09-06 19:20:51 -0700629 for (outbuf = wcschr(fmt, '%');
Victor Stinner55329f82013-11-17 23:39:21 +0100630 outbuf != NULL;
631 outbuf = wcschr(outbuf+2, '%'))
632 {
Steve Dowere5b58952015-09-06 19:20:51 -0700633 if (outbuf[1] == L'\0')
634 break;
Victor Stinner55329f82013-11-17 23:39:21 +0100635 /* Issue #19634: On AIX, wcsftime("y", (1899, 1, 1, 0, 0, 0, 0, 0, 0))
636 returns "0/" instead of "99" */
637 if (outbuf[1] == L'y' && buf.tm_year < 0) {
638 PyErr_SetString(PyExc_ValueError,
639 "format %y requires year >= 1900 on AIX");
Victor Stinner55329f82013-11-17 23:39:21 +0100640 return NULL;
641 }
642 }
Amaury Forgeot d'Arcb5be6d42009-03-02 23:52:57 +0000643#endif
644
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000645 fmtlen = time_strlen(fmt);
Guido van Rossumc222ec21999-02-23 00:00:10 +0000646
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000647 /* I hate these functions that presume you know how big the output
648 * will be ahead of time...
649 */
650 for (i = 1024; ; i += i) {
Victor Stinner136ea492011-12-17 22:37:18 +0100651#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100652 int err;
Victor Stinner136ea492011-12-17 22:37:18 +0100653#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000654 outbuf = (time_char *)PyMem_Malloc(i*sizeof(time_char));
655 if (outbuf == NULL) {
Victor Stinnerb2904782010-09-29 10:34:19 +0000656 PyErr_NoMemory();
657 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000658 }
Steve Dowerd9ef74e2015-05-22 15:08:34 -0700659 _Py_BEGIN_SUPPRESS_IPH
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000660 buflen = format_time(outbuf, i, fmt, &buf);
Steve Dowerd9ef74e2015-05-22 15:08:34 -0700661 _Py_END_SUPPRESS_IPH
Victor Stinner136ea492011-12-17 22:37:18 +0100662#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100663 err = errno;
Victor Stinner136ea492011-12-17 22:37:18 +0100664#endif
Steve Dowere5b58952015-09-06 19:20:51 -0700665 if (buflen > 0 || fmtlen == 0 ||
666 (fmtlen > 4 && i >= 256 * fmtlen)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000667 /* If the buffer is 256 times as long as the format,
668 it's probably not failing for lack of room!
669 More likely, the format yields an empty result,
670 e.g. an empty format, or %Z when the timezone
671 is unknown. */
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000672#ifdef HAVE_WCSFTIME
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000673 ret = PyUnicode_FromWideChar(outbuf, buflen);
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000674#else
Victor Stinner1b579672011-12-17 05:47:23 +0100675 ret = PyUnicode_DecodeLocaleAndSize(outbuf, buflen,
676 "surrogateescape");
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000677#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000678 PyMem_Free(outbuf);
Victor Stinnerb2904782010-09-29 10:34:19 +0000679 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000680 }
681 PyMem_Free(outbuf);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000682#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000683 /* VisualStudio .NET 2005 does this properly */
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100684 if (buflen == 0 && err == EINVAL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000685 PyErr_SetString(PyExc_ValueError, "Invalid format string");
Victor Stinnerb2904782010-09-29 10:34:19 +0000686 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000687 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000688#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000689 }
Victor Stinnerb2904782010-09-29 10:34:19 +0000690#ifdef HAVE_WCSFTIME
691 PyMem_Free(format);
692#else
693 Py_DECREF(format);
694#endif
695 return ret;
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000696}
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000697
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000698#undef time_char
699#undef format_time
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000700PyDoc_STRVAR(strftime_doc,
Thomas Woutersfe385252001-01-19 23:16:56 +0000701"strftime(format[, tuple]) -> string\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000702\n\
703Convert a time tuple to a string according to a format specification.\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000704See the library reference manual for formatting codes. When the time tuple\n\
Alexander Belopolskycf774542012-10-02 18:39:16 -0400705is not present, current time as returned by localtime() is used.\n\
706\n" STRFTIME_FORMAT_CODES);
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000707#endif /* HAVE_STRFTIME */
708
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000709static PyObject *
710time_strptime(PyObject *self, PyObject *args)
711{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000712 PyObject *strptime_module = PyImport_ImportModuleNoBlock("_strptime");
713 PyObject *strptime_result;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200714 _Py_IDENTIFIER(_strptime_time);
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000715
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000716 if (!strptime_module)
717 return NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200718 strptime_result = _PyObject_CallMethodId(strptime_module,
719 &PyId__strptime_time, "O", args);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000720 Py_DECREF(strptime_module);
721 return strptime_result;
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000722}
723
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000724
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000725PyDoc_STRVAR(strptime_doc,
Brett Cannon20def8b2003-07-01 05:16:08 +0000726"strptime(string, format) -> struct_time\n\
Martin v. Löwisb3cfc1d2001-12-02 12:27:43 +0000727\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000728Parse a string to a time tuple according to a format specification.\n\
Alexander Belopolskycf774542012-10-02 18:39:16 -0400729See the library reference manual for formatting codes (same as\n\
730strftime()).\n\
731\n" STRFTIME_FORMAT_CODES);
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000732
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000733static PyObject *
734_asctime(struct tm *timeptr)
735{
736 /* Inspired by Open Group reference implementation available at
737 * http://pubs.opengroup.org/onlinepubs/009695399/functions/asctime.html */
Victor Stinner499dfcf2011-03-21 13:26:24 +0100738 static char wday_name[7][4] = {
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000739 "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
740 };
Victor Stinner499dfcf2011-03-21 13:26:24 +0100741 static char mon_name[12][4] = {
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000742 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
743 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
744 };
Victor Stinner499dfcf2011-03-21 13:26:24 +0100745 return PyUnicode_FromFormat(
746 "%s %s%3d %.2d:%.2d:%.2d %d",
747 wday_name[timeptr->tm_wday],
748 mon_name[timeptr->tm_mon],
749 timeptr->tm_mday, timeptr->tm_hour,
750 timeptr->tm_min, timeptr->tm_sec,
751 1900 + timeptr->tm_year);
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000752}
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000753
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000754static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000755time_asctime(PyObject *self, PyObject *args)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000756{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000757 PyObject *tup = NULL;
758 struct tm buf;
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000759
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000760 if (!PyArg_UnpackTuple(args, "asctime", 0, 1, &tup))
761 return NULL;
762 if (tup == NULL) {
763 time_t tt = time(NULL);
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100764 if (pylocaltime(&tt, &buf) == -1)
765 return NULL;
766
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000767 } else if (!gettmarg(tup, &buf) || !checktm(&buf))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000768 return NULL;
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000769 return _asctime(&buf);
Guido van Rossum9e90a671993-06-24 11:10:19 +0000770}
771
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000772PyDoc_STRVAR(asctime_doc,
Thomas Woutersfe385252001-01-19 23:16:56 +0000773"asctime([tuple]) -> string\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000774\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000775Convert a time tuple to a string, e.g. 'Sat Jun 06 16:26:11 1998'.\n\
776When the time tuple is not present, current time as returned by localtime()\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000777is used.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000778
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000779static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000780time_ctime(PyObject *self, PyObject *args)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000781{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000782 time_t tt;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100783 struct tm buf;
784 if (!parse_time_t_args(args, "|O:ctime", &tt))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000785 return NULL;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100786 if (pylocaltime(&tt, &buf) == -1)
Alexander Belopolsky5da468f2011-01-04 17:15:52 +0000787 return NULL;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100788 return _asctime(&buf);
Guido van Rossum9e90a671993-06-24 11:10:19 +0000789}
790
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000791PyDoc_STRVAR(ctime_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000792"ctime(seconds) -> string\n\
793\n\
794Convert a time in seconds since the Epoch to a string in local time.\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000795This is equivalent to asctime(localtime(seconds)). When the time tuple is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000796not present, current time as returned by localtime() is used.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000797
Guido van Rossum60cd8131998-03-06 17:16:21 +0000798#ifdef HAVE_MKTIME
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000799static PyObject *
Victor Stinner4195b5c2012-02-08 23:03:19 +0100800time_mktime(PyObject *self, PyObject *tup)
Guido van Rossum234f9421993-06-17 12:35:49 +0000801{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000802 struct tm buf;
803 time_t tt;
804 if (!gettmarg(tup, &buf))
805 return NULL;
Victor Stinner1ac42612014-02-21 09:27:17 +0100806#ifdef _AIX
807 /* year < 1902 or year > 2037 */
808 if (buf.tm_year < 2 || buf.tm_year > 137) {
809 /* Issue #19748: On AIX, mktime() doesn't report overflow error for
810 * timestamp < -2^31 or timestamp > 2**31-1. */
811 PyErr_SetString(PyExc_OverflowError,
812 "mktime argument out of range");
813 return NULL;
814 }
815#else
Alexander Belopolskyb7d40d12011-01-11 01:21:25 +0000816 buf.tm_wday = -1; /* sentinel; original value ignored */
Victor Stinner1ac42612014-02-21 09:27:17 +0100817#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000818 tt = mktime(&buf);
Alexander Belopolskyb7d40d12011-01-11 01:21:25 +0000819 /* Return value of -1 does not necessarily mean an error, but tm_wday
Ezio Melotti13925002011-03-16 11:05:33 +0200820 * cannot remain set to -1 if mktime succeeded. */
Victor Stinner93037492013-06-25 22:54:35 +0200821 if (tt == (time_t)(-1)
822#ifndef _AIX
823 /* Return value of -1 does not necessarily mean an error, but
824 * tm_wday cannot remain set to -1 if mktime succeeded. */
825 && buf.tm_wday == -1
826#else
827 /* on AIX, tm_wday is always sets, even on error */
828#endif
829 )
830 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000831 PyErr_SetString(PyExc_OverflowError,
832 "mktime argument out of range");
833 return NULL;
834 }
Victor Stinner4195b5c2012-02-08 23:03:19 +0100835 return PyFloat_FromDouble((double)tt);
Guido van Rossum234f9421993-06-17 12:35:49 +0000836}
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000837
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000838PyDoc_STRVAR(mktime_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000839"mktime(tuple) -> floating point number\n\
840\n\
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400841Convert a time tuple in local time to seconds since the Epoch.\n\
842Note that mktime(gmtime(0)) will not generally return zero for most\n\
843time zones; instead the returned value will either be equal to that\n\
844of the timezone or altzone attributes on the time module.");
Guido van Rossum60cd8131998-03-06 17:16:21 +0000845#endif /* HAVE_MKTIME */
Guido van Rossum234f9421993-06-17 12:35:49 +0000846
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000847#ifdef HAVE_WORKING_TZSET
Martin v. Löwis1a214512008-06-11 05:26:20 +0000848static void PyInit_timezone(PyObject *module);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000849
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000850static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000851time_tzset(PyObject *self, PyObject *unused)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000852{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000853 PyObject* m;
Fred Drake9bb74322002-04-01 14:49:59 +0000854
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000855 m = PyImport_ImportModuleNoBlock("time");
856 if (m == NULL) {
857 return NULL;
858 }
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000859
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000860 tzset();
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000861
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000862 /* Reset timezone, altzone, daylight and tzname */
863 PyInit_timezone(m);
864 Py_DECREF(m);
Victor Stinner2ff51b82013-07-17 21:42:45 +0200865 if (PyErr_Occurred())
866 return NULL;
Tim Peters1b6f7a92004-06-20 02:50:16 +0000867
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000868 Py_INCREF(Py_None);
869 return Py_None;
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000870}
871
872PyDoc_STRVAR(tzset_doc,
R. David Murray4d55bf92010-12-14 00:55:46 +0000873"tzset()\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000874\n\
875Initialize, or reinitialize, the local timezone to the value stored in\n\
876os.environ['TZ']. The TZ environment variable should be specified in\n\
Neal Norwitzdc8e1942004-07-20 22:34:37 +0000877standard Unix timezone format as documented in the tzset man page\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000878(eg. 'US/Eastern', 'Europe/Amsterdam'). Unknown timezones will silently\n\
879fall back to UTC. If the TZ environment variable is not set, the local\n\
880timezone is set to the systems best guess of wallclock time.\n\
881Changing the TZ environment variable without calling tzset *may* change\n\
882the local timezone used by methods such as localtime, but this behaviour\n\
883should not be relied on.");
884#endif /* HAVE_WORKING_TZSET */
885
Victor Stinnerae586492014-09-02 23:18:25 +0200886static PyObject *
Victor Stinnerec895392012-04-29 02:41:27 +0200887pymonotonic(_Py_clock_info_t *info)
Victor Stinnerb94b2662012-01-18 01:50:21 +0100888{
Victor Stinner4bfb4602015-03-27 22:27:24 +0100889 _PyTime_t t;
890 double d;
891 if (_PyTime_GetMonotonicClockWithInfo(&t, info) < 0) {
Victor Stinnerae586492014-09-02 23:18:25 +0200892 assert(info != NULL);
Victor Stinner071eca32012-03-15 01:17:09 +0100893 return NULL;
894 }
Victor Stinner4bfb4602015-03-27 22:27:24 +0100895 d = _PyTime_AsSecondsDouble(t);
896 return PyFloat_FromDouble(d);
Victor Stinner8b302012012-02-07 23:29:46 +0100897}
898
Victor Stinner071eca32012-03-15 01:17:09 +0100899static PyObject *
Victor Stinnerec895392012-04-29 02:41:27 +0200900time_monotonic(PyObject *self, PyObject *unused)
Victor Stinner071eca32012-03-15 01:17:09 +0100901{
Victor Stinnerec895392012-04-29 02:41:27 +0200902 return pymonotonic(NULL);
Victor Stinner071eca32012-03-15 01:17:09 +0100903}
904
Victor Stinnerec895392012-04-29 02:41:27 +0200905PyDoc_STRVAR(monotonic_doc,
906"monotonic() -> float\n\
Victor Stinner8b302012012-02-07 23:29:46 +0100907\n\
Victor Stinnerec895392012-04-29 02:41:27 +0200908Monotonic clock, cannot go backward.");
Victor Stinnerec919cc2012-03-15 00:58:32 +0100909
Victor Stinnerec895392012-04-29 02:41:27 +0200910static PyObject*
911perf_counter(_Py_clock_info_t *info)
912{
Victor Stinner54884492014-08-29 16:51:33 +0200913#ifdef WIN32_PERF_COUNTER
914 return win_perf_counter(info);
915#else
Victor Stinnerae586492014-09-02 23:18:25 +0200916 return pymonotonic(info);
Victor Stinner54884492014-08-29 16:51:33 +0200917#endif
Victor Stinnerec895392012-04-29 02:41:27 +0200918}
919
920static PyObject *
921time_perf_counter(PyObject *self, PyObject *unused)
922{
923 return perf_counter(NULL);
924}
925
926PyDoc_STRVAR(perf_counter_doc,
927"perf_counter() -> float\n\
928\n\
929Performance counter for benchmarking.");
930
931static PyObject*
932py_process_time(_Py_clock_info_t *info)
933{
934#if defined(MS_WINDOWS)
935 HANDLE process;
936 FILETIME creation_time, exit_time, kernel_time, user_time;
937 ULARGE_INTEGER large;
938 double total;
939 BOOL ok;
940
941 process = GetCurrentProcess();
942 ok = GetProcessTimes(process, &creation_time, &exit_time, &kernel_time, &user_time);
943 if (!ok)
944 return PyErr_SetFromWindowsErr(0);
945
946 large.u.LowPart = kernel_time.dwLowDateTime;
947 large.u.HighPart = kernel_time.dwHighDateTime;
948 total = (double)large.QuadPart;
949 large.u.LowPart = user_time.dwLowDateTime;
950 large.u.HighPart = user_time.dwHighDateTime;
951 total += (double)large.QuadPart;
952 if (info) {
953 info->implementation = "GetProcessTimes()";
954 info->resolution = 1e-7;
Benjamin Peterson49a69e42012-05-01 09:38:34 -0400955 info->monotonic = 1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +0200956 info->adjustable = 0;
Victor Stinnerec895392012-04-29 02:41:27 +0200957 }
958 return PyFloat_FromDouble(total * 1e-7);
959#else
960
961#if defined(HAVE_SYS_RESOURCE_H)
962 struct rusage ru;
963#endif
964#ifdef HAVE_TIMES
965 struct tms t;
966 static long ticks_per_second = -1;
967#endif
968
969#if defined(HAVE_CLOCK_GETTIME) \
970 && (defined(CLOCK_PROCESS_CPUTIME_ID) || defined(CLOCK_PROF))
971 struct timespec tp;
972#ifdef CLOCK_PROF
973 const clockid_t clk_id = CLOCK_PROF;
974 const char *function = "clock_gettime(CLOCK_PROF)";
975#else
976 const clockid_t clk_id = CLOCK_PROCESS_CPUTIME_ID;
977 const char *function = "clock_gettime(CLOCK_PROCESS_CPUTIME_ID)";
978#endif
979
980 if (clock_gettime(clk_id, &tp) == 0) {
981 if (info) {
982 struct timespec res;
983 info->implementation = function;
Benjamin Peterson49a69e42012-05-01 09:38:34 -0400984 info->monotonic = 1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +0200985 info->adjustable = 0;
Victor Stinnerec895392012-04-29 02:41:27 +0200986 if (clock_getres(clk_id, &res) == 0)
987 info->resolution = res.tv_sec + res.tv_nsec * 1e-9;
988 else
989 info->resolution = 1e-9;
990 }
991 return PyFloat_FromDouble(tp.tv_sec + tp.tv_nsec * 1e-9);
992 }
993#endif
994
995#if defined(HAVE_SYS_RESOURCE_H)
996 if (getrusage(RUSAGE_SELF, &ru) == 0) {
997 double total;
998 total = ru.ru_utime.tv_sec + ru.ru_utime.tv_usec * 1e-6;
999 total += ru.ru_stime.tv_sec + ru.ru_stime.tv_usec * 1e-6;
1000 if (info) {
1001 info->implementation = "getrusage(RUSAGE_SELF)";
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001002 info->monotonic = 1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001003 info->adjustable = 0;
Victor Stinnerec895392012-04-29 02:41:27 +02001004 info->resolution = 1e-6;
1005 }
1006 return PyFloat_FromDouble(total);
1007 }
1008#endif
1009
1010#ifdef HAVE_TIMES
1011 if (times(&t) != (clock_t)-1) {
1012 double total;
1013
1014 if (ticks_per_second == -1) {
1015#if defined(HAVE_SYSCONF) && defined(_SC_CLK_TCK)
1016 ticks_per_second = sysconf(_SC_CLK_TCK);
1017 if (ticks_per_second < 1)
1018 ticks_per_second = -1;
1019#elif defined(HZ)
1020 ticks_per_second = HZ;
1021#else
1022 ticks_per_second = 60; /* magic fallback value; may be bogus */
1023#endif
1024 }
1025
1026 if (ticks_per_second != -1) {
1027 total = (double)t.tms_utime / ticks_per_second;
1028 total += (double)t.tms_stime / ticks_per_second;
1029 if (info) {
1030 info->implementation = "times()";
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001031 info->monotonic = 1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001032 info->adjustable = 0;
Victor Stinnerec895392012-04-29 02:41:27 +02001033 info->resolution = 1.0 / ticks_per_second;
1034 }
1035 return PyFloat_FromDouble(total);
1036 }
1037 }
1038#endif
1039
1040 return floatclock(info);
1041#endif
1042}
1043
1044static PyObject *
1045time_process_time(PyObject *self, PyObject *unused)
1046{
1047 return py_process_time(NULL);
1048}
1049
1050PyDoc_STRVAR(process_time_doc,
1051"process_time() -> float\n\
1052\n\
1053Process time for profiling: sum of the kernel and user-space CPU time.");
1054
1055
Victor Stinnerec895392012-04-29 02:41:27 +02001056static PyObject *
1057time_get_clock_info(PyObject *self, PyObject *args)
1058{
1059 char *name;
Victor Stinnerec895392012-04-29 02:41:27 +02001060 _Py_clock_info_t info;
Victor Stinnerbda4b882012-06-12 22:11:44 +02001061 PyObject *obj = NULL, *dict, *ns;
Victor Stinnerec895392012-04-29 02:41:27 +02001062
1063 if (!PyArg_ParseTuple(args, "s:get_clock_info", &name))
1064 return NULL;
1065
1066#ifdef Py_DEBUG
1067 info.implementation = NULL;
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001068 info.monotonic = -1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001069 info.adjustable = -1;
Victor Stinnerec895392012-04-29 02:41:27 +02001070 info.resolution = -1.0;
1071#else
1072 info.implementation = "";
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001073 info.monotonic = 0;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001074 info.adjustable = 0;
Victor Stinnerec895392012-04-29 02:41:27 +02001075 info.resolution = 1.0;
1076#endif
1077
1078 if (strcmp(name, "time") == 0)
1079 obj = floattime(&info);
1080#ifdef PYCLOCK
1081 else if (strcmp(name, "clock") == 0)
1082 obj = pyclock(&info);
1083#endif
Victor Stinnerec895392012-04-29 02:41:27 +02001084 else if (strcmp(name, "monotonic") == 0)
1085 obj = pymonotonic(&info);
Victor Stinnerec895392012-04-29 02:41:27 +02001086 else if (strcmp(name, "perf_counter") == 0)
1087 obj = perf_counter(&info);
1088 else if (strcmp(name, "process_time") == 0)
1089 obj = py_process_time(&info);
1090 else {
1091 PyErr_SetString(PyExc_ValueError, "unknown clock");
1092 return NULL;
1093 }
1094 if (obj == NULL)
1095 return NULL;
1096 Py_DECREF(obj);
1097
Victor Stinnerbda4b882012-06-12 22:11:44 +02001098 dict = PyDict_New();
1099 if (dict == NULL)
Victor Stinnerec895392012-04-29 02:41:27 +02001100 return NULL;
1101
1102 assert(info.implementation != NULL);
1103 obj = PyUnicode_FromString(info.implementation);
1104 if (obj == NULL)
1105 goto error;
Victor Stinnerbda4b882012-06-12 22:11:44 +02001106 if (PyDict_SetItemString(dict, "implementation", obj) == -1)
1107 goto error;
1108 Py_CLEAR(obj);
Victor Stinnerec895392012-04-29 02:41:27 +02001109
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001110 assert(info.monotonic != -1);
1111 obj = PyBool_FromLong(info.monotonic);
Victor Stinnerec895392012-04-29 02:41:27 +02001112 if (obj == NULL)
1113 goto error;
Victor Stinnerbda4b882012-06-12 22:11:44 +02001114 if (PyDict_SetItemString(dict, "monotonic", obj) == -1)
1115 goto error;
1116 Py_CLEAR(obj);
Victor Stinnerec895392012-04-29 02:41:27 +02001117
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001118 assert(info.adjustable != -1);
1119 obj = PyBool_FromLong(info.adjustable);
Victor Stinnerec895392012-04-29 02:41:27 +02001120 if (obj == NULL)
1121 goto error;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001122 if (PyDict_SetItemString(dict, "adjustable", obj) == -1)
Victor Stinnerbda4b882012-06-12 22:11:44 +02001123 goto error;
1124 Py_CLEAR(obj);
Victor Stinnerec895392012-04-29 02:41:27 +02001125
1126 assert(info.resolution > 0.0);
1127 assert(info.resolution <= 1.0);
1128 obj = PyFloat_FromDouble(info.resolution);
1129 if (obj == NULL)
1130 goto error;
Victor Stinnerbda4b882012-06-12 22:11:44 +02001131 if (PyDict_SetItemString(dict, "resolution", obj) == -1)
1132 goto error;
1133 Py_CLEAR(obj);
Victor Stinnerec895392012-04-29 02:41:27 +02001134
Victor Stinnerbda4b882012-06-12 22:11:44 +02001135 ns = _PyNamespace_New(dict);
1136 Py_DECREF(dict);
1137 return ns;
Victor Stinnerec895392012-04-29 02:41:27 +02001138
1139error:
Victor Stinnerbda4b882012-06-12 22:11:44 +02001140 Py_DECREF(dict);
1141 Py_XDECREF(obj);
Victor Stinnerec895392012-04-29 02:41:27 +02001142 return NULL;
1143}
1144
1145PyDoc_STRVAR(get_clock_info_doc,
1146"get_clock_info(name: str) -> dict\n\
1147\n\
1148Get information of the specified clock.");
Victor Stinner8b302012012-02-07 23:29:46 +01001149
Martin v. Löwisd218dc12008-04-07 03:17:54 +00001150static void
Martin v. Löwis1a214512008-06-11 05:26:20 +00001151PyInit_timezone(PyObject *m) {
1152 /* This code moved from PyInit_time wholesale to allow calling it from
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001153 time_tzset. In the future, some parts of it can be moved back
1154 (for platforms that don't HAVE_WORKING_TZSET, when we know what they
1155 are), and the extraneous calls to tzset(3) should be removed.
1156 I haven't done this yet, as I don't want to change this code as
1157 little as possible when introducing the time.tzset and time.tzsetwall
1158 methods. This should simply be a method of doing the following once,
1159 at the top of this function and removing the call to tzset() from
1160 time_tzset():
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001161
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001162 #ifdef HAVE_TZSET
1163 tzset()
1164 #endif
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001165
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001166 And I'm lazy and hate C so nyer.
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001167 */
Guido van Rossum10b164a2001-09-25 13:59:01 +00001168#if defined(HAVE_TZNAME) && !defined(__GLIBC__) && !defined(__CYGWIN__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001169 PyObject *otz0, *otz1;
1170 tzset();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001171 PyModule_AddIntConstant(m, "timezone", timezone);
Guido van Rossumb6775db1994-08-01 11:34:53 +00001172#ifdef HAVE_ALTZONE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001173 PyModule_AddIntConstant(m, "altzone", altzone);
Guido van Rossumb6775db1994-08-01 11:34:53 +00001174#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001175 PyModule_AddIntConstant(m, "altzone", timezone-3600);
Guido van Rossumb6775db1994-08-01 11:34:53 +00001176#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001177 PyModule_AddIntConstant(m, "daylight", daylight);
Victor Stinner1b579672011-12-17 05:47:23 +01001178 otz0 = PyUnicode_DecodeLocale(tzname[0], "surrogateescape");
1179 otz1 = PyUnicode_DecodeLocale(tzname[1], "surrogateescape");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001180 PyModule_AddObject(m, "tzname", Py_BuildValue("(NN)", otz0, otz1));
Guido van Rossum10b164a2001-09-25 13:59:01 +00001181#else /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/
Martin v. Löwis60a5d722002-10-16 20:28:25 +00001182#ifdef HAVE_STRUCT_TM_TM_ZONE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001183 {
Guido van Rossum234f9421993-06-17 12:35:49 +00001184#define YEAR ((time_t)((365 * 24 + 6) * 3600))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001185 time_t t;
1186 struct tm *p;
1187 long janzone, julyzone;
1188 char janname[10], julyname[10];
1189 t = (time((time_t *)0) / YEAR) * YEAR;
1190 p = localtime(&t);
1191 janzone = -p->tm_gmtoff;
1192 strncpy(janname, p->tm_zone ? p->tm_zone : " ", 9);
1193 janname[9] = '\0';
1194 t += YEAR/2;
1195 p = localtime(&t);
1196 julyzone = -p->tm_gmtoff;
1197 strncpy(julyname, p->tm_zone ? p->tm_zone : " ", 9);
1198 julyname[9] = '\0';
Guido van Rossum10b164a2001-09-25 13:59:01 +00001199
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001200 if( janzone < julyzone ) {
1201 /* DST is reversed in the southern hemisphere */
1202 PyModule_AddIntConstant(m, "timezone", julyzone);
1203 PyModule_AddIntConstant(m, "altzone", janzone);
1204 PyModule_AddIntConstant(m, "daylight",
1205 janzone != julyzone);
1206 PyModule_AddObject(m, "tzname",
1207 Py_BuildValue("(zz)",
1208 julyname, janname));
1209 } else {
1210 PyModule_AddIntConstant(m, "timezone", janzone);
1211 PyModule_AddIntConstant(m, "altzone", julyzone);
1212 PyModule_AddIntConstant(m, "daylight",
1213 janzone != julyzone);
1214 PyModule_AddObject(m, "tzname",
1215 Py_BuildValue("(zz)",
1216 janname, julyname));
1217 }
1218 }
Guido van Rossume6a4b7b1997-10-08 15:27:56 +00001219#else
Martin v. Löwis60a5d722002-10-16 20:28:25 +00001220#endif /* HAVE_STRUCT_TM_TM_ZONE */
Tim Peters26ae7cd2001-03-20 03:26:49 +00001221#ifdef __CYGWIN__
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001222 tzset();
1223 PyModule_AddIntConstant(m, "timezone", _timezone);
1224 PyModule_AddIntConstant(m, "altzone", _timezone-3600);
1225 PyModule_AddIntConstant(m, "daylight", _daylight);
1226 PyModule_AddObject(m, "tzname",
1227 Py_BuildValue("(zz)", _tzname[0], _tzname[1]));
Tim Peters26ae7cd2001-03-20 03:26:49 +00001228#endif /* __CYGWIN__ */
Guido van Rossum10b164a2001-09-25 13:59:01 +00001229#endif /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/
Victor Stinnere0be4232011-10-25 13:06:09 +02001230
Victor Stinnerec895392012-04-29 02:41:27 +02001231#if defined(HAVE_CLOCK_GETTIME)
Victor Stinnere0be4232011-10-25 13:06:09 +02001232 PyModule_AddIntMacro(m, CLOCK_REALTIME);
Victor Stinnere0be4232011-10-25 13:06:09 +02001233#ifdef CLOCK_MONOTONIC
1234 PyModule_AddIntMacro(m, CLOCK_MONOTONIC);
1235#endif
1236#ifdef CLOCK_MONOTONIC_RAW
1237 PyModule_AddIntMacro(m, CLOCK_MONOTONIC_RAW);
1238#endif
Victor Stinner1470f352012-04-03 00:31:17 +02001239#ifdef CLOCK_HIGHRES
1240 PyModule_AddIntMacro(m, CLOCK_HIGHRES);
1241#endif
Victor Stinnere0be4232011-10-25 13:06:09 +02001242#ifdef CLOCK_PROCESS_CPUTIME_ID
1243 PyModule_AddIntMacro(m, CLOCK_PROCESS_CPUTIME_ID);
1244#endif
1245#ifdef CLOCK_THREAD_CPUTIME_ID
1246 PyModule_AddIntMacro(m, CLOCK_THREAD_CPUTIME_ID);
1247#endif
1248#endif /* HAVE_CLOCK_GETTIME */
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001249}
1250
1251
1252static PyMethodDef time_methods[] = {
Victor Stinner4195b5c2012-02-08 23:03:19 +01001253 {"time", time_time, METH_NOARGS, time_doc},
Victor Stinnerec895392012-04-29 02:41:27 +02001254#ifdef PYCLOCK
Victor Stinner4195b5c2012-02-08 23:03:19 +01001255 {"clock", time_clock, METH_NOARGS, clock_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001256#endif
Victor Stinnere0be4232011-10-25 13:06:09 +02001257#ifdef HAVE_CLOCK_GETTIME
Victor Stinner4195b5c2012-02-08 23:03:19 +01001258 {"clock_gettime", time_clock_gettime, METH_VARARGS, clock_gettime_doc},
Victor Stinner30d79472012-04-03 00:45:07 +02001259 {"clock_settime", time_clock_settime, METH_VARARGS, clock_settime_doc},
Victor Stinner4195b5c2012-02-08 23:03:19 +01001260 {"clock_getres", time_clock_getres, METH_VARARGS, clock_getres_doc},
Victor Stinnere0be4232011-10-25 13:06:09 +02001261#endif
Victor Stinnercb29f012015-03-27 13:31:18 +01001262 {"sleep", time_sleep, METH_O, sleep_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001263 {"gmtime", time_gmtime, METH_VARARGS, gmtime_doc},
1264 {"localtime", time_localtime, METH_VARARGS, localtime_doc},
1265 {"asctime", time_asctime, METH_VARARGS, asctime_doc},
1266 {"ctime", time_ctime, METH_VARARGS, ctime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001267#ifdef HAVE_MKTIME
Victor Stinner4195b5c2012-02-08 23:03:19 +01001268 {"mktime", time_mktime, METH_O, mktime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001269#endif
1270#ifdef HAVE_STRFTIME
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001271 {"strftime", time_strftime, METH_VARARGS, strftime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001272#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001273 {"strptime", time_strptime, METH_VARARGS, strptime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001274#ifdef HAVE_WORKING_TZSET
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001275 {"tzset", time_tzset, METH_NOARGS, tzset_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001276#endif
Victor Stinnerec895392012-04-29 02:41:27 +02001277 {"monotonic", time_monotonic, METH_NOARGS, monotonic_doc},
Victor Stinnerec895392012-04-29 02:41:27 +02001278 {"process_time", time_process_time, METH_NOARGS, process_time_doc},
1279 {"perf_counter", time_perf_counter, METH_NOARGS, perf_counter_doc},
1280 {"get_clock_info", time_get_clock_info, METH_VARARGS, get_clock_info_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001281 {NULL, NULL} /* sentinel */
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001282};
1283
1284
1285PyDoc_STRVAR(module_doc,
1286"This module provides various functions to manipulate time values.\n\
1287\n\
1288There are two standard representations of time. One is the number\n\
1289of seconds since the Epoch, in UTC (a.k.a. GMT). It may be an integer\n\
1290or a floating point number (to represent fractions of seconds).\n\
1291The Epoch is system-defined; on Unix, it is generally January 1st, 1970.\n\
1292The actual value can be retrieved by calling gmtime(0).\n\
1293\n\
1294The other representation is a tuple of 9 integers giving local time.\n\
1295The tuple items are:\n\
Alexander Belopolsky03163ac2011-05-02 12:20:52 -04001296 year (including century, e.g. 1998)\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001297 month (1-12)\n\
1298 day (1-31)\n\
1299 hours (0-23)\n\
1300 minutes (0-59)\n\
1301 seconds (0-59)\n\
1302 weekday (0-6, Monday is 0)\n\
1303 Julian day (day in the year, 1-366)\n\
1304 DST (Daylight Savings Time) flag (-1, 0 or 1)\n\
1305If the DST flag is 0, the time is given in the regular time zone;\n\
1306if it is 1, the time is given in the DST time zone;\n\
1307if it is -1, mktime() should guess based on the date and time.\n\
1308\n\
1309Variables:\n\
1310\n\
1311timezone -- difference in seconds between UTC and local standard time\n\
1312altzone -- difference in seconds between UTC and local DST time\n\
1313daylight -- whether local time should reflect DST\n\
1314tzname -- tuple of (standard time zone name, DST time zone name)\n\
1315\n\
1316Functions:\n\
1317\n\
1318time() -- return current time in seconds since the Epoch as a float\n\
1319clock() -- return CPU time since process start as a float\n\
1320sleep() -- delay for a number of seconds given as a float\n\
1321gmtime() -- convert seconds since Epoch to UTC tuple\n\
1322localtime() -- convert seconds since Epoch to local time tuple\n\
1323asctime() -- convert time tuple to string\n\
1324ctime() -- convert time in seconds to string\n\
1325mktime() -- convert local time tuple to seconds since Epoch\n\
1326strftime() -- convert time tuple to string according to format specification\n\
1327strptime() -- parse string to time tuple according to format specification\n\
1328tzset() -- change the local timezone");
1329
1330
Martin v. Löwis1a214512008-06-11 05:26:20 +00001331
1332static struct PyModuleDef timemodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001333 PyModuleDef_HEAD_INIT,
1334 "time",
1335 module_doc,
1336 -1,
1337 time_methods,
1338 NULL,
1339 NULL,
1340 NULL,
1341 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00001342};
1343
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001344PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00001345PyInit_time(void)
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001346{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001347 PyObject *m;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001348 m = PyModule_Create(&timemodule);
1349 if (m == NULL)
1350 return NULL;
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001351
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001352 /* Set, or reset, module variables like time.timezone */
1353 PyInit_timezone(m);
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001355 if (!initialized) {
Victor Stinner1c8f0592013-07-22 22:24:54 +02001356 if (PyStructSequence_InitType2(&StructTimeType,
1357 &struct_time_type_desc) < 0)
1358 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001359 }
1360 Py_INCREF(&StructTimeType);
Alexander Belopolskyc142bba2012-06-13 22:15:26 -04001361#ifdef HAVE_STRUCT_TM_TM_ZONE
1362 PyModule_AddIntConstant(m, "_STRUCT_TM_ITEMS", 11);
1363#else
1364 PyModule_AddIntConstant(m, "_STRUCT_TM_ITEMS", 9);
1365#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001366 PyModule_AddObject(m, "struct_time", (PyObject*) &StructTimeType);
1367 initialized = 1;
1368 return m;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001369}
1370
Victor Stinner071eca32012-03-15 01:17:09 +01001371static PyObject*
Victor Stinnerec895392012-04-29 02:41:27 +02001372floattime(_Py_clock_info_t *info)
Victor Stinner4195b5c2012-02-08 23:03:19 +01001373{
Victor Stinnera47b8812015-03-27 18:16:17 +01001374 _PyTime_t t;
1375 double d;
1376 if (_PyTime_GetSystemClockWithInfo(&t, info) < 0) {
Victor Stinner00111242014-08-29 16:31:59 +02001377 assert(info != NULL);
1378 return NULL;
1379 }
Victor Stinnera47b8812015-03-27 18:16:17 +01001380 d = _PyTime_AsSecondsDouble(t);
1381 return PyFloat_FromDouble(d);
Victor Stinner4195b5c2012-02-08 23:03:19 +01001382}
1383
1384
Victor Stinnercb29f012015-03-27 13:31:18 +01001385/* Implement pysleep() for various platforms.
Guido van Rossumb6775db1994-08-01 11:34:53 +00001386 When interrupted (or when another error occurs), return -1 and
1387 set an exception; else return 0. */
1388
1389static int
Victor Stinnercb29f012015-03-27 13:31:18 +01001390pysleep(_PyTime_t secs)
Guido van Rossum426035c1991-02-19 12:27:35 +00001391{
Victor Stinnercb29f012015-03-27 13:31:18 +01001392 _PyTime_t deadline, monotonic;
Victor Stinner79d68f92015-03-19 21:54:09 +01001393#ifndef MS_WINDOWS
1394 struct timeval timeout;
Victor Stinner79d68f92015-03-19 21:54:09 +01001395 int err = 0;
1396#else
Victor Stinnercb29f012015-03-27 13:31:18 +01001397 _PyTime_t millisecs;
Victor Stinner79d68f92015-03-19 21:54:09 +01001398 unsigned long ul_millis;
1399 DWORD rc;
1400 HANDLE hInterruptEvent;
Victor Stinner0c2fd892015-03-17 10:49:17 +01001401#endif
Victor Stinner79d68f92015-03-19 21:54:09 +01001402
Victor Stinnercb29f012015-03-27 13:31:18 +01001403 deadline = _PyTime_GetMonotonicClock() + secs;
Victor Stinner79d68f92015-03-19 21:54:09 +01001404
1405 do {
1406#ifndef MS_WINDOWS
Victor Stinner869e1772015-03-30 03:49:14 +02001407 if (_PyTime_AsTimeval(secs, &timeout, _PyTime_ROUND_CEILING) < 0)
Victor Stinnercb29f012015-03-27 13:31:18 +01001408 return -1;
Victor Stinner79d68f92015-03-19 21:54:09 +01001409
1410 Py_BEGIN_ALLOW_THREADS
1411 err = select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &timeout);
1412 Py_END_ALLOW_THREADS
1413
1414 if (err == 0)
1415 break;
1416
1417 if (errno != EINTR) {
Victor Stinner0c2fd892015-03-17 10:49:17 +01001418 PyErr_SetFromErrno(PyExc_OSError);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001419 return -1;
1420 }
Victor Stinner79d68f92015-03-19 21:54:09 +01001421#else
Victor Stinner869e1772015-03-30 03:49:14 +02001422 millisecs = _PyTime_AsMilliseconds(secs, _PyTime_ROUND_CEILING);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001423 if (millisecs > (double)ULONG_MAX) {
1424 PyErr_SetString(PyExc_OverflowError,
1425 "sleep length is too large");
1426 return -1;
1427 }
Victor Stinner79d68f92015-03-19 21:54:09 +01001428
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001429 /* Allow sleep(0) to maintain win32 semantics, and as decreed
1430 * by Guido, only the main thread can be interrupted.
1431 */
1432 ul_millis = (unsigned long)millisecs;
Victor Stinner79d68f92015-03-19 21:54:09 +01001433 if (ul_millis == 0 || !_PyOS_IsMainThread()) {
1434 Py_BEGIN_ALLOW_THREADS
Victor Stinner0eac1302015-03-20 03:06:12 +01001435 Sleep(ul_millis);
Victor Stinner79d68f92015-03-19 21:54:09 +01001436 Py_END_ALLOW_THREADS
1437 break;
Victor Stinner945c82e2015-03-12 16:19:01 +01001438 }
Victor Stinner79d68f92015-03-19 21:54:09 +01001439
1440 hInterruptEvent = _PyOS_SigintEvent();
1441 ResetEvent(hInterruptEvent);
1442
1443 Py_BEGIN_ALLOW_THREADS
1444 rc = WaitForSingleObjectEx(hInterruptEvent, ul_millis, FALSE);
Victor Stinner0c2fd892015-03-17 10:49:17 +01001445 Py_END_ALLOW_THREADS
Victor Stinner79d68f92015-03-19 21:54:09 +01001446
1447 if (rc != WAIT_OBJECT_0)
1448 break;
Victor Stinner945c82e2015-03-12 16:19:01 +01001449#endif
Victor Stinner0c2fd892015-03-17 10:49:17 +01001450
Victor Stinner79d68f92015-03-19 21:54:09 +01001451 /* sleep was interrupted by SIGINT */
1452 if (PyErr_CheckSignals())
1453 return -1;
1454
Victor Stinnercb29f012015-03-27 13:31:18 +01001455 monotonic = _PyTime_GetMonotonicClock();
1456 secs = deadline - monotonic;
Victor Stinner6aa446c2015-03-30 21:33:51 +02001457 if (secs < 0)
Victor Stinner79d68f92015-03-19 21:54:09 +01001458 break;
1459 /* retry with the recomputed delay */
1460 } while (1);
1461
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001462 return 0;
Guido van Rossum80c9d881991-04-16 08:47:51 +00001463}