blob: 5961ac9e49209eb4a9e6457eec20d850619eea49 [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"
30
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000031#if defined(__BORLANDC__)
Guido van Rossumb2fb3641996-09-07 00:47:35 +000032/* These overrides not needed for Win32 */
Guido van Rossumb6775db1994-08-01 11:34:53 +000033#define timezone _timezone
Guido van Rossumcc081121995-03-14 15:05:41 +000034#define tzname _tzname
35#define daylight _daylight
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000036#endif /* __BORLANDC__ */
Guido van Rossumcac6c721996-09-06 13:34:02 +000037#endif /* MS_WINDOWS */
Guido van Rossum7bf22de1997-12-02 20:34:19 +000038#endif /* !__WATCOMC__ || __QNX__ */
Guido van Rossum234f9421993-06-17 12:35:49 +000039
Andrew MacIntyre7bf68332002-03-03 02:59:16 +000040#if defined(PYOS_OS2)
41#define INCL_DOS
42#define INCL_ERRORS
43#include <os2.h>
44#endif
45
Guido van Rossum8e9ebfd1997-11-22 21:53:48 +000046#if defined(PYCC_VACPP)
Guido van Rossum26452411998-09-28 22:07:11 +000047#include <sys/time.h>
Guido van Rossum8e9ebfd1997-11-22 21:53:48 +000048#endif
49
Victor Stinnera8ec5ea2012-03-13 00:25:42 +010050#if defined(__APPLE__)
51#include <mach/mach_time.h>
52#endif
53
Guido van Rossum234f9421993-06-17 12:35:49 +000054/* Forward declarations */
Tim Petersdbd9ba62000-07-09 03:09:57 +000055static int floatsleep(double);
Victor Stinnerec895392012-04-29 02:41:27 +020056static PyObject* floattime(_Py_clock_info_t *info);
57
58#ifdef MS_WINDOWS
59static OSVERSIONINFOEX winver;
60#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000061
Barry Warsaw9a2a8a81996-12-06 23:32:14 +000062static PyObject *
Victor Stinner4195b5c2012-02-08 23:03:19 +010063time_time(PyObject *self, PyObject *unused)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000064{
Victor Stinnerec895392012-04-29 02:41:27 +020065 return floattime(NULL);
Guido van Rossumb6775db1994-08-01 11:34:53 +000066}
67
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000068PyDoc_STRVAR(time_doc,
Victor Stinner4195b5c2012-02-08 23:03:19 +010069"time() -> floating point number\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +000070\n\
71Return the current time in seconds since the Epoch.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000072Fractions of a second may be present if the system clock provides them.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +000073
Victor Stinner85fdfa82012-01-27 00:38:48 +010074#if defined(HAVE_CLOCK)
75
76#ifndef CLOCKS_PER_SEC
77#ifdef CLK_TCK
78#define CLOCKS_PER_SEC CLK_TCK
79#else
80#define CLOCKS_PER_SEC 1000000
81#endif
82#endif
83
Victor Stinner4195b5c2012-02-08 23:03:19 +010084static PyObject *
Victor Stinnerec895392012-04-29 02:41:27 +020085floatclock(_Py_clock_info_t *info)
Victor Stinner85fdfa82012-01-27 00:38:48 +010086{
Victor Stinner4195b5c2012-02-08 23:03:19 +010087 clock_t value;
88 value = clock();
89 if (value == (clock_t)-1) {
Victor Stinner85fdfa82012-01-27 00:38:48 +010090 PyErr_SetString(PyExc_RuntimeError,
91 "the processor time used is not available "
92 "or its value cannot be represented");
Victor Stinner4195b5c2012-02-08 23:03:19 +010093 return NULL;
Victor Stinner85fdfa82012-01-27 00:38:48 +010094 }
Victor Stinnerec895392012-04-29 02:41:27 +020095 if (info) {
96 info->implementation = "clock()";
97 info->resolution = 1.0 / (double)CLOCKS_PER_SEC;
Benjamin Peterson49a69e42012-05-01 09:38:34 -040098 info->monotonic = 1;
99 info->adjusted = 0;
Victor Stinnerec895392012-04-29 02:41:27 +0200100 }
Victor Stinner4195b5c2012-02-08 23:03:19 +0100101 return PyFloat_FromDouble((double)value / CLOCKS_PER_SEC);
Victor Stinner85fdfa82012-01-27 00:38:48 +0100102}
103#endif /* HAVE_CLOCK */
104
Thomas Wouters477c8d52006-05-27 19:21:47 +0000105#if defined(MS_WINDOWS) && !defined(__BORLANDC__)
Victor Stinnerec895392012-04-29 02:41:27 +0200106#define WIN32_PERF_COUNTER
Victor Stinner9122fdd2011-07-04 13:55:40 +0200107/* Win32 has better clock replacement; we have our own version, due to Mark
108 Hammond and Tim Peters */
Victor Stinnerec895392012-04-29 02:41:27 +0200109static int
110win_perf_counter(_Py_clock_info_t *info, PyObject **result)
Guido van Rossum3917c221997-04-02 05:35:28 +0000111{
Victor Stinner8b302012012-02-07 23:29:46 +0100112 static LONGLONG cpu_frequency = 0;
Victor Stinner4195b5c2012-02-08 23:03:19 +0100113 static LONGLONG ctrStart;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000114 LARGE_INTEGER now;
Victor Stinner4195b5c2012-02-08 23:03:19 +0100115 double diff;
Guido van Rossum3917c221997-04-02 05:35:28 +0000116
Victor Stinner8b302012012-02-07 23:29:46 +0100117 if (cpu_frequency == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000118 LARGE_INTEGER freq;
Victor Stinner8b302012012-02-07 23:29:46 +0100119 QueryPerformanceCounter(&now);
Victor Stinner4195b5c2012-02-08 23:03:19 +0100120 ctrStart = now.QuadPart;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000121 if (!QueryPerformanceFrequency(&freq) || freq.QuadPart == 0) {
122 /* Unlikely to happen - this works on all intel
123 machines at least! Revert to clock() */
Victor Stinnerec895392012-04-29 02:41:27 +0200124 *result = NULL;
125 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000126 }
Victor Stinner8b302012012-02-07 23:29:46 +0100127 cpu_frequency = freq.QuadPart;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000128 }
129 QueryPerformanceCounter(&now);
Victor Stinner4195b5c2012-02-08 23:03:19 +0100130 diff = (double)(now.QuadPart - ctrStart);
Victor Stinnerec895392012-04-29 02:41:27 +0200131 if (info) {
132 info->implementation = "QueryPerformanceCounter()";
133 info->resolution = 1.0 / (double)cpu_frequency;
Benjamin Peterson49a69e42012-05-01 09:38:34 -0400134 info->monotonic = 1;
135 info->adjusted = 0;
Victor Stinnerec895392012-04-29 02:41:27 +0200136 }
137 *result = PyFloat_FromDouble(diff / (double)cpu_frequency);
138 return 0;
Guido van Rossum3917c221997-04-02 05:35:28 +0000139}
Victor Stinner8b302012012-02-07 23:29:46 +0100140#endif
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000141
Victor Stinnerec895392012-04-29 02:41:27 +0200142#if defined(WIN32_PERF_COUNTER) || defined(HAVE_CLOCK)
143#define PYCLOCK
144static PyObject*
145pyclock(_Py_clock_info_t *info)
146{
147#ifdef WIN32_PERF_COUNTER
148 PyObject *res;
149 if (win_perf_counter(info, &res) == 0)
150 return res;
151#endif
152 return floatclock(info);
153}
154
Victor Stinner9122fdd2011-07-04 13:55:40 +0200155static PyObject *
Victor Stinner4195b5c2012-02-08 23:03:19 +0100156time_clock(PyObject *self, PyObject *unused)
Victor Stinner9122fdd2011-07-04 13:55:40 +0200157{
Victor Stinnerec895392012-04-29 02:41:27 +0200158 return pyclock(NULL);
Victor Stinner9122fdd2011-07-04 13:55:40 +0200159}
Victor Stinner9122fdd2011-07-04 13:55:40 +0200160
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000161PyDoc_STRVAR(clock_doc,
Victor Stinner4195b5c2012-02-08 23:03:19 +0100162"clock() -> floating point number\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000163\n\
164Return the CPU time or real time since the start of the process or since\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000165the first call to clock(). This has as much precision as the system\n\
166records.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000167#endif
168
Victor Stinnere0be4232011-10-25 13:06:09 +0200169#ifdef HAVE_CLOCK_GETTIME
170static PyObject *
Victor Stinner4195b5c2012-02-08 23:03:19 +0100171time_clock_gettime(PyObject *self, PyObject *args)
Victor Stinnere0be4232011-10-25 13:06:09 +0200172{
173 int ret;
Victor Stinnerb8d01692012-04-13 23:44:05 +0200174 int clk_id;
Victor Stinnere0be4232011-10-25 13:06:09 +0200175 struct timespec tp;
176
Victor Stinner4195b5c2012-02-08 23:03:19 +0100177 if (!PyArg_ParseTuple(args, "i:clock_gettime", &clk_id))
Victor Stinnere0be4232011-10-25 13:06:09 +0200178 return NULL;
179
180 ret = clock_gettime((clockid_t)clk_id, &tp);
Antoine Pitrou2c085602012-01-18 01:41:44 +0100181 if (ret != 0) {
Victor Stinnere0be4232011-10-25 13:06:09 +0200182 PyErr_SetFromErrno(PyExc_IOError);
Antoine Pitrou2c085602012-01-18 01:41:44 +0100183 return NULL;
184 }
Victor Stinner4195b5c2012-02-08 23:03:19 +0100185 return PyFloat_FromDouble(tp.tv_sec + tp.tv_nsec * 1e-9);
Victor Stinnere0be4232011-10-25 13:06:09 +0200186}
187
188PyDoc_STRVAR(clock_gettime_doc,
Victor Stinner4195b5c2012-02-08 23:03:19 +0100189"clock_gettime(clk_id) -> floating point number\n\
Victor Stinnere0be4232011-10-25 13:06:09 +0200190\n\
191Return the time of the specified clock clk_id.");
Victor Stinner30d79472012-04-03 00:45:07 +0200192
193static PyObject *
194time_clock_settime(PyObject *self, PyObject *args)
195{
Victor Stinnerb8d01692012-04-13 23:44:05 +0200196 int clk_id;
Victor Stinner30d79472012-04-03 00:45:07 +0200197 PyObject *obj;
198 struct timespec tp;
199 int ret;
200
201 if (!PyArg_ParseTuple(args, "iO:clock_settime", &clk_id, &obj))
202 return NULL;
203
204 if (_PyTime_ObjectToTimespec(obj, &tp.tv_sec, &tp.tv_nsec) == -1)
205 return NULL;
206
207 ret = clock_settime((clockid_t)clk_id, &tp);
208 if (ret != 0) {
209 PyErr_SetFromErrno(PyExc_IOError);
210 return NULL;
211 }
212 Py_RETURN_NONE;
213}
214
215PyDoc_STRVAR(clock_settime_doc,
216"clock_settime(clk_id, time)\n\
217\n\
218Set the time of the specified clock clk_id.");
Victor Stinnere0be4232011-10-25 13:06:09 +0200219
Victor Stinnere0be4232011-10-25 13:06:09 +0200220static PyObject *
Victor Stinner4195b5c2012-02-08 23:03:19 +0100221time_clock_getres(PyObject *self, PyObject *args)
Victor Stinnere0be4232011-10-25 13:06:09 +0200222{
223 int ret;
Victor Stinnerb8d01692012-04-13 23:44:05 +0200224 int clk_id;
Victor Stinnere0be4232011-10-25 13:06:09 +0200225 struct timespec tp;
226
Victor Stinner4195b5c2012-02-08 23:03:19 +0100227 if (!PyArg_ParseTuple(args, "i:clock_getres", &clk_id))
Victor Stinnere0be4232011-10-25 13:06:09 +0200228 return NULL;
229
230 ret = clock_getres((clockid_t)clk_id, &tp);
Antoine Pitrou2c085602012-01-18 01:41:44 +0100231 if (ret != 0) {
Victor Stinnere0be4232011-10-25 13:06:09 +0200232 PyErr_SetFromErrno(PyExc_IOError);
Antoine Pitrou2c085602012-01-18 01:41:44 +0100233 return NULL;
234 }
Victor Stinner4195b5c2012-02-08 23:03:19 +0100235
236 return PyFloat_FromDouble(tp.tv_sec + tp.tv_nsec * 1e-9);
Victor Stinnere0be4232011-10-25 13:06:09 +0200237}
238
239PyDoc_STRVAR(clock_getres_doc,
Victor Stinner4195b5c2012-02-08 23:03:19 +0100240"clock_getres(clk_id) -> floating point number\n\
Victor Stinnere0be4232011-10-25 13:06:09 +0200241\n\
242Return the resolution (precision) of the specified clock clk_id.");
Victor Stinnerb8d01692012-04-13 23:44:05 +0200243#endif /* HAVE_CLOCK_GETTIME */
Victor Stinnere0be4232011-10-25 13:06:09 +0200244
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000245static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000246time_sleep(PyObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000247{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000248 double secs;
249 if (!PyArg_ParseTuple(args, "d:sleep", &secs))
250 return NULL;
Victor Stinner7f53a502011-07-05 22:00:25 +0200251 if (secs < 0) {
252 PyErr_SetString(PyExc_ValueError,
253 "sleep length must be non-negative");
254 return NULL;
255 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000256 if (floatsleep(secs) != 0)
257 return NULL;
258 Py_INCREF(Py_None);
259 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000260}
261
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000262PyDoc_STRVAR(sleep_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000263"sleep(seconds)\n\
264\n\
265Delay execution for a given number of seconds. The argument may be\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000266a floating point number for subsecond precision.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000267
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000268static PyStructSequence_Field struct_time_type_fields[] = {
Alexander Belopolsky69f3fd02010-06-05 15:04:51 +0000269 {"tm_year", "year, for example, 1993"},
270 {"tm_mon", "month of year, range [1, 12]"},
271 {"tm_mday", "day of month, range [1, 31]"},
272 {"tm_hour", "hours, range [0, 23]"},
273 {"tm_min", "minutes, range [0, 59]"},
274 {"tm_sec", "seconds, range [0, 61])"},
275 {"tm_wday", "day of week, range [0, 6], Monday is 0"},
276 {"tm_yday", "day of year, range [1, 366]"},
277 {"tm_isdst", "1 if summer time is in effect, 0 if not, and -1 if unknown"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000278 {0}
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000279};
280
281static PyStructSequence_Desc struct_time_type_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000282 "time.struct_time",
Alexander Belopolsky69f3fd02010-06-05 15:04:51 +0000283 "The time value as returned by gmtime(), localtime(), and strptime(), and\n"
284 " accepted by asctime(), mktime() and strftime(). May be considered as a\n"
285 " sequence of 9 integers.\n\n"
286 " Note that several fields' values are not the same as those defined by\n"
287 " the C language standard for struct tm. For example, the value of the\n"
288 " field tm_year is the actual year, not year - 1900. See individual\n"
289 " fields' descriptions for details.",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000290 struct_time_type_fields,
291 9,
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000292};
Tim Peters9ad4b682002-02-13 05:14:18 +0000293
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000294static int initialized;
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000295static PyTypeObject StructTimeType;
296
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000297static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000298tmtotuple(struct tm *p)
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000299{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000300 PyObject *v = PyStructSequence_New(&StructTimeType);
301 if (v == NULL)
302 return NULL;
Tim Peters9ad4b682002-02-13 05:14:18 +0000303
Christian Heimes217cfd12007-12-02 14:31:20 +0000304#define SET(i,val) PyStructSequence_SET_ITEM(v, i, PyLong_FromLong((long) val))
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000305
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000306 SET(0, p->tm_year + 1900);
307 SET(1, p->tm_mon + 1); /* Want January == 1 */
308 SET(2, p->tm_mday);
309 SET(3, p->tm_hour);
310 SET(4, p->tm_min);
311 SET(5, p->tm_sec);
312 SET(6, (p->tm_wday + 6) % 7); /* Want Monday == 0 */
313 SET(7, p->tm_yday + 1); /* Want January, 1 == 1 */
314 SET(8, p->tm_isdst);
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000315#undef SET
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000316 if (PyErr_Occurred()) {
317 Py_XDECREF(v);
318 return NULL;
319 }
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000320
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000321 return v;
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000322}
323
Fred Drakef901abd2004-08-03 17:58:55 +0000324/* Parse arg tuple that can contain an optional float-or-None value;
325 format needs to be "|O:name".
326 Returns non-zero on success (parallels PyArg_ParseTuple).
327*/
328static int
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100329parse_time_t_args(PyObject *args, char *format, time_t *pwhen)
Fred Drakef901abd2004-08-03 17:58:55 +0000330{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000331 PyObject *ot = NULL;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100332 time_t whent;
Fred Drakef901abd2004-08-03 17:58:55 +0000333
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000334 if (!PyArg_ParseTuple(args, format, &ot))
335 return 0;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100336 if (ot == NULL || ot == Py_None) {
337 whent = time(NULL);
338 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000339 else {
Victor Stinner5d272cc2012-03-13 13:35:55 +0100340 if (_PyTime_ObjectToTime_t(ot, &whent) == -1)
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100341 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000342 }
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100343 *pwhen = whent;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000344 return 1;
Fred Drakef901abd2004-08-03 17:58:55 +0000345}
346
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000347static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000348time_gmtime(PyObject *self, PyObject *args)
Guido van Rossum234f9421993-06-17 12:35:49 +0000349{
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100350 time_t when;
351 struct tm buf, *local;
352
353 if (!parse_time_t_args(args, "|O:gmtime", &when))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000354 return NULL;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100355
356 errno = 0;
357 local = gmtime(&when);
358 if (local == NULL) {
359#ifdef EINVAL
360 if (errno == 0)
361 errno = EINVAL;
362#endif
363 return PyErr_SetFromErrno(PyExc_OSError);
364 }
365 buf = *local;
366 return tmtotuple(&buf);
Guido van Rossum234f9421993-06-17 12:35:49 +0000367}
368
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000369PyDoc_STRVAR(gmtime_doc,
Christian Heimes9a371592007-12-28 14:08:13 +0000370"gmtime([seconds]) -> (tm_year, tm_mon, tm_mday, tm_hour, tm_min,\n\
Fred Drake193a3f62002-03-12 21:38:49 +0000371 tm_sec, tm_wday, tm_yday, tm_isdst)\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000372\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000373Convert seconds since the Epoch to a time tuple expressing UTC (a.k.a.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000374GMT). When 'seconds' is not passed in, convert the current time instead.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000375
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100376static int
377pylocaltime(time_t *timep, struct tm *result)
378{
379 struct tm *local;
380
381 assert (timep != NULL);
382 local = localtime(timep);
383 if (local == NULL) {
384 /* unconvertible time */
385#ifdef EINVAL
386 if (errno == 0)
387 errno = EINVAL;
388#endif
389 PyErr_SetFromErrno(PyExc_OSError);
390 return -1;
391 }
392 *result = *local;
393 return 0;
394}
395
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000396static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000397time_localtime(PyObject *self, PyObject *args)
Guido van Rossum234f9421993-06-17 12:35:49 +0000398{
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100399 time_t when;
400 struct tm buf;
401
402 if (!parse_time_t_args(args, "|O:localtime", &when))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000403 return NULL;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100404 if (pylocaltime(&when, &buf) == 1)
405 return NULL;
406 return tmtotuple(&buf);
Guido van Rossum234f9421993-06-17 12:35:49 +0000407}
408
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000409PyDoc_STRVAR(localtime_doc,
Christian Heimes9a371592007-12-28 14:08:13 +0000410"localtime([seconds]) -> (tm_year,tm_mon,tm_mday,tm_hour,tm_min,\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000411 tm_sec,tm_wday,tm_yday,tm_isdst)\n\
Martin v. Löwisb3cfc1d2001-12-02 12:27:43 +0000412\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000413Convert seconds since the Epoch to a time tuple expressing local time.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000414When 'seconds' is not passed in, convert the current time instead.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000415
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000416/* Convert 9-item tuple to tm structure. Return 1 on success, set
417 * an exception and return 0 on error.
418 */
Guido van Rossum9e90a671993-06-24 11:10:19 +0000419static int
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000420gettmarg(PyObject *args, struct tm *p)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000421{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000422 int y;
Guido van Rossumcfbaecc1998-08-25 14:51:12 +0000423
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000424 memset((void *) p, '\0', sizeof(struct tm));
Guido van Rossumb9081262007-08-25 03:14:09 +0000425
Alexander Belopolsky610e5442011-01-06 21:57:06 +0000426 if (!PyTuple_Check(args)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000427 PyErr_SetString(PyExc_TypeError,
428 "Tuple or struct_time argument required");
429 return 0;
430 }
Skip Montanaro41cfce92007-08-24 21:11:00 +0000431
Alexander Belopolsky610e5442011-01-06 21:57:06 +0000432 if (!PyArg_ParseTuple(args, "iiiiiiiii",
433 &y, &p->tm_mon, &p->tm_mday,
434 &p->tm_hour, &p->tm_min, &p->tm_sec,
435 &p->tm_wday, &p->tm_yday, &p->tm_isdst))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000436 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000437 p->tm_year = y - 1900;
438 p->tm_mon--;
439 p->tm_wday = (p->tm_wday + 1) % 7;
440 p->tm_yday--;
441 return 1;
Guido van Rossum9e90a671993-06-24 11:10:19 +0000442}
443
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000444/* Check values of the struct tm fields before it is passed to strftime() and
445 * asctime(). Return 1 if all values are valid, otherwise set an exception
446 * and returns 0.
447 */
Victor Stinneref128102010-10-07 01:00:52 +0000448static int
449checktm(struct tm* buf)
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000450{
Victor Stinneref128102010-10-07 01:00:52 +0000451 /* Checks added to make sure strftime() and asctime() does not crash Python by
452 indexing blindly into some array for a textual representation
453 by some bad index (fixes bug #897625 and #6608).
454
455 Also support values of zero from Python code for arguments in which
456 that is out of range by forcing that value to the lowest value that
457 is valid (fixed bug #1520914).
458
459 Valid ranges based on what is allowed in struct tm:
460
461 - tm_year: [0, max(int)] (1)
462 - tm_mon: [0, 11] (2)
463 - tm_mday: [1, 31]
464 - tm_hour: [0, 23]
465 - tm_min: [0, 59]
466 - tm_sec: [0, 60]
467 - tm_wday: [0, 6] (1)
468 - tm_yday: [0, 365] (2)
469 - tm_isdst: [-max(int), max(int)]
470
471 (1) gettmarg() handles bounds-checking.
472 (2) Python's acceptable range is one greater than the range in C,
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000473 thus need to check against automatic decrement by gettmarg().
474 */
475 if (buf->tm_mon == -1)
476 buf->tm_mon = 0;
477 else if (buf->tm_mon < 0 || buf->tm_mon > 11) {
478 PyErr_SetString(PyExc_ValueError, "month out of range");
479 return 0;
480 }
481 if (buf->tm_mday == 0)
482 buf->tm_mday = 1;
483 else if (buf->tm_mday < 0 || buf->tm_mday > 31) {
484 PyErr_SetString(PyExc_ValueError, "day of month out of range");
485 return 0;
486 }
487 if (buf->tm_hour < 0 || buf->tm_hour > 23) {
488 PyErr_SetString(PyExc_ValueError, "hour out of range");
489 return 0;
490 }
491 if (buf->tm_min < 0 || buf->tm_min > 59) {
492 PyErr_SetString(PyExc_ValueError, "minute out of range");
493 return 0;
494 }
495 if (buf->tm_sec < 0 || buf->tm_sec > 61) {
496 PyErr_SetString(PyExc_ValueError, "seconds out of range");
497 return 0;
498 }
499 /* tm_wday does not need checking of its upper-bound since taking
500 ``% 7`` in gettmarg() automatically restricts the range. */
501 if (buf->tm_wday < 0) {
502 PyErr_SetString(PyExc_ValueError, "day of week out of range");
503 return 0;
504 }
505 if (buf->tm_yday == -1)
506 buf->tm_yday = 0;
507 else if (buf->tm_yday < 0 || buf->tm_yday > 365) {
508 PyErr_SetString(PyExc_ValueError, "day of year out of range");
509 return 0;
510 }
511 return 1;
512}
513
Victor Stinnerc1f32ca2011-10-14 02:36:13 +0200514#ifdef MS_WINDOWS
515 /* wcsftime() doesn't format correctly time zones, see issue #10653 */
516# undef HAVE_WCSFTIME
517#endif
518
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000519#ifdef HAVE_STRFTIME
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000520#ifdef HAVE_WCSFTIME
521#define time_char wchar_t
522#define format_time wcsftime
523#define time_strlen wcslen
524#else
525#define time_char char
526#define format_time strftime
527#define time_strlen strlen
528#endif
529
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000530static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000531time_strftime(PyObject *self, PyObject *args)
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000532{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000533 PyObject *tup = NULL;
534 struct tm buf;
535 const time_char *fmt;
Victor Stinnerb2904782010-09-29 10:34:19 +0000536#ifdef HAVE_WCSFTIME
537 wchar_t *format;
538#else
539 PyObject *format;
540#endif
Victor Stinneref128102010-10-07 01:00:52 +0000541 PyObject *format_arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000542 size_t fmtlen, buflen;
Victor Stinnerb2904782010-09-29 10:34:19 +0000543 time_char *outbuf = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000544 size_t i;
Victor Stinnerb2904782010-09-29 10:34:19 +0000545 PyObject *ret = NULL;
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000546
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000547 memset((void *) &buf, '\0', sizeof(buf));
Guido van Rossum1f41f841998-04-27 19:04:26 +0000548
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000549 /* Will always expect a unicode string to be passed as format.
550 Given that there's no str type anymore in py3k this seems safe.
551 */
Victor Stinneref128102010-10-07 01:00:52 +0000552 if (!PyArg_ParseTuple(args, "U|O:strftime", &format_arg, &tup))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000553 return NULL;
Thomas Woutersfe385252001-01-19 23:16:56 +0000554
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000555 if (tup == NULL) {
556 time_t tt = time(NULL);
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100557 if (pylocaltime(&tt, &buf) == -1)
558 return NULL;
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000559 }
560 else if (!gettmarg(tup, &buf) || !checktm(&buf))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000561 return NULL;
Guido van Rossum10b164a2001-09-25 13:59:01 +0000562
Victor Stinner06ec45e2011-01-08 03:35:36 +0000563#if defined(_MSC_VER) || defined(sun)
Victor Stinner73ea29c2011-01-08 01:56:31 +0000564 if (buf.tm_year + 1900 < 1 || 9999 < buf.tm_year + 1900) {
Victor Stinner6f0e4f92011-03-21 02:14:53 +0100565 PyErr_SetString(PyExc_ValueError,
566 "strftime() requires year in [1; 9999]");
Alexander Belopolsky0dd06f42011-01-08 01:23:02 +0000567 return NULL;
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000568 }
Victor Stinner73ea29c2011-01-08 01:56:31 +0000569#endif
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000570
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000571 /* Normalize tm_isdst just in case someone foolishly implements %Z
572 based on the assumption that tm_isdst falls within the range of
573 [-1, 1] */
574 if (buf.tm_isdst < -1)
575 buf.tm_isdst = -1;
576 else if (buf.tm_isdst > 1)
577 buf.tm_isdst = 1;
Brett Cannond1080a32004-03-02 04:38:10 +0000578
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000579#ifdef HAVE_WCSFTIME
Victor Stinnerbeb4135b2010-10-07 01:02:42 +0000580 format = PyUnicode_AsWideCharString(format_arg, NULL);
Victor Stinnerb2904782010-09-29 10:34:19 +0000581 if (format == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000582 return NULL;
Victor Stinnerb2904782010-09-29 10:34:19 +0000583 fmt = format;
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000584#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000585 /* Convert the unicode string to an ascii one */
Victor Stinner1b579672011-12-17 05:47:23 +0100586 format = PyUnicode_EncodeLocale(format_arg, "surrogateescape");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000587 if (format == NULL)
588 return NULL;
589 fmt = PyBytes_AS_STRING(format);
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000590#endif
Amaury Forgeot d'Arcb5be6d42009-03-02 23:52:57 +0000591
Stefan Krah4aea7d32012-02-27 16:30:26 +0100592#if defined(MS_WINDOWS) && !defined(HAVE_WCSFTIME)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000593 /* check that the format string contains only valid directives */
Victor Stinner5a3ff792011-10-16 19:08:23 +0200594 for(outbuf = strchr(fmt, '%');
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000595 outbuf != NULL;
Victor Stinner5a3ff792011-10-16 19:08:23 +0200596 outbuf = strchr(outbuf+2, '%'))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000597 {
598 if (outbuf[1]=='#')
599 ++outbuf; /* not documented by python, */
600 if (outbuf[1]=='\0' ||
Victor Stinner5a3ff792011-10-16 19:08:23 +0200601 !strchr("aAbBcdHIjmMpSUwWxXyYzZ%", outbuf[1]))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000602 {
603 PyErr_SetString(PyExc_ValueError, "Invalid format string");
Stefan Krah4aea7d32012-02-27 16:30:26 +0100604 Py_DECREF(format);
605 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000606 }
607 }
Amaury Forgeot d'Arcb5be6d42009-03-02 23:52:57 +0000608#endif
609
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000610 fmtlen = time_strlen(fmt);
Guido van Rossumc222ec21999-02-23 00:00:10 +0000611
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000612 /* I hate these functions that presume you know how big the output
613 * will be ahead of time...
614 */
615 for (i = 1024; ; i += i) {
Victor Stinner136ea492011-12-17 22:37:18 +0100616#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100617 int err;
Victor Stinner136ea492011-12-17 22:37:18 +0100618#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000619 outbuf = (time_char *)PyMem_Malloc(i*sizeof(time_char));
620 if (outbuf == NULL) {
Victor Stinnerb2904782010-09-29 10:34:19 +0000621 PyErr_NoMemory();
622 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000623 }
624 buflen = format_time(outbuf, i, fmt, &buf);
Victor Stinner136ea492011-12-17 22:37:18 +0100625#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100626 err = errno;
Victor Stinner136ea492011-12-17 22:37:18 +0100627#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000628 if (buflen > 0 || i >= 256 * fmtlen) {
629 /* If the buffer is 256 times as long as the format,
630 it's probably not failing for lack of room!
631 More likely, the format yields an empty result,
632 e.g. an empty format, or %Z when the timezone
633 is unknown. */
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000634#ifdef HAVE_WCSFTIME
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000635 ret = PyUnicode_FromWideChar(outbuf, buflen);
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000636#else
Victor Stinner1b579672011-12-17 05:47:23 +0100637 ret = PyUnicode_DecodeLocaleAndSize(outbuf, buflen,
638 "surrogateescape");
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000639#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000640 PyMem_Free(outbuf);
Victor Stinnerb2904782010-09-29 10:34:19 +0000641 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000642 }
643 PyMem_Free(outbuf);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000644#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000645 /* VisualStudio .NET 2005 does this properly */
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100646 if (buflen == 0 && err == EINVAL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000647 PyErr_SetString(PyExc_ValueError, "Invalid format string");
Victor Stinnerb2904782010-09-29 10:34:19 +0000648 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000649 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000650#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000651 }
Victor Stinnerb2904782010-09-29 10:34:19 +0000652#ifdef HAVE_WCSFTIME
653 PyMem_Free(format);
654#else
655 Py_DECREF(format);
656#endif
657 return ret;
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000658}
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000659
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000660#undef time_char
661#undef format_time
662
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000663PyDoc_STRVAR(strftime_doc,
Thomas Woutersfe385252001-01-19 23:16:56 +0000664"strftime(format[, tuple]) -> string\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000665\n\
666Convert a time tuple to a string according to a format specification.\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000667See the library reference manual for formatting codes. When the time tuple\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000668is not present, current time as returned by localtime() is used.");
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000669#endif /* HAVE_STRFTIME */
670
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000671static PyObject *
672time_strptime(PyObject *self, PyObject *args)
673{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000674 PyObject *strptime_module = PyImport_ImportModuleNoBlock("_strptime");
675 PyObject *strptime_result;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200676 _Py_IDENTIFIER(_strptime_time);
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000677
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000678 if (!strptime_module)
679 return NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200680 strptime_result = _PyObject_CallMethodId(strptime_module,
681 &PyId__strptime_time, "O", args);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000682 Py_DECREF(strptime_module);
683 return strptime_result;
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000684}
685
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000686
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000687PyDoc_STRVAR(strptime_doc,
Brett Cannon20def8b2003-07-01 05:16:08 +0000688"strptime(string, format) -> struct_time\n\
Martin v. Löwisb3cfc1d2001-12-02 12:27:43 +0000689\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000690Parse a string to a time tuple according to a format specification.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000691See the library reference manual for formatting codes (same as strftime()).");
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000692
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000693static PyObject *
694_asctime(struct tm *timeptr)
695{
696 /* Inspired by Open Group reference implementation available at
697 * http://pubs.opengroup.org/onlinepubs/009695399/functions/asctime.html */
Victor Stinner499dfcf2011-03-21 13:26:24 +0100698 static char wday_name[7][4] = {
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000699 "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
700 };
Victor Stinner499dfcf2011-03-21 13:26:24 +0100701 static char mon_name[12][4] = {
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000702 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
703 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
704 };
Victor Stinner499dfcf2011-03-21 13:26:24 +0100705 return PyUnicode_FromFormat(
706 "%s %s%3d %.2d:%.2d:%.2d %d",
707 wday_name[timeptr->tm_wday],
708 mon_name[timeptr->tm_mon],
709 timeptr->tm_mday, timeptr->tm_hour,
710 timeptr->tm_min, timeptr->tm_sec,
711 1900 + timeptr->tm_year);
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000712}
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000713
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000714static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000715time_asctime(PyObject *self, PyObject *args)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000716{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000717 PyObject *tup = NULL;
718 struct tm buf;
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000719
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000720 if (!PyArg_UnpackTuple(args, "asctime", 0, 1, &tup))
721 return NULL;
722 if (tup == NULL) {
723 time_t tt = time(NULL);
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100724 if (pylocaltime(&tt, &buf) == -1)
725 return NULL;
726
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000727 } else if (!gettmarg(tup, &buf) || !checktm(&buf))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000728 return NULL;
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000729 return _asctime(&buf);
Guido van Rossum9e90a671993-06-24 11:10:19 +0000730}
731
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000732PyDoc_STRVAR(asctime_doc,
Thomas Woutersfe385252001-01-19 23:16:56 +0000733"asctime([tuple]) -> string\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000734\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000735Convert a time tuple to a string, e.g. 'Sat Jun 06 16:26:11 1998'.\n\
736When the time tuple is not present, current time as returned by localtime()\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000737is used.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000738
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000739static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000740time_ctime(PyObject *self, PyObject *args)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000741{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000742 time_t tt;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100743 struct tm buf;
744 if (!parse_time_t_args(args, "|O:ctime", &tt))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000745 return NULL;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100746 if (pylocaltime(&tt, &buf) == -1)
Alexander Belopolsky5da468f2011-01-04 17:15:52 +0000747 return NULL;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100748 return _asctime(&buf);
Guido van Rossum9e90a671993-06-24 11:10:19 +0000749}
750
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000751PyDoc_STRVAR(ctime_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000752"ctime(seconds) -> string\n\
753\n\
754Convert a time in seconds since the Epoch to a string in local time.\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000755This is equivalent to asctime(localtime(seconds)). When the time tuple is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000756not present, current time as returned by localtime() is used.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000757
Guido van Rossum60cd8131998-03-06 17:16:21 +0000758#ifdef HAVE_MKTIME
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000759static PyObject *
Victor Stinner4195b5c2012-02-08 23:03:19 +0100760time_mktime(PyObject *self, PyObject *tup)
Guido van Rossum234f9421993-06-17 12:35:49 +0000761{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000762 struct tm buf;
763 time_t tt;
764 if (!gettmarg(tup, &buf))
765 return NULL;
Alexander Belopolskyb7d40d12011-01-11 01:21:25 +0000766 buf.tm_wday = -1; /* sentinel; original value ignored */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000767 tt = mktime(&buf);
Alexander Belopolskyb7d40d12011-01-11 01:21:25 +0000768 /* Return value of -1 does not necessarily mean an error, but tm_wday
Ezio Melotti13925002011-03-16 11:05:33 +0200769 * cannot remain set to -1 if mktime succeeded. */
Alexander Belopolskyb7d40d12011-01-11 01:21:25 +0000770 if (tt == (time_t)(-1) && buf.tm_wday == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000771 PyErr_SetString(PyExc_OverflowError,
772 "mktime argument out of range");
773 return NULL;
774 }
Victor Stinner4195b5c2012-02-08 23:03:19 +0100775 return PyFloat_FromDouble((double)tt);
Guido van Rossum234f9421993-06-17 12:35:49 +0000776}
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000777
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000778PyDoc_STRVAR(mktime_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000779"mktime(tuple) -> floating point number\n\
780\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000781Convert a time tuple in local time to seconds since the Epoch.");
Guido van Rossum60cd8131998-03-06 17:16:21 +0000782#endif /* HAVE_MKTIME */
Guido van Rossum234f9421993-06-17 12:35:49 +0000783
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000784#ifdef HAVE_WORKING_TZSET
Martin v. Löwis1a214512008-06-11 05:26:20 +0000785static void PyInit_timezone(PyObject *module);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000786
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000787static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000788time_tzset(PyObject *self, PyObject *unused)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000789{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000790 PyObject* m;
Fred Drake9bb74322002-04-01 14:49:59 +0000791
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000792 m = PyImport_ImportModuleNoBlock("time");
793 if (m == NULL) {
794 return NULL;
795 }
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000796
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000797 tzset();
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000798
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000799 /* Reset timezone, altzone, daylight and tzname */
800 PyInit_timezone(m);
801 Py_DECREF(m);
Tim Peters1b6f7a92004-06-20 02:50:16 +0000802
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000803 Py_INCREF(Py_None);
804 return Py_None;
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000805}
806
807PyDoc_STRVAR(tzset_doc,
R. David Murray4d55bf92010-12-14 00:55:46 +0000808"tzset()\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000809\n\
810Initialize, or reinitialize, the local timezone to the value stored in\n\
811os.environ['TZ']. The TZ environment variable should be specified in\n\
Neal Norwitzdc8e1942004-07-20 22:34:37 +0000812standard Unix timezone format as documented in the tzset man page\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000813(eg. 'US/Eastern', 'Europe/Amsterdam'). Unknown timezones will silently\n\
814fall back to UTC. If the TZ environment variable is not set, the local\n\
815timezone is set to the systems best guess of wallclock time.\n\
816Changing the TZ environment variable without calling tzset *may* change\n\
817the local timezone used by methods such as localtime, but this behaviour\n\
818should not be relied on.");
819#endif /* HAVE_WORKING_TZSET */
820
Victor Stinnerec895392012-04-29 02:41:27 +0200821#if defined(MS_WINDOWS) || defined(__APPLE__) \
822 || (defined(HAVE_CLOCK_GETTIME) \
823 && (defined(CLOCK_HIGHRES) || defined(CLOCK_MONOTONIC)))
824#define PYMONOTONIC
825#endif
826
827#ifdef PYMONOTONIC
Victor Stinner071eca32012-03-15 01:17:09 +0100828static PyObject*
Victor Stinnerec895392012-04-29 02:41:27 +0200829pymonotonic(_Py_clock_info_t *info)
Victor Stinnerb94b2662012-01-18 01:50:21 +0100830{
Victor Stinnerec895392012-04-29 02:41:27 +0200831#if defined(MS_WINDOWS)
832 static ULONGLONG (*GetTickCount64) (void) = NULL;
833 static ULONGLONG (CALLBACK *Py_GetTickCount64)(void);
834 static int has_getickcount64 = -1;
835 double result;
836
837 if (has_getickcount64 == -1) {
838 /* GetTickCount64() was added to Windows Vista */
839 if (winver.dwMajorVersion >= 6) {
840 HINSTANCE hKernel32;
841 hKernel32 = GetModuleHandleW(L"KERNEL32");
842 *(FARPROC*)&Py_GetTickCount64 = GetProcAddress(hKernel32,
843 "GetTickCount64");
844 has_getickcount64 = (Py_GetTickCount64 != NULL);
845 }
846 else
847 has_getickcount64 = 0;
848 }
849
850 if (has_getickcount64) {
851 ULONGLONG ticks;
852 ticks = Py_GetTickCount64();
853 result = (double)ticks * 1e-3;
854 }
855 else {
856 static DWORD last_ticks = 0;
857 static DWORD n_overflow = 0;
858 DWORD ticks;
859
860 ticks = GetTickCount();
861 if (ticks < last_ticks)
862 n_overflow++;
863 last_ticks = ticks;
864
865 result = ldexp(n_overflow, 32);
866 result += ticks;
867 result *= 1e-3;
868 }
869
870 if (info) {
871 DWORD timeAdjustment, timeIncrement;
872 BOOL isTimeAdjustmentDisabled, ok;
873 if (has_getickcount64)
874 info->implementation = "GetTickCount64()";
875 else
876 info->implementation = "GetTickCount()";
Benjamin Peterson49a69e42012-05-01 09:38:34 -0400877 info->monotonic = 1;
Victor Stinnerec895392012-04-29 02:41:27 +0200878 ok = GetSystemTimeAdjustment(&timeAdjustment, &timeIncrement,
879 &isTimeAdjustmentDisabled);
880 if (!ok) {
881 PyErr_SetFromWindowsErr(0);
882 return NULL;
883 }
884 info->resolution = timeIncrement * 1e-7;
Benjamin Peterson49a69e42012-05-01 09:38:34 -0400885 info->adjusted = 0;
Victor Stinnerec895392012-04-29 02:41:27 +0200886 }
887 return PyFloat_FromDouble(result);
888
Victor Stinnera8ec5ea2012-03-13 00:25:42 +0100889#elif defined(__APPLE__)
Victor Stinner74eb6c02012-03-28 02:50:46 +0200890 static mach_timebase_info_data_t timebase;
891 uint64_t time;
Victor Stinnera8ec5ea2012-03-13 00:25:42 +0100892 double secs;
893
Victor Stinner74eb6c02012-03-28 02:50:46 +0200894 if (timebase.denom == 0) {
895 /* According to the Technical Q&A QA1398, mach_timebase_info() cannot
896 fail: https://developer.apple.com/library/mac/#qa/qa1398/ */
897 (void)mach_timebase_info(&timebase);
898 }
Victor Stinnera8ec5ea2012-03-13 00:25:42 +0100899
Victor Stinner74eb6c02012-03-28 02:50:46 +0200900 time = mach_absolute_time();
Victor Stinnera8ec5ea2012-03-13 00:25:42 +0100901 secs = (double)time * timebase.numer / timebase.denom * 1e-9;
Victor Stinnerec895392012-04-29 02:41:27 +0200902 if (info) {
903 info->implementation = "mach_absolute_time()";
904 info->resolution = (double)timebase.numer / timebase.denom * 1e-9;
Benjamin Peterson49a69e42012-05-01 09:38:34 -0400905 info->monotonic = 1;
906 info->adjusted = 0;
Victor Stinnerec895392012-04-29 02:41:27 +0200907 }
Victor Stinnera8ec5ea2012-03-13 00:25:42 +0100908 return PyFloat_FromDouble(secs);
Victor Stinnerec895392012-04-29 02:41:27 +0200909
910#elif defined(HAVE_CLOCK_GETTIME) && (defined(CLOCK_HIGHRES) || defined(CLOCK_MONOTONIC))
Victor Stinner8b302012012-02-07 23:29:46 +0100911 struct timespec tp;
Victor Stinnerec895392012-04-29 02:41:27 +0200912#ifdef CLOCK_HIGHRES
913 const clockid_t clk_id = CLOCK_HIGHRES;
914 const char *function = "clock_gettime(CLOCK_HIGHRES)";
915#else
916 const clockid_t clk_id = CLOCK_MONOTONIC;
917 const char *function = "clock_gettime(CLOCK_MONOTONIC)";
918#endif
Victor Stinner8b302012012-02-07 23:29:46 +0100919
Victor Stinnerec895392012-04-29 02:41:27 +0200920 if (clock_gettime(clk_id, &tp) != 0) {
Victor Stinner071eca32012-03-15 01:17:09 +0100921 PyErr_SetFromErrno(PyExc_OSError);
922 return NULL;
923 }
Victor Stinnerec895392012-04-29 02:41:27 +0200924
925 if (info) {
926 struct timespec res;
Benjamin Peterson49a69e42012-05-01 09:38:34 -0400927 info->monotonic = 1;
Victor Stinnerec895392012-04-29 02:41:27 +0200928 info->implementation = function;
929#if (defined(linux) || defined(__linux) || defined(__linux__)) \
930 && !defined(CLOCK_HIGHRES)
931 /* CLOCK_MONOTONIC is adjusted on Linux */
Benjamin Peterson49a69e42012-05-01 09:38:34 -0400932 info->adjusted = 1;
Victor Stinnerec919cc2012-03-15 00:58:32 +0100933#else
Benjamin Peterson49a69e42012-05-01 09:38:34 -0400934 info->adjusted = 0;
Victor Stinnerec895392012-04-29 02:41:27 +0200935#endif
936 if (clock_getres(clk_id, &res) == 0)
937 info->resolution = res.tv_sec + res.tv_nsec * 1e-9;
938 else
939 info->resolution = 1e-9;
Victor Stinner071eca32012-03-15 01:17:09 +0100940 }
Victor Stinnerec895392012-04-29 02:41:27 +0200941 return PyFloat_FromDouble(tp.tv_sec + tp.tv_nsec * 1e-9);
Victor Stinner8b302012012-02-07 23:29:46 +0100942#endif
943}
944
Victor Stinner071eca32012-03-15 01:17:09 +0100945static PyObject *
Victor Stinnerec895392012-04-29 02:41:27 +0200946time_monotonic(PyObject *self, PyObject *unused)
Victor Stinner071eca32012-03-15 01:17:09 +0100947{
Victor Stinnerec895392012-04-29 02:41:27 +0200948 return pymonotonic(NULL);
Victor Stinner071eca32012-03-15 01:17:09 +0100949}
950
Victor Stinnerec895392012-04-29 02:41:27 +0200951PyDoc_STRVAR(monotonic_doc,
952"monotonic() -> float\n\
Victor Stinner8b302012012-02-07 23:29:46 +0100953\n\
Victor Stinnerec895392012-04-29 02:41:27 +0200954Monotonic clock, cannot go backward.");
955#endif /* PYMONOTONIC */
Victor Stinnerec919cc2012-03-15 00:58:32 +0100956
Victor Stinnerec895392012-04-29 02:41:27 +0200957static PyObject*
958perf_counter(_Py_clock_info_t *info)
959{
960#if defined(WIN32_PERF_COUNTER) || defined(PYMONOTONIC)
961 PyObject *res;
962#endif
963#if defined(WIN32_PERF_COUNTER)
964 static int use_perf_counter = 1;
965#endif
966#ifdef PYMONOTONIC
967 static int use_monotonic = 1;
968#endif
969
970#ifdef WIN32_PERF_COUNTER
971 if (use_perf_counter) {
972 if (win_perf_counter(info, &res) == 0)
973 return res;
974 use_perf_counter = 0;
975 }
976#endif
977
978#ifdef PYMONOTONIC
979 if (use_monotonic) {
980 res = pymonotonic(info);
981 if (res != NULL)
982 return res;
983 use_monotonic = 0;
984 PyErr_Clear();
985 }
986#endif
987
988 return floattime(info);
989}
990
991static PyObject *
992time_perf_counter(PyObject *self, PyObject *unused)
993{
994 return perf_counter(NULL);
995}
996
997PyDoc_STRVAR(perf_counter_doc,
998"perf_counter() -> float\n\
999\n\
1000Performance counter for benchmarking.");
1001
1002static PyObject*
1003py_process_time(_Py_clock_info_t *info)
1004{
1005#if defined(MS_WINDOWS)
1006 HANDLE process;
1007 FILETIME creation_time, exit_time, kernel_time, user_time;
1008 ULARGE_INTEGER large;
1009 double total;
1010 BOOL ok;
1011
1012 process = GetCurrentProcess();
1013 ok = GetProcessTimes(process, &creation_time, &exit_time, &kernel_time, &user_time);
1014 if (!ok)
1015 return PyErr_SetFromWindowsErr(0);
1016
1017 large.u.LowPart = kernel_time.dwLowDateTime;
1018 large.u.HighPart = kernel_time.dwHighDateTime;
1019 total = (double)large.QuadPart;
1020 large.u.LowPart = user_time.dwLowDateTime;
1021 large.u.HighPart = user_time.dwHighDateTime;
1022 total += (double)large.QuadPart;
1023 if (info) {
1024 info->implementation = "GetProcessTimes()";
1025 info->resolution = 1e-7;
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001026 info->monotonic = 1;
1027 info->adjusted = 0;
Victor Stinnerec895392012-04-29 02:41:27 +02001028 }
1029 return PyFloat_FromDouble(total * 1e-7);
1030#else
1031
1032#if defined(HAVE_SYS_RESOURCE_H)
1033 struct rusage ru;
1034#endif
1035#ifdef HAVE_TIMES
1036 struct tms t;
1037 static long ticks_per_second = -1;
1038#endif
1039
1040#if defined(HAVE_CLOCK_GETTIME) \
1041 && (defined(CLOCK_PROCESS_CPUTIME_ID) || defined(CLOCK_PROF))
1042 struct timespec tp;
1043#ifdef CLOCK_PROF
1044 const clockid_t clk_id = CLOCK_PROF;
1045 const char *function = "clock_gettime(CLOCK_PROF)";
1046#else
1047 const clockid_t clk_id = CLOCK_PROCESS_CPUTIME_ID;
1048 const char *function = "clock_gettime(CLOCK_PROCESS_CPUTIME_ID)";
1049#endif
1050
1051 if (clock_gettime(clk_id, &tp) == 0) {
1052 if (info) {
1053 struct timespec res;
1054 info->implementation = function;
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001055 info->monotonic = 1;
1056 info->adjusted = 0;
Victor Stinnerec895392012-04-29 02:41:27 +02001057 if (clock_getres(clk_id, &res) == 0)
1058 info->resolution = res.tv_sec + res.tv_nsec * 1e-9;
1059 else
1060 info->resolution = 1e-9;
1061 }
1062 return PyFloat_FromDouble(tp.tv_sec + tp.tv_nsec * 1e-9);
1063 }
1064#endif
1065
1066#if defined(HAVE_SYS_RESOURCE_H)
1067 if (getrusage(RUSAGE_SELF, &ru) == 0) {
1068 double total;
1069 total = ru.ru_utime.tv_sec + ru.ru_utime.tv_usec * 1e-6;
1070 total += ru.ru_stime.tv_sec + ru.ru_stime.tv_usec * 1e-6;
1071 if (info) {
1072 info->implementation = "getrusage(RUSAGE_SELF)";
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001073 info->monotonic = 1;
1074 info->adjusted = 0;
Victor Stinnerec895392012-04-29 02:41:27 +02001075 info->resolution = 1e-6;
1076 }
1077 return PyFloat_FromDouble(total);
1078 }
1079#endif
1080
1081#ifdef HAVE_TIMES
1082 if (times(&t) != (clock_t)-1) {
1083 double total;
1084
1085 if (ticks_per_second == -1) {
1086#if defined(HAVE_SYSCONF) && defined(_SC_CLK_TCK)
1087 ticks_per_second = sysconf(_SC_CLK_TCK);
1088 if (ticks_per_second < 1)
1089 ticks_per_second = -1;
1090#elif defined(HZ)
1091 ticks_per_second = HZ;
1092#else
1093 ticks_per_second = 60; /* magic fallback value; may be bogus */
1094#endif
1095 }
1096
1097 if (ticks_per_second != -1) {
1098 total = (double)t.tms_utime / ticks_per_second;
1099 total += (double)t.tms_stime / ticks_per_second;
1100 if (info) {
1101 info->implementation = "times()";
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001102 info->monotonic = 1;
1103 info->adjusted = 0;
Victor Stinnerec895392012-04-29 02:41:27 +02001104 info->resolution = 1.0 / ticks_per_second;
1105 }
1106 return PyFloat_FromDouble(total);
1107 }
1108 }
1109#endif
1110
1111 return floatclock(info);
1112#endif
1113}
1114
1115static PyObject *
1116time_process_time(PyObject *self, PyObject *unused)
1117{
1118 return py_process_time(NULL);
1119}
1120
1121PyDoc_STRVAR(process_time_doc,
1122"process_time() -> float\n\
1123\n\
1124Process time for profiling: sum of the kernel and user-space CPU time.");
1125
1126
1127static PyTypeObject ClockInfoType;
1128
1129PyDoc_STRVAR(ClockInfo_docstring,
1130 "Clock information");
1131
1132static PyStructSequence_Field ClockInfo_fields[] = {
1133 {"implementation", "name of the underlying C function "
1134 "used to get the clock value"},
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001135 {"monotonic", "True if the clock cannot go backward, False otherwise"},
1136 {"adjusted", "True if the clock can be adjusted "
Victor Stinnerec895392012-04-29 02:41:27 +02001137 "(e.g. by a NTP daemon), False otherwise"},
1138 {"resolution", "resolution of the clock in seconds"},
1139 {NULL, NULL}
1140};
1141
1142static PyStructSequence_Desc ClockInfo_desc = {
1143 "time.clock_info",
1144 ClockInfo_docstring,
1145 ClockInfo_fields,
1146 4,
1147};
1148
1149static PyObject *
1150time_get_clock_info(PyObject *self, PyObject *args)
1151{
1152 char *name;
1153 PyObject *obj;
1154 _Py_clock_info_t info;
1155 PyObject *result;
1156
1157 if (!PyArg_ParseTuple(args, "s:get_clock_info", &name))
1158 return NULL;
1159
1160#ifdef Py_DEBUG
1161 info.implementation = NULL;
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001162 info.monotonic = -1;
1163 info.adjusted = -1;
Victor Stinnerec895392012-04-29 02:41:27 +02001164 info.resolution = -1.0;
1165#else
1166 info.implementation = "";
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001167 info.monotonic = 0;
1168 info.adjusted = 0;
Victor Stinnerec895392012-04-29 02:41:27 +02001169 info.resolution = 1.0;
1170#endif
1171
1172 if (strcmp(name, "time") == 0)
1173 obj = floattime(&info);
1174#ifdef PYCLOCK
1175 else if (strcmp(name, "clock") == 0)
1176 obj = pyclock(&info);
1177#endif
1178#ifdef PYMONOTONIC
1179 else if (strcmp(name, "monotonic") == 0)
1180 obj = pymonotonic(&info);
1181#endif
1182 else if (strcmp(name, "perf_counter") == 0)
1183 obj = perf_counter(&info);
1184 else if (strcmp(name, "process_time") == 0)
1185 obj = py_process_time(&info);
1186 else {
1187 PyErr_SetString(PyExc_ValueError, "unknown clock");
1188 return NULL;
1189 }
1190 if (obj == NULL)
1191 return NULL;
1192 Py_DECREF(obj);
1193
1194 result = PyStructSequence_New(&ClockInfoType);
1195 if (result == NULL)
1196 return NULL;
1197
1198 assert(info.implementation != NULL);
1199 obj = PyUnicode_FromString(info.implementation);
1200 if (obj == NULL)
1201 goto error;
1202 PyStructSequence_SET_ITEM(result, 0, obj);
1203
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001204 assert(info.monotonic != -1);
1205 obj = PyBool_FromLong(info.monotonic);
Victor Stinnerec895392012-04-29 02:41:27 +02001206 if (obj == NULL)
1207 goto error;
1208 PyStructSequence_SET_ITEM(result, 1, obj);
1209
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001210 assert(info.adjusted != -1);
1211 obj = PyBool_FromLong(info.adjusted);
Victor Stinnerec895392012-04-29 02:41:27 +02001212 if (obj == NULL)
1213 goto error;
1214 PyStructSequence_SET_ITEM(result, 2, obj);
1215
1216 assert(info.resolution > 0.0);
1217 assert(info.resolution <= 1.0);
1218 obj = PyFloat_FromDouble(info.resolution);
1219 if (obj == NULL)
1220 goto error;
1221 PyStructSequence_SET_ITEM(result, 3, obj);
1222
1223 return result;
1224
1225error:
1226 Py_DECREF(result);
1227 return NULL;
1228}
1229
1230PyDoc_STRVAR(get_clock_info_doc,
1231"get_clock_info(name: str) -> dict\n\
1232\n\
1233Get information of the specified clock.");
Victor Stinner8b302012012-02-07 23:29:46 +01001234
Martin v. Löwisd218dc12008-04-07 03:17:54 +00001235static void
Martin v. Löwis1a214512008-06-11 05:26:20 +00001236PyInit_timezone(PyObject *m) {
1237 /* This code moved from PyInit_time wholesale to allow calling it from
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001238 time_tzset. In the future, some parts of it can be moved back
1239 (for platforms that don't HAVE_WORKING_TZSET, when we know what they
1240 are), and the extraneous calls to tzset(3) should be removed.
1241 I haven't done this yet, as I don't want to change this code as
1242 little as possible when introducing the time.tzset and time.tzsetwall
1243 methods. This should simply be a method of doing the following once,
1244 at the top of this function and removing the call to tzset() from
1245 time_tzset():
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001246
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001247 #ifdef HAVE_TZSET
1248 tzset()
1249 #endif
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001250
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001251 And I'm lazy and hate C so nyer.
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001252 */
Guido van Rossum10b164a2001-09-25 13:59:01 +00001253#if defined(HAVE_TZNAME) && !defined(__GLIBC__) && !defined(__CYGWIN__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001254 PyObject *otz0, *otz1;
1255 tzset();
Guido van Rossum26452411998-09-28 22:07:11 +00001256#ifdef PYOS_OS2
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001257 PyModule_AddIntConstant(m, "timezone", _timezone);
Guido van Rossum26452411998-09-28 22:07:11 +00001258#else /* !PYOS_OS2 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001259 PyModule_AddIntConstant(m, "timezone", timezone);
Guido van Rossum26452411998-09-28 22:07:11 +00001260#endif /* PYOS_OS2 */
Guido van Rossumb6775db1994-08-01 11:34:53 +00001261#ifdef HAVE_ALTZONE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001262 PyModule_AddIntConstant(m, "altzone", altzone);
Guido van Rossumb6775db1994-08-01 11:34:53 +00001263#else
Guido van Rossum26452411998-09-28 22:07:11 +00001264#ifdef PYOS_OS2
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001265 PyModule_AddIntConstant(m, "altzone", _timezone-3600);
Guido van Rossum26452411998-09-28 22:07:11 +00001266#else /* !PYOS_OS2 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001267 PyModule_AddIntConstant(m, "altzone", timezone-3600);
Guido van Rossum26452411998-09-28 22:07:11 +00001268#endif /* PYOS_OS2 */
Guido van Rossumb6775db1994-08-01 11:34:53 +00001269#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001270 PyModule_AddIntConstant(m, "daylight", daylight);
Victor Stinner1b579672011-12-17 05:47:23 +01001271 otz0 = PyUnicode_DecodeLocale(tzname[0], "surrogateescape");
1272 otz1 = PyUnicode_DecodeLocale(tzname[1], "surrogateescape");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001273 PyModule_AddObject(m, "tzname", Py_BuildValue("(NN)", otz0, otz1));
Guido van Rossum10b164a2001-09-25 13:59:01 +00001274#else /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/
Martin v. Löwis60a5d722002-10-16 20:28:25 +00001275#ifdef HAVE_STRUCT_TM_TM_ZONE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001276 {
Guido van Rossum234f9421993-06-17 12:35:49 +00001277#define YEAR ((time_t)((365 * 24 + 6) * 3600))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001278 time_t t;
1279 struct tm *p;
1280 long janzone, julyzone;
1281 char janname[10], julyname[10];
1282 t = (time((time_t *)0) / YEAR) * YEAR;
1283 p = localtime(&t);
1284 janzone = -p->tm_gmtoff;
1285 strncpy(janname, p->tm_zone ? p->tm_zone : " ", 9);
1286 janname[9] = '\0';
1287 t += YEAR/2;
1288 p = localtime(&t);
1289 julyzone = -p->tm_gmtoff;
1290 strncpy(julyname, p->tm_zone ? p->tm_zone : " ", 9);
1291 julyname[9] = '\0';
Guido van Rossum10b164a2001-09-25 13:59:01 +00001292
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001293 if( janzone < julyzone ) {
1294 /* DST is reversed in the southern hemisphere */
1295 PyModule_AddIntConstant(m, "timezone", julyzone);
1296 PyModule_AddIntConstant(m, "altzone", janzone);
1297 PyModule_AddIntConstant(m, "daylight",
1298 janzone != julyzone);
1299 PyModule_AddObject(m, "tzname",
1300 Py_BuildValue("(zz)",
1301 julyname, janname));
1302 } else {
1303 PyModule_AddIntConstant(m, "timezone", janzone);
1304 PyModule_AddIntConstant(m, "altzone", julyzone);
1305 PyModule_AddIntConstant(m, "daylight",
1306 janzone != julyzone);
1307 PyModule_AddObject(m, "tzname",
1308 Py_BuildValue("(zz)",
1309 janname, julyname));
1310 }
1311 }
Guido van Rossume6a4b7b1997-10-08 15:27:56 +00001312#else
Martin v. Löwis60a5d722002-10-16 20:28:25 +00001313#endif /* HAVE_STRUCT_TM_TM_ZONE */
Tim Peters26ae7cd2001-03-20 03:26:49 +00001314#ifdef __CYGWIN__
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001315 tzset();
1316 PyModule_AddIntConstant(m, "timezone", _timezone);
1317 PyModule_AddIntConstant(m, "altzone", _timezone-3600);
1318 PyModule_AddIntConstant(m, "daylight", _daylight);
1319 PyModule_AddObject(m, "tzname",
1320 Py_BuildValue("(zz)", _tzname[0], _tzname[1]));
Tim Peters26ae7cd2001-03-20 03:26:49 +00001321#endif /* __CYGWIN__ */
Guido van Rossum10b164a2001-09-25 13:59:01 +00001322#endif /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/
Victor Stinnere0be4232011-10-25 13:06:09 +02001323
Victor Stinnerec895392012-04-29 02:41:27 +02001324#if defined(HAVE_CLOCK_GETTIME)
Victor Stinnere0be4232011-10-25 13:06:09 +02001325 PyModule_AddIntMacro(m, CLOCK_REALTIME);
Victor Stinnere0be4232011-10-25 13:06:09 +02001326#ifdef CLOCK_MONOTONIC
1327 PyModule_AddIntMacro(m, CLOCK_MONOTONIC);
1328#endif
1329#ifdef CLOCK_MONOTONIC_RAW
1330 PyModule_AddIntMacro(m, CLOCK_MONOTONIC_RAW);
1331#endif
Victor Stinner1470f352012-04-03 00:31:17 +02001332#ifdef CLOCK_HIGHRES
1333 PyModule_AddIntMacro(m, CLOCK_HIGHRES);
1334#endif
Victor Stinnere0be4232011-10-25 13:06:09 +02001335#ifdef CLOCK_PROCESS_CPUTIME_ID
1336 PyModule_AddIntMacro(m, CLOCK_PROCESS_CPUTIME_ID);
1337#endif
1338#ifdef CLOCK_THREAD_CPUTIME_ID
1339 PyModule_AddIntMacro(m, CLOCK_THREAD_CPUTIME_ID);
1340#endif
1341#endif /* HAVE_CLOCK_GETTIME */
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001342}
1343
1344
1345static PyMethodDef time_methods[] = {
Victor Stinner4195b5c2012-02-08 23:03:19 +01001346 {"time", time_time, METH_NOARGS, time_doc},
Victor Stinnerec895392012-04-29 02:41:27 +02001347#ifdef PYCLOCK
Victor Stinner4195b5c2012-02-08 23:03:19 +01001348 {"clock", time_clock, METH_NOARGS, clock_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001349#endif
Victor Stinnere0be4232011-10-25 13:06:09 +02001350#ifdef HAVE_CLOCK_GETTIME
Victor Stinner4195b5c2012-02-08 23:03:19 +01001351 {"clock_gettime", time_clock_gettime, METH_VARARGS, clock_gettime_doc},
Victor Stinner30d79472012-04-03 00:45:07 +02001352 {"clock_settime", time_clock_settime, METH_VARARGS, clock_settime_doc},
Victor Stinner4195b5c2012-02-08 23:03:19 +01001353 {"clock_getres", time_clock_getres, METH_VARARGS, clock_getres_doc},
Victor Stinnere0be4232011-10-25 13:06:09 +02001354#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001355 {"sleep", time_sleep, METH_VARARGS, sleep_doc},
1356 {"gmtime", time_gmtime, METH_VARARGS, gmtime_doc},
1357 {"localtime", time_localtime, METH_VARARGS, localtime_doc},
1358 {"asctime", time_asctime, METH_VARARGS, asctime_doc},
1359 {"ctime", time_ctime, METH_VARARGS, ctime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001360#ifdef HAVE_MKTIME
Victor Stinner4195b5c2012-02-08 23:03:19 +01001361 {"mktime", time_mktime, METH_O, mktime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001362#endif
1363#ifdef HAVE_STRFTIME
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001364 {"strftime", time_strftime, METH_VARARGS, strftime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001365#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001366 {"strptime", time_strptime, METH_VARARGS, strptime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001367#ifdef HAVE_WORKING_TZSET
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001368 {"tzset", time_tzset, METH_NOARGS, tzset_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001369#endif
Victor Stinnerec895392012-04-29 02:41:27 +02001370#ifdef PYMONOTONIC
1371 {"monotonic", time_monotonic, METH_NOARGS, monotonic_doc},
1372#endif
1373 {"process_time", time_process_time, METH_NOARGS, process_time_doc},
1374 {"perf_counter", time_perf_counter, METH_NOARGS, perf_counter_doc},
1375 {"get_clock_info", time_get_clock_info, METH_VARARGS, get_clock_info_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001376 {NULL, NULL} /* sentinel */
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001377};
1378
1379
1380PyDoc_STRVAR(module_doc,
1381"This module provides various functions to manipulate time values.\n\
1382\n\
1383There are two standard representations of time. One is the number\n\
1384of seconds since the Epoch, in UTC (a.k.a. GMT). It may be an integer\n\
1385or a floating point number (to represent fractions of seconds).\n\
1386The Epoch is system-defined; on Unix, it is generally January 1st, 1970.\n\
1387The actual value can be retrieved by calling gmtime(0).\n\
1388\n\
1389The other representation is a tuple of 9 integers giving local time.\n\
1390The tuple items are:\n\
Alexander Belopolsky03163ac2011-05-02 12:20:52 -04001391 year (including century, e.g. 1998)\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001392 month (1-12)\n\
1393 day (1-31)\n\
1394 hours (0-23)\n\
1395 minutes (0-59)\n\
1396 seconds (0-59)\n\
1397 weekday (0-6, Monday is 0)\n\
1398 Julian day (day in the year, 1-366)\n\
1399 DST (Daylight Savings Time) flag (-1, 0 or 1)\n\
1400If the DST flag is 0, the time is given in the regular time zone;\n\
1401if it is 1, the time is given in the DST time zone;\n\
1402if it is -1, mktime() should guess based on the date and time.\n\
1403\n\
1404Variables:\n\
1405\n\
1406timezone -- difference in seconds between UTC and local standard time\n\
1407altzone -- difference in seconds between UTC and local DST time\n\
1408daylight -- whether local time should reflect DST\n\
1409tzname -- tuple of (standard time zone name, DST time zone name)\n\
1410\n\
1411Functions:\n\
1412\n\
1413time() -- return current time in seconds since the Epoch as a float\n\
1414clock() -- return CPU time since process start as a float\n\
1415sleep() -- delay for a number of seconds given as a float\n\
1416gmtime() -- convert seconds since Epoch to UTC tuple\n\
1417localtime() -- convert seconds since Epoch to local time tuple\n\
1418asctime() -- convert time tuple to string\n\
1419ctime() -- convert time in seconds to string\n\
1420mktime() -- convert local time tuple to seconds since Epoch\n\
1421strftime() -- convert time tuple to string according to format specification\n\
1422strptime() -- parse string to time tuple according to format specification\n\
1423tzset() -- change the local timezone");
1424
1425
Martin v. Löwis1a214512008-06-11 05:26:20 +00001426
1427static struct PyModuleDef timemodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001428 PyModuleDef_HEAD_INIT,
1429 "time",
1430 module_doc,
1431 -1,
1432 time_methods,
1433 NULL,
1434 NULL,
1435 NULL,
1436 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00001437};
1438
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001439PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00001440PyInit_time(void)
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001441{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001442 PyObject *m;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001443 m = PyModule_Create(&timemodule);
1444 if (m == NULL)
1445 return NULL;
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001446
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001447 /* Set, or reset, module variables like time.timezone */
1448 PyInit_timezone(m);
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001449
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001450 if (!initialized) {
1451 PyStructSequence_InitType(&StructTimeType,
1452 &struct_time_type_desc);
Victor Stinnerec895392012-04-29 02:41:27 +02001453
1454 /* initialize ClockInfoType */
1455 PyStructSequence_InitType(&ClockInfoType, &ClockInfo_desc);
1456 Py_INCREF(&ClockInfoType);
1457 PyModule_AddObject(m, "clock_info", (PyObject*)&ClockInfoType);
1458
1459#ifdef MS_WINDOWS
1460 winver.dwOSVersionInfoSize = sizeof(winver);
1461 if (!GetVersionEx((OSVERSIONINFO*)&winver)) {
1462 Py_DECREF(m);
1463 PyErr_SetFromWindowsErr(0);
1464 return NULL;
1465 }
1466#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001467 }
1468 Py_INCREF(&StructTimeType);
1469 PyModule_AddObject(m, "struct_time", (PyObject*) &StructTimeType);
1470 initialized = 1;
1471 return m;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001472}
1473
Victor Stinner071eca32012-03-15 01:17:09 +01001474static PyObject*
Victor Stinnerec895392012-04-29 02:41:27 +02001475floattime(_Py_clock_info_t *info)
Victor Stinner4195b5c2012-02-08 23:03:19 +01001476{
1477 _PyTime_timeval t;
Victor Stinnerad95c2d2012-03-28 02:54:15 +02001478#ifdef HAVE_CLOCK_GETTIME
1479 struct timespec tp;
1480 int ret;
1481
1482 /* _PyTime_gettimeofday() does not use clock_gettime()
1483 because it would require to link Python to the rt (real-time)
1484 library, at least on Linux */
1485 ret = clock_gettime(CLOCK_REALTIME, &tp);
Victor Stinnerec895392012-04-29 02:41:27 +02001486 if (ret == 0) {
1487 if (info) {
1488 struct timespec res;
1489 info->implementation = "clock_gettime(CLOCK_REALTIME)";
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001490 info->monotonic = 0;
1491 info->adjusted = 1;
Victor Stinnerec895392012-04-29 02:41:27 +02001492 if (clock_getres(CLOCK_REALTIME, &res) == 0)
1493 info->resolution = res.tv_sec + res.tv_nsec * 1e-9;
1494 else
1495 info->resolution = 1e-9;
1496 }
Victor Stinnerad95c2d2012-03-28 02:54:15 +02001497 return PyFloat_FromDouble(tp.tv_sec + tp.tv_nsec * 1e-9);
Victor Stinnerec895392012-04-29 02:41:27 +02001498 }
Victor Stinnerad95c2d2012-03-28 02:54:15 +02001499#endif
Victor Stinnerec895392012-04-29 02:41:27 +02001500 _PyTime_gettimeofday_info(&t, info);
Victor Stinner70b2e1e2012-03-26 22:08:02 +02001501 return PyFloat_FromDouble((double)t.tv_sec + t.tv_usec * 1e-6);
Victor Stinner4195b5c2012-02-08 23:03:19 +01001502}
1503
1504
Guido van Rossumb6775db1994-08-01 11:34:53 +00001505/* Implement floatsleep() for various platforms.
1506 When interrupted (or when another error occurs), return -1 and
1507 set an exception; else return 0. */
1508
1509static int
Guido van Rossuma320fd31995-03-09 12:14:15 +00001510floatsleep(double secs)
Guido van Rossum426035c1991-02-19 12:27:35 +00001511{
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001512/* XXX Should test for MS_WINDOWS first! */
Skip Montanaroeb33e5a2007-08-17 12:57:41 +00001513#if defined(HAVE_SELECT) && !defined(__EMX__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001514 struct timeval t;
1515 double frac;
Victor Stinner48b1ce52011-07-01 13:50:09 +02001516 int err;
1517
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001518 frac = fmod(secs, 1.0);
1519 secs = floor(secs);
1520 t.tv_sec = (long)secs;
1521 t.tv_usec = (long)(frac*1000000.0);
1522 Py_BEGIN_ALLOW_THREADS
Victor Stinner48b1ce52011-07-01 13:50:09 +02001523 err = select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &t);
1524 Py_END_ALLOW_THREADS
1525 if (err != 0) {
Guido van Rossum09cbb011999-11-08 15:32:27 +00001526#ifdef EINTR
Victor Stinner48b1ce52011-07-01 13:50:09 +02001527 if (errno == EINTR) {
1528 if (PyErr_CheckSignals())
1529 return -1;
1530 }
1531 else
Guido van Rossum09cbb011999-11-08 15:32:27 +00001532#endif
Victor Stinner48b1ce52011-07-01 13:50:09 +02001533 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001534 PyErr_SetFromErrno(PyExc_IOError);
1535 return -1;
1536 }
1537 }
Martin v. Löwis02af9642002-01-16 11:04:06 +00001538#elif defined(__WATCOMC__) && !defined(__QNX__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001539 /* XXX Can't interrupt this sleep */
1540 Py_BEGIN_ALLOW_THREADS
1541 delay((int)(secs * 1000 + 0.5)); /* delay() uses milliseconds */
1542 Py_END_ALLOW_THREADS
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001543#elif defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001544 {
1545 double millisecs = secs * 1000.0;
1546 unsigned long ul_millis;
Tim Peters513a1cd2003-01-19 04:54:58 +00001547
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001548 if (millisecs > (double)ULONG_MAX) {
1549 PyErr_SetString(PyExc_OverflowError,
1550 "sleep length is too large");
1551 return -1;
1552 }
1553 Py_BEGIN_ALLOW_THREADS
1554 /* Allow sleep(0) to maintain win32 semantics, and as decreed
1555 * by Guido, only the main thread can be interrupted.
1556 */
1557 ul_millis = (unsigned long)millisecs;
Antoine Pitrou6dd381e2011-11-21 21:26:56 +01001558 if (ul_millis == 0 || !_PyOS_IsMainThread())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001559 Sleep(ul_millis);
1560 else {
1561 DWORD rc;
Antoine Pitrou6dd381e2011-11-21 21:26:56 +01001562 HANDLE hInterruptEvent = _PyOS_SigintEvent();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001563 ResetEvent(hInterruptEvent);
1564 rc = WaitForSingleObject(hInterruptEvent, ul_millis);
1565 if (rc == WAIT_OBJECT_0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001566 Py_BLOCK_THREADS
1567 errno = EINTR;
1568 PyErr_SetFromErrno(PyExc_IOError);
1569 return -1;
1570 }
1571 }
1572 Py_END_ALLOW_THREADS
1573 }
Martin v. Löwis02af9642002-01-16 11:04:06 +00001574#elif defined(PYOS_OS2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001575 /* This Sleep *IS* Interruptable by Exceptions */
1576 Py_BEGIN_ALLOW_THREADS
1577 if (DosSleep(secs * 1000) != NO_ERROR) {
1578 Py_BLOCK_THREADS
1579 PyErr_SetFromErrno(PyExc_IOError);
1580 return -1;
1581 }
1582 Py_END_ALLOW_THREADS
Martin v. Löwis02af9642002-01-16 11:04:06 +00001583#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001584 /* XXX Can't interrupt this sleep */
1585 Py_BEGIN_ALLOW_THREADS
1586 sleep((int)secs);
1587 Py_END_ALLOW_THREADS
Martin v. Löwis02af9642002-01-16 11:04:06 +00001588#endif
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001589
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001590 return 0;
Guido van Rossum80c9d881991-04-16 08:47:51 +00001591}