blob: 1f07bcc90fdd25a6fd4805253be969912d49768f [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 */
Tim Petersdbd9ba62000-07-09 03:09:57 +000034static int floatsleep(double);
Victor Stinnerec895392012-04-29 02:41:27 +020035static PyObject* floattime(_Py_clock_info_t *info);
36
37#ifdef MS_WINDOWS
38static OSVERSIONINFOEX winver;
39#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000040
Barry Warsaw9a2a8a81996-12-06 23:32:14 +000041static PyObject *
Victor Stinner4195b5c2012-02-08 23:03:19 +010042time_time(PyObject *self, PyObject *unused)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000043{
Victor Stinnerec895392012-04-29 02:41:27 +020044 return floattime(NULL);
Guido van Rossumb6775db1994-08-01 11:34:53 +000045}
46
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000047PyDoc_STRVAR(time_doc,
Victor Stinner4195b5c2012-02-08 23:03:19 +010048"time() -> floating point number\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +000049\n\
50Return the current time in seconds since the Epoch.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000051Fractions of a second may be present if the system clock provides them.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +000052
Victor Stinner85fdfa82012-01-27 00:38:48 +010053#if defined(HAVE_CLOCK)
54
55#ifndef CLOCKS_PER_SEC
56#ifdef CLK_TCK
57#define CLOCKS_PER_SEC CLK_TCK
58#else
59#define CLOCKS_PER_SEC 1000000
60#endif
61#endif
62
Victor Stinner4195b5c2012-02-08 23:03:19 +010063static PyObject *
Victor Stinnerec895392012-04-29 02:41:27 +020064floatclock(_Py_clock_info_t *info)
Victor Stinner85fdfa82012-01-27 00:38:48 +010065{
Victor Stinner4195b5c2012-02-08 23:03:19 +010066 clock_t value;
67 value = clock();
68 if (value == (clock_t)-1) {
Victor Stinner85fdfa82012-01-27 00:38:48 +010069 PyErr_SetString(PyExc_RuntimeError,
70 "the processor time used is not available "
71 "or its value cannot be represented");
Victor Stinner4195b5c2012-02-08 23:03:19 +010072 return NULL;
Victor Stinner85fdfa82012-01-27 00:38:48 +010073 }
Victor Stinnerec895392012-04-29 02:41:27 +020074 if (info) {
75 info->implementation = "clock()";
76 info->resolution = 1.0 / (double)CLOCKS_PER_SEC;
Benjamin Peterson49a69e42012-05-01 09:38:34 -040077 info->monotonic = 1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +020078 info->adjustable = 0;
Victor Stinnerec895392012-04-29 02:41:27 +020079 }
Victor Stinner4195b5c2012-02-08 23:03:19 +010080 return PyFloat_FromDouble((double)value / CLOCKS_PER_SEC);
Victor Stinner85fdfa82012-01-27 00:38:48 +010081}
82#endif /* HAVE_CLOCK */
83
Victor Stinnerf427a142014-10-22 12:33:23 +020084#ifdef MS_WINDOWS
Victor Stinnerec895392012-04-29 02:41:27 +020085#define WIN32_PERF_COUNTER
Victor Stinner9122fdd2011-07-04 13:55:40 +020086/* Win32 has better clock replacement; we have our own version, due to Mark
87 Hammond and Tim Peters */
Victor Stinner54884492014-08-29 16:51:33 +020088static PyObject*
89win_perf_counter(_Py_clock_info_t *info)
Guido van Rossum3917c221997-04-02 05:35:28 +000090{
Victor Stinner8b302012012-02-07 23:29:46 +010091 static LONGLONG cpu_frequency = 0;
Victor Stinner4195b5c2012-02-08 23:03:19 +010092 static LONGLONG ctrStart;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000093 LARGE_INTEGER now;
Victor Stinner4195b5c2012-02-08 23:03:19 +010094 double diff;
Guido van Rossum3917c221997-04-02 05:35:28 +000095
Victor Stinner8b302012012-02-07 23:29:46 +010096 if (cpu_frequency == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000097 LARGE_INTEGER freq;
Victor Stinner8b302012012-02-07 23:29:46 +010098 QueryPerformanceCounter(&now);
Victor Stinner4195b5c2012-02-08 23:03:19 +010099 ctrStart = now.QuadPart;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000100 if (!QueryPerformanceFrequency(&freq) || freq.QuadPart == 0) {
Victor Stinner54884492014-08-29 16:51:33 +0200101 PyErr_SetFromWindowsErr(0);
102 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000103 }
Victor Stinner8b302012012-02-07 23:29:46 +0100104 cpu_frequency = freq.QuadPart;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000105 }
106 QueryPerformanceCounter(&now);
Victor Stinner4195b5c2012-02-08 23:03:19 +0100107 diff = (double)(now.QuadPart - ctrStart);
Victor Stinnerec895392012-04-29 02:41:27 +0200108 if (info) {
109 info->implementation = "QueryPerformanceCounter()";
110 info->resolution = 1.0 / (double)cpu_frequency;
Benjamin Peterson49a69e42012-05-01 09:38:34 -0400111 info->monotonic = 1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +0200112 info->adjustable = 0;
Victor Stinnerec895392012-04-29 02:41:27 +0200113 }
Victor Stinner54884492014-08-29 16:51:33 +0200114 return PyFloat_FromDouble(diff / (double)cpu_frequency);
Guido van Rossum3917c221997-04-02 05:35:28 +0000115}
Victor Stinnerf427a142014-10-22 12:33:23 +0200116#endif /* MS_WINDOWS */
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000117
Victor Stinnerec895392012-04-29 02:41:27 +0200118#if defined(WIN32_PERF_COUNTER) || defined(HAVE_CLOCK)
119#define PYCLOCK
120static PyObject*
121pyclock(_Py_clock_info_t *info)
122{
123#ifdef WIN32_PERF_COUNTER
Victor Stinner54884492014-08-29 16:51:33 +0200124 return win_perf_counter(info);
125#else
Victor Stinnerec895392012-04-29 02:41:27 +0200126 return floatclock(info);
Victor Stinner54884492014-08-29 16:51:33 +0200127#endif
Victor Stinnerec895392012-04-29 02:41:27 +0200128}
129
Victor Stinner9122fdd2011-07-04 13:55:40 +0200130static PyObject *
Victor Stinner4195b5c2012-02-08 23:03:19 +0100131time_clock(PyObject *self, PyObject *unused)
Victor Stinner9122fdd2011-07-04 13:55:40 +0200132{
Victor Stinnerec895392012-04-29 02:41:27 +0200133 return pyclock(NULL);
Victor Stinner9122fdd2011-07-04 13:55:40 +0200134}
Victor Stinner9122fdd2011-07-04 13:55:40 +0200135
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000136PyDoc_STRVAR(clock_doc,
Victor Stinner4195b5c2012-02-08 23:03:19 +0100137"clock() -> floating point number\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000138\n\
139Return the CPU time or real time since the start of the process or since\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000140the first call to clock(). This has as much precision as the system\n\
141records.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000142#endif
143
Victor Stinnere0be4232011-10-25 13:06:09 +0200144#ifdef HAVE_CLOCK_GETTIME
145static PyObject *
Victor Stinner4195b5c2012-02-08 23:03:19 +0100146time_clock_gettime(PyObject *self, PyObject *args)
Victor Stinnere0be4232011-10-25 13:06:09 +0200147{
148 int ret;
Victor Stinnerb8d01692012-04-13 23:44:05 +0200149 int clk_id;
Victor Stinnere0be4232011-10-25 13:06:09 +0200150 struct timespec tp;
151
Victor Stinner4195b5c2012-02-08 23:03:19 +0100152 if (!PyArg_ParseTuple(args, "i:clock_gettime", &clk_id))
Victor Stinnere0be4232011-10-25 13:06:09 +0200153 return NULL;
154
155 ret = clock_gettime((clockid_t)clk_id, &tp);
Antoine Pitrou2c085602012-01-18 01:41:44 +0100156 if (ret != 0) {
Victor Stinnera734af32014-07-31 13:07:17 +0200157 PyErr_SetFromErrno(PyExc_OSError);
Antoine Pitrou2c085602012-01-18 01:41:44 +0100158 return NULL;
159 }
Victor Stinner4195b5c2012-02-08 23:03:19 +0100160 return PyFloat_FromDouble(tp.tv_sec + tp.tv_nsec * 1e-9);
Victor Stinnere0be4232011-10-25 13:06:09 +0200161}
162
163PyDoc_STRVAR(clock_gettime_doc,
Victor Stinner4195b5c2012-02-08 23:03:19 +0100164"clock_gettime(clk_id) -> floating point number\n\
Victor Stinnere0be4232011-10-25 13:06:09 +0200165\n\
166Return the time of the specified clock clk_id.");
Victor Stinner30d79472012-04-03 00:45:07 +0200167
168static PyObject *
169time_clock_settime(PyObject *self, PyObject *args)
170{
Victor Stinnerb8d01692012-04-13 23:44:05 +0200171 int clk_id;
Victor Stinner30d79472012-04-03 00:45:07 +0200172 PyObject *obj;
Antoine Pitroucf8a1e52013-04-17 22:06:44 +0200173 time_t tv_sec;
174 long tv_nsec;
Victor Stinner30d79472012-04-03 00:45:07 +0200175 struct timespec tp;
176 int ret;
177
178 if (!PyArg_ParseTuple(args, "iO:clock_settime", &clk_id, &obj))
179 return NULL;
180
Victor Stinner3c1b3792014-02-17 00:02:43 +0100181 if (_PyTime_ObjectToTimespec(obj, &tv_sec, &tv_nsec, _PyTime_ROUND_DOWN) == -1)
Victor Stinner30d79472012-04-03 00:45:07 +0200182 return NULL;
Antoine Pitroucf8a1e52013-04-17 22:06:44 +0200183 tp.tv_sec = tv_sec;
184 tp.tv_nsec = tv_nsec;
Victor Stinner30d79472012-04-03 00:45:07 +0200185
186 ret = clock_settime((clockid_t)clk_id, &tp);
187 if (ret != 0) {
Victor Stinnera734af32014-07-31 13:07:17 +0200188 PyErr_SetFromErrno(PyExc_OSError);
Victor Stinner30d79472012-04-03 00:45:07 +0200189 return NULL;
190 }
191 Py_RETURN_NONE;
192}
193
194PyDoc_STRVAR(clock_settime_doc,
195"clock_settime(clk_id, time)\n\
196\n\
197Set the time of the specified clock clk_id.");
Victor Stinnere0be4232011-10-25 13:06:09 +0200198
Victor Stinnere0be4232011-10-25 13:06:09 +0200199static PyObject *
Victor Stinner4195b5c2012-02-08 23:03:19 +0100200time_clock_getres(PyObject *self, PyObject *args)
Victor Stinnere0be4232011-10-25 13:06:09 +0200201{
202 int ret;
Victor Stinnerb8d01692012-04-13 23:44:05 +0200203 int clk_id;
Victor Stinnere0be4232011-10-25 13:06:09 +0200204 struct timespec tp;
205
Victor Stinner4195b5c2012-02-08 23:03:19 +0100206 if (!PyArg_ParseTuple(args, "i:clock_getres", &clk_id))
Victor Stinnere0be4232011-10-25 13:06:09 +0200207 return NULL;
208
209 ret = clock_getres((clockid_t)clk_id, &tp);
Antoine Pitrou2c085602012-01-18 01:41:44 +0100210 if (ret != 0) {
Victor Stinnera734af32014-07-31 13:07:17 +0200211 PyErr_SetFromErrno(PyExc_OSError);
Antoine Pitrou2c085602012-01-18 01:41:44 +0100212 return NULL;
213 }
Victor Stinner4195b5c2012-02-08 23:03:19 +0100214
215 return PyFloat_FromDouble(tp.tv_sec + tp.tv_nsec * 1e-9);
Victor Stinnere0be4232011-10-25 13:06:09 +0200216}
217
218PyDoc_STRVAR(clock_getres_doc,
Victor Stinner4195b5c2012-02-08 23:03:19 +0100219"clock_getres(clk_id) -> floating point number\n\
Victor Stinnere0be4232011-10-25 13:06:09 +0200220\n\
221Return the resolution (precision) of the specified clock clk_id.");
Victor Stinnerb8d01692012-04-13 23:44:05 +0200222#endif /* HAVE_CLOCK_GETTIME */
Victor Stinnere0be4232011-10-25 13:06:09 +0200223
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000224static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000225time_sleep(PyObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000226{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000227 double secs;
228 if (!PyArg_ParseTuple(args, "d:sleep", &secs))
229 return NULL;
Victor Stinner7f53a502011-07-05 22:00:25 +0200230 if (secs < 0) {
231 PyErr_SetString(PyExc_ValueError,
232 "sleep length must be non-negative");
233 return NULL;
234 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000235 if (floatsleep(secs) != 0)
236 return NULL;
237 Py_INCREF(Py_None);
238 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000239}
240
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000241PyDoc_STRVAR(sleep_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000242"sleep(seconds)\n\
243\n\
244Delay execution for a given number of seconds. The argument may be\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000245a floating point number for subsecond precision.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000246
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000247static PyStructSequence_Field struct_time_type_fields[] = {
Alexander Belopolsky69f3fd02010-06-05 15:04:51 +0000248 {"tm_year", "year, for example, 1993"},
249 {"tm_mon", "month of year, range [1, 12]"},
250 {"tm_mday", "day of month, range [1, 31]"},
251 {"tm_hour", "hours, range [0, 23]"},
252 {"tm_min", "minutes, range [0, 59]"},
253 {"tm_sec", "seconds, range [0, 61])"},
254 {"tm_wday", "day of week, range [0, 6], Monday is 0"},
255 {"tm_yday", "day of year, range [1, 366]"},
256 {"tm_isdst", "1 if summer time is in effect, 0 if not, and -1 if unknown"},
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400257#ifdef HAVE_STRUCT_TM_TM_ZONE
258 {"tm_zone", "abbreviation of timezone name"},
259 {"tm_gmtoff", "offset from UTC in seconds"},
260#endif /* HAVE_STRUCT_TM_TM_ZONE */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000261 {0}
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000262};
263
264static PyStructSequence_Desc struct_time_type_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000265 "time.struct_time",
Alexander Belopolsky69f3fd02010-06-05 15:04:51 +0000266 "The time value as returned by gmtime(), localtime(), and strptime(), and\n"
267 " accepted by asctime(), mktime() and strftime(). May be considered as a\n"
268 " sequence of 9 integers.\n\n"
269 " Note that several fields' values are not the same as those defined by\n"
270 " the C language standard for struct tm. For example, the value of the\n"
271 " field tm_year is the actual year, not year - 1900. See individual\n"
272 " fields' descriptions for details.",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000273 struct_time_type_fields,
274 9,
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000275};
Tim Peters9ad4b682002-02-13 05:14:18 +0000276
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000277static int initialized;
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000278static PyTypeObject StructTimeType;
279
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400280
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000281static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000282tmtotuple(struct tm *p)
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000283{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000284 PyObject *v = PyStructSequence_New(&StructTimeType);
285 if (v == NULL)
286 return NULL;
Tim Peters9ad4b682002-02-13 05:14:18 +0000287
Christian Heimes217cfd12007-12-02 14:31:20 +0000288#define SET(i,val) PyStructSequence_SET_ITEM(v, i, PyLong_FromLong((long) val))
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000289
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000290 SET(0, p->tm_year + 1900);
291 SET(1, p->tm_mon + 1); /* Want January == 1 */
292 SET(2, p->tm_mday);
293 SET(3, p->tm_hour);
294 SET(4, p->tm_min);
295 SET(5, p->tm_sec);
296 SET(6, (p->tm_wday + 6) % 7); /* Want Monday == 0 */
297 SET(7, p->tm_yday + 1); /* Want January, 1 == 1 */
298 SET(8, p->tm_isdst);
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400299#ifdef HAVE_STRUCT_TM_TM_ZONE
300 PyStructSequence_SET_ITEM(v, 9,
301 PyUnicode_DecodeLocale(p->tm_zone, "surrogateescape"));
302 SET(10, p->tm_gmtoff);
303#endif /* HAVE_STRUCT_TM_TM_ZONE */
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000304#undef SET
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000305 if (PyErr_Occurred()) {
306 Py_XDECREF(v);
307 return NULL;
308 }
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000310 return v;
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000311}
312
Fred Drakef901abd2004-08-03 17:58:55 +0000313/* Parse arg tuple that can contain an optional float-or-None value;
314 format needs to be "|O:name".
315 Returns non-zero on success (parallels PyArg_ParseTuple).
316*/
317static int
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100318parse_time_t_args(PyObject *args, char *format, time_t *pwhen)
Fred Drakef901abd2004-08-03 17:58:55 +0000319{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000320 PyObject *ot = NULL;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100321 time_t whent;
Fred Drakef901abd2004-08-03 17:58:55 +0000322
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000323 if (!PyArg_ParseTuple(args, format, &ot))
324 return 0;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100325 if (ot == NULL || ot == Py_None) {
326 whent = time(NULL);
327 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000328 else {
Victor Stinner3c1b3792014-02-17 00:02:43 +0100329 if (_PyTime_ObjectToTime_t(ot, &whent, _PyTime_ROUND_DOWN) == -1)
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100330 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000331 }
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100332 *pwhen = whent;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000333 return 1;
Fred Drakef901abd2004-08-03 17:58:55 +0000334}
335
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000336static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000337time_gmtime(PyObject *self, PyObject *args)
Guido van Rossum234f9421993-06-17 12:35:49 +0000338{
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100339 time_t when;
340 struct tm buf, *local;
341
342 if (!parse_time_t_args(args, "|O:gmtime", &when))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000343 return NULL;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100344
345 errno = 0;
346 local = gmtime(&when);
347 if (local == NULL) {
348#ifdef EINVAL
349 if (errno == 0)
350 errno = EINVAL;
351#endif
352 return PyErr_SetFromErrno(PyExc_OSError);
353 }
354 buf = *local;
355 return tmtotuple(&buf);
Guido van Rossum234f9421993-06-17 12:35:49 +0000356}
357
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000358PyDoc_STRVAR(gmtime_doc,
Christian Heimes9a371592007-12-28 14:08:13 +0000359"gmtime([seconds]) -> (tm_year, tm_mon, tm_mday, tm_hour, tm_min,\n\
Fred Drake193a3f62002-03-12 21:38:49 +0000360 tm_sec, tm_wday, tm_yday, tm_isdst)\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000361\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000362Convert seconds since the Epoch to a time tuple expressing UTC (a.k.a.\n\
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400363GMT). When 'seconds' is not passed in, convert the current time instead.\n\
364\n\
365If the platform supports the tm_gmtoff and tm_zone, they are available as\n\
366attributes only.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000367
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100368static int
369pylocaltime(time_t *timep, struct tm *result)
370{
371 struct tm *local;
372
373 assert (timep != NULL);
374 local = localtime(timep);
375 if (local == NULL) {
376 /* unconvertible time */
377#ifdef EINVAL
378 if (errno == 0)
379 errno = EINVAL;
380#endif
381 PyErr_SetFromErrno(PyExc_OSError);
382 return -1;
383 }
384 *result = *local;
385 return 0;
386}
387
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000388static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000389time_localtime(PyObject *self, PyObject *args)
Guido van Rossum234f9421993-06-17 12:35:49 +0000390{
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100391 time_t when;
392 struct tm buf;
393
394 if (!parse_time_t_args(args, "|O:localtime", &when))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000395 return NULL;
Alexander Belopolskyd9738242012-06-12 16:14:17 -0400396 if (pylocaltime(&when, &buf) == -1)
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100397 return NULL;
398 return tmtotuple(&buf);
Guido van Rossum234f9421993-06-17 12:35:49 +0000399}
400
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000401PyDoc_STRVAR(localtime_doc,
Christian Heimes9a371592007-12-28 14:08:13 +0000402"localtime([seconds]) -> (tm_year,tm_mon,tm_mday,tm_hour,tm_min,\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000403 tm_sec,tm_wday,tm_yday,tm_isdst)\n\
Martin v. Löwisb3cfc1d2001-12-02 12:27:43 +0000404\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000405Convert seconds since the Epoch to a time tuple expressing local time.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000406When 'seconds' is not passed in, convert the current time instead.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000407
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000408/* Convert 9-item tuple to tm structure. Return 1 on success, set
409 * an exception and return 0 on error.
410 */
Guido van Rossum9e90a671993-06-24 11:10:19 +0000411static int
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000412gettmarg(PyObject *args, struct tm *p)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000413{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000414 int y;
Guido van Rossumcfbaecc1998-08-25 14:51:12 +0000415
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000416 memset((void *) p, '\0', sizeof(struct tm));
Guido van Rossumb9081262007-08-25 03:14:09 +0000417
Alexander Belopolsky610e5442011-01-06 21:57:06 +0000418 if (!PyTuple_Check(args)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000419 PyErr_SetString(PyExc_TypeError,
420 "Tuple or struct_time argument required");
421 return 0;
422 }
Skip Montanaro41cfce92007-08-24 21:11:00 +0000423
Alexander Belopolsky610e5442011-01-06 21:57:06 +0000424 if (!PyArg_ParseTuple(args, "iiiiiiiii",
425 &y, &p->tm_mon, &p->tm_mday,
426 &p->tm_hour, &p->tm_min, &p->tm_sec,
427 &p->tm_wday, &p->tm_yday, &p->tm_isdst))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000428 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000429 p->tm_year = y - 1900;
430 p->tm_mon--;
431 p->tm_wday = (p->tm_wday + 1) % 7;
432 p->tm_yday--;
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400433#ifdef HAVE_STRUCT_TM_TM_ZONE
434 if (Py_TYPE(args) == &StructTimeType) {
435 PyObject *item;
436 item = PyTuple_GET_ITEM(args, 9);
437 p->tm_zone = item == Py_None ? NULL : _PyUnicode_AsString(item);
438 item = PyTuple_GET_ITEM(args, 10);
439 p->tm_gmtoff = item == Py_None ? 0 : PyLong_AsLong(item);
440 if (PyErr_Occurred())
441 return 0;
442 }
443#endif /* HAVE_STRUCT_TM_TM_ZONE */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000444 return 1;
Guido van Rossum9e90a671993-06-24 11:10:19 +0000445}
446
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000447/* Check values of the struct tm fields before it is passed to strftime() and
448 * asctime(). Return 1 if all values are valid, otherwise set an exception
449 * and returns 0.
450 */
Victor Stinneref128102010-10-07 01:00:52 +0000451static int
452checktm(struct tm* buf)
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000453{
Victor Stinneref128102010-10-07 01:00:52 +0000454 /* Checks added to make sure strftime() and asctime() does not crash Python by
455 indexing blindly into some array for a textual representation
456 by some bad index (fixes bug #897625 and #6608).
457
458 Also support values of zero from Python code for arguments in which
459 that is out of range by forcing that value to the lowest value that
460 is valid (fixed bug #1520914).
461
462 Valid ranges based on what is allowed in struct tm:
463
464 - tm_year: [0, max(int)] (1)
465 - tm_mon: [0, 11] (2)
466 - tm_mday: [1, 31]
467 - tm_hour: [0, 23]
468 - tm_min: [0, 59]
469 - tm_sec: [0, 60]
470 - tm_wday: [0, 6] (1)
471 - tm_yday: [0, 365] (2)
472 - tm_isdst: [-max(int), max(int)]
473
474 (1) gettmarg() handles bounds-checking.
475 (2) Python's acceptable range is one greater than the range in C,
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000476 thus need to check against automatic decrement by gettmarg().
477 */
478 if (buf->tm_mon == -1)
479 buf->tm_mon = 0;
480 else if (buf->tm_mon < 0 || buf->tm_mon > 11) {
481 PyErr_SetString(PyExc_ValueError, "month out of range");
482 return 0;
483 }
484 if (buf->tm_mday == 0)
485 buf->tm_mday = 1;
486 else if (buf->tm_mday < 0 || buf->tm_mday > 31) {
487 PyErr_SetString(PyExc_ValueError, "day of month out of range");
488 return 0;
489 }
490 if (buf->tm_hour < 0 || buf->tm_hour > 23) {
491 PyErr_SetString(PyExc_ValueError, "hour out of range");
492 return 0;
493 }
494 if (buf->tm_min < 0 || buf->tm_min > 59) {
495 PyErr_SetString(PyExc_ValueError, "minute out of range");
496 return 0;
497 }
498 if (buf->tm_sec < 0 || buf->tm_sec > 61) {
499 PyErr_SetString(PyExc_ValueError, "seconds out of range");
500 return 0;
501 }
502 /* tm_wday does not need checking of its upper-bound since taking
503 ``% 7`` in gettmarg() automatically restricts the range. */
504 if (buf->tm_wday < 0) {
505 PyErr_SetString(PyExc_ValueError, "day of week out of range");
506 return 0;
507 }
508 if (buf->tm_yday == -1)
509 buf->tm_yday = 0;
510 else if (buf->tm_yday < 0 || buf->tm_yday > 365) {
511 PyErr_SetString(PyExc_ValueError, "day of year out of range");
512 return 0;
513 }
514 return 1;
515}
516
Victor Stinnerc1f32ca2011-10-14 02:36:13 +0200517#ifdef MS_WINDOWS
518 /* wcsftime() doesn't format correctly time zones, see issue #10653 */
519# undef HAVE_WCSFTIME
520#endif
Alexander Belopolskycf774542012-10-02 18:39:16 -0400521#define STRFTIME_FORMAT_CODES \
522"Commonly used format codes:\n\
523\n\
524%Y Year with century as a decimal number.\n\
525%m Month as a decimal number [01,12].\n\
526%d Day of the month as a decimal number [01,31].\n\
527%H Hour (24-hour clock) as a decimal number [00,23].\n\
528%M Minute as a decimal number [00,59].\n\
529%S Second as a decimal number [00,61].\n\
530%z Time zone offset from UTC.\n\
531%a Locale's abbreviated weekday name.\n\
532%A Locale's full weekday name.\n\
533%b Locale's abbreviated month name.\n\
534%B Locale's full month name.\n\
535%c Locale's appropriate date and time representation.\n\
536%I Hour (12-hour clock) as a decimal number [01,12].\n\
537%p Locale's equivalent of either AM or PM.\n\
538\n\
539Other codes may be available on your platform. See documentation for\n\
540the C library strftime function.\n"
Victor Stinnerc1f32ca2011-10-14 02:36:13 +0200541
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000542#ifdef HAVE_STRFTIME
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000543#ifdef HAVE_WCSFTIME
544#define time_char wchar_t
545#define format_time wcsftime
546#define time_strlen wcslen
547#else
548#define time_char char
549#define format_time strftime
550#define time_strlen strlen
551#endif
552
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000553static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000554time_strftime(PyObject *self, PyObject *args)
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000555{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000556 PyObject *tup = NULL;
557 struct tm buf;
558 const time_char *fmt;
Victor Stinnerb2904782010-09-29 10:34:19 +0000559#ifdef HAVE_WCSFTIME
560 wchar_t *format;
561#else
562 PyObject *format;
563#endif
Victor Stinneref128102010-10-07 01:00:52 +0000564 PyObject *format_arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000565 size_t fmtlen, buflen;
Victor Stinnerb2904782010-09-29 10:34:19 +0000566 time_char *outbuf = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000567 size_t i;
Victor Stinnerb2904782010-09-29 10:34:19 +0000568 PyObject *ret = NULL;
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000569
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000570 memset((void *) &buf, '\0', sizeof(buf));
Guido van Rossum1f41f841998-04-27 19:04:26 +0000571
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000572 /* Will always expect a unicode string to be passed as format.
573 Given that there's no str type anymore in py3k this seems safe.
574 */
Victor Stinneref128102010-10-07 01:00:52 +0000575 if (!PyArg_ParseTuple(args, "U|O:strftime", &format_arg, &tup))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000576 return NULL;
Thomas Woutersfe385252001-01-19 23:16:56 +0000577
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000578 if (tup == NULL) {
579 time_t tt = time(NULL);
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100580 if (pylocaltime(&tt, &buf) == -1)
581 return NULL;
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000582 }
583 else if (!gettmarg(tup, &buf) || !checktm(&buf))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000584 return NULL;
Guido van Rossum10b164a2001-09-25 13:59:01 +0000585
Victor Stinner36b82d82013-06-25 02:33:53 +0200586#if defined(_MSC_VER) || defined(sun) || defined(_AIX)
Victor Stinner73ea29c2011-01-08 01:56:31 +0000587 if (buf.tm_year + 1900 < 1 || 9999 < buf.tm_year + 1900) {
Victor Stinner6f0e4f92011-03-21 02:14:53 +0100588 PyErr_SetString(PyExc_ValueError,
589 "strftime() requires year in [1; 9999]");
Alexander Belopolsky0dd06f42011-01-08 01:23:02 +0000590 return NULL;
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000591 }
Victor Stinner73ea29c2011-01-08 01:56:31 +0000592#endif
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000593
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000594 /* Normalize tm_isdst just in case someone foolishly implements %Z
595 based on the assumption that tm_isdst falls within the range of
596 [-1, 1] */
597 if (buf.tm_isdst < -1)
598 buf.tm_isdst = -1;
599 else if (buf.tm_isdst > 1)
600 buf.tm_isdst = 1;
Brett Cannond1080a32004-03-02 04:38:10 +0000601
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000602#ifdef HAVE_WCSFTIME
Victor Stinnerbeb4135b2010-10-07 01:02:42 +0000603 format = PyUnicode_AsWideCharString(format_arg, NULL);
Victor Stinnerb2904782010-09-29 10:34:19 +0000604 if (format == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000605 return NULL;
Victor Stinnerb2904782010-09-29 10:34:19 +0000606 fmt = format;
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000607#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000608 /* Convert the unicode string to an ascii one */
Victor Stinner1b579672011-12-17 05:47:23 +0100609 format = PyUnicode_EncodeLocale(format_arg, "surrogateescape");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000610 if (format == NULL)
611 return NULL;
612 fmt = PyBytes_AS_STRING(format);
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000613#endif
Amaury Forgeot d'Arcb5be6d42009-03-02 23:52:57 +0000614
Stefan Krah4aea7d32012-02-27 16:30:26 +0100615#if defined(MS_WINDOWS) && !defined(HAVE_WCSFTIME)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000616 /* check that the format string contains only valid directives */
Victor Stinner5a3ff792011-10-16 19:08:23 +0200617 for(outbuf = strchr(fmt, '%');
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000618 outbuf != NULL;
Victor Stinner5a3ff792011-10-16 19:08:23 +0200619 outbuf = strchr(outbuf+2, '%'))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000620 {
621 if (outbuf[1]=='#')
622 ++outbuf; /* not documented by python, */
623 if (outbuf[1]=='\0' ||
Victor Stinner5a3ff792011-10-16 19:08:23 +0200624 !strchr("aAbBcdHIjmMpSUwWxXyYzZ%", outbuf[1]))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000625 {
626 PyErr_SetString(PyExc_ValueError, "Invalid format string");
Stefan Krah4aea7d32012-02-27 16:30:26 +0100627 Py_DECREF(format);
628 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000629 }
Tim Golden6e51b8f2013-11-12 12:36:54 +0000630 if ((outbuf[1] == 'y') && buf.tm_year < 0)
631 {
632 PyErr_SetString(PyExc_ValueError,
633 "format %y requires year >= 1900 on Windows");
634 Py_DECREF(format);
635 return NULL;
636 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000637 }
Victor Stinner93965f72013-11-23 14:59:33 +0100638#elif (defined(_AIX) || defined(sun)) && defined(HAVE_WCSFTIME)
Victor Stinner55329f82013-11-17 23:39:21 +0100639 for(outbuf = wcschr(fmt, '%');
640 outbuf != NULL;
641 outbuf = wcschr(outbuf+2, '%'))
642 {
643 /* Issue #19634: On AIX, wcsftime("y", (1899, 1, 1, 0, 0, 0, 0, 0, 0))
644 returns "0/" instead of "99" */
645 if (outbuf[1] == L'y' && buf.tm_year < 0) {
646 PyErr_SetString(PyExc_ValueError,
647 "format %y requires year >= 1900 on AIX");
Victor Stinner55329f82013-11-17 23:39:21 +0100648 return NULL;
649 }
650 }
Amaury Forgeot d'Arcb5be6d42009-03-02 23:52:57 +0000651#endif
652
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000653 fmtlen = time_strlen(fmt);
Guido van Rossumc222ec21999-02-23 00:00:10 +0000654
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000655 /* I hate these functions that presume you know how big the output
656 * will be ahead of time...
657 */
658 for (i = 1024; ; i += i) {
Victor Stinner136ea492011-12-17 22:37:18 +0100659#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100660 int err;
Victor Stinner136ea492011-12-17 22:37:18 +0100661#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000662 outbuf = (time_char *)PyMem_Malloc(i*sizeof(time_char));
663 if (outbuf == NULL) {
Victor Stinnerb2904782010-09-29 10:34:19 +0000664 PyErr_NoMemory();
665 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000666 }
667 buflen = format_time(outbuf, i, fmt, &buf);
Victor Stinner136ea492011-12-17 22:37:18 +0100668#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100669 err = errno;
Victor Stinner136ea492011-12-17 22:37:18 +0100670#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000671 if (buflen > 0 || i >= 256 * fmtlen) {
672 /* If the buffer is 256 times as long as the format,
673 it's probably not failing for lack of room!
674 More likely, the format yields an empty result,
675 e.g. an empty format, or %Z when the timezone
676 is unknown. */
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000677#ifdef HAVE_WCSFTIME
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000678 ret = PyUnicode_FromWideChar(outbuf, buflen);
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000679#else
Victor Stinner1b579672011-12-17 05:47:23 +0100680 ret = PyUnicode_DecodeLocaleAndSize(outbuf, buflen,
681 "surrogateescape");
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000682#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000683 PyMem_Free(outbuf);
Victor Stinnerb2904782010-09-29 10:34:19 +0000684 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000685 }
686 PyMem_Free(outbuf);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000687#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000688 /* VisualStudio .NET 2005 does this properly */
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100689 if (buflen == 0 && err == EINVAL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000690 PyErr_SetString(PyExc_ValueError, "Invalid format string");
Victor Stinnerb2904782010-09-29 10:34:19 +0000691 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000692 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000693#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000694 }
Victor Stinnerb2904782010-09-29 10:34:19 +0000695#ifdef HAVE_WCSFTIME
696 PyMem_Free(format);
697#else
698 Py_DECREF(format);
699#endif
700 return ret;
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000701}
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000702
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000703#undef time_char
704#undef format_time
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000705PyDoc_STRVAR(strftime_doc,
Thomas Woutersfe385252001-01-19 23:16:56 +0000706"strftime(format[, tuple]) -> string\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000707\n\
708Convert a time tuple to a string according to a format specification.\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000709See the library reference manual for formatting codes. When the time tuple\n\
Alexander Belopolskycf774542012-10-02 18:39:16 -0400710is not present, current time as returned by localtime() is used.\n\
711\n" STRFTIME_FORMAT_CODES);
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000712#endif /* HAVE_STRFTIME */
713
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000714static PyObject *
715time_strptime(PyObject *self, PyObject *args)
716{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000717 PyObject *strptime_module = PyImport_ImportModuleNoBlock("_strptime");
718 PyObject *strptime_result;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200719 _Py_IDENTIFIER(_strptime_time);
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000720
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000721 if (!strptime_module)
722 return NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200723 strptime_result = _PyObject_CallMethodId(strptime_module,
724 &PyId__strptime_time, "O", args);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000725 Py_DECREF(strptime_module);
726 return strptime_result;
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000727}
728
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000729
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000730PyDoc_STRVAR(strptime_doc,
Brett Cannon20def8b2003-07-01 05:16:08 +0000731"strptime(string, format) -> struct_time\n\
Martin v. Löwisb3cfc1d2001-12-02 12:27:43 +0000732\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000733Parse a string to a time tuple according to a format specification.\n\
Alexander Belopolskycf774542012-10-02 18:39:16 -0400734See the library reference manual for formatting codes (same as\n\
735strftime()).\n\
736\n" STRFTIME_FORMAT_CODES);
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000737
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000738static PyObject *
739_asctime(struct tm *timeptr)
740{
741 /* Inspired by Open Group reference implementation available at
742 * http://pubs.opengroup.org/onlinepubs/009695399/functions/asctime.html */
Victor Stinner499dfcf2011-03-21 13:26:24 +0100743 static char wday_name[7][4] = {
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000744 "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
745 };
Victor Stinner499dfcf2011-03-21 13:26:24 +0100746 static char mon_name[12][4] = {
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000747 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
748 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
749 };
Victor Stinner499dfcf2011-03-21 13:26:24 +0100750 return PyUnicode_FromFormat(
751 "%s %s%3d %.2d:%.2d:%.2d %d",
752 wday_name[timeptr->tm_wday],
753 mon_name[timeptr->tm_mon],
754 timeptr->tm_mday, timeptr->tm_hour,
755 timeptr->tm_min, timeptr->tm_sec,
756 1900 + timeptr->tm_year);
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000757}
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000758
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000759static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000760time_asctime(PyObject *self, PyObject *args)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000761{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000762 PyObject *tup = NULL;
763 struct tm buf;
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000764
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000765 if (!PyArg_UnpackTuple(args, "asctime", 0, 1, &tup))
766 return NULL;
767 if (tup == NULL) {
768 time_t tt = time(NULL);
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100769 if (pylocaltime(&tt, &buf) == -1)
770 return NULL;
771
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000772 } else if (!gettmarg(tup, &buf) || !checktm(&buf))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000773 return NULL;
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000774 return _asctime(&buf);
Guido van Rossum9e90a671993-06-24 11:10:19 +0000775}
776
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000777PyDoc_STRVAR(asctime_doc,
Thomas Woutersfe385252001-01-19 23:16:56 +0000778"asctime([tuple]) -> string\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000779\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000780Convert a time tuple to a string, e.g. 'Sat Jun 06 16:26:11 1998'.\n\
781When the time tuple is not present, current time as returned by localtime()\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000782is used.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000783
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000784static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000785time_ctime(PyObject *self, PyObject *args)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000786{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000787 time_t tt;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100788 struct tm buf;
789 if (!parse_time_t_args(args, "|O:ctime", &tt))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000790 return NULL;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100791 if (pylocaltime(&tt, &buf) == -1)
Alexander Belopolsky5da468f2011-01-04 17:15:52 +0000792 return NULL;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100793 return _asctime(&buf);
Guido van Rossum9e90a671993-06-24 11:10:19 +0000794}
795
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000796PyDoc_STRVAR(ctime_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000797"ctime(seconds) -> string\n\
798\n\
799Convert a time in seconds since the Epoch to a string in local time.\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000800This is equivalent to asctime(localtime(seconds)). When the time tuple is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000801not present, current time as returned by localtime() is used.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000802
Guido van Rossum60cd8131998-03-06 17:16:21 +0000803#ifdef HAVE_MKTIME
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000804static PyObject *
Victor Stinner4195b5c2012-02-08 23:03:19 +0100805time_mktime(PyObject *self, PyObject *tup)
Guido van Rossum234f9421993-06-17 12:35:49 +0000806{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000807 struct tm buf;
808 time_t tt;
809 if (!gettmarg(tup, &buf))
810 return NULL;
Victor Stinner1ac42612014-02-21 09:27:17 +0100811#ifdef _AIX
812 /* year < 1902 or year > 2037 */
813 if (buf.tm_year < 2 || buf.tm_year > 137) {
814 /* Issue #19748: On AIX, mktime() doesn't report overflow error for
815 * timestamp < -2^31 or timestamp > 2**31-1. */
816 PyErr_SetString(PyExc_OverflowError,
817 "mktime argument out of range");
818 return NULL;
819 }
820#else
Alexander Belopolskyb7d40d12011-01-11 01:21:25 +0000821 buf.tm_wday = -1; /* sentinel; original value ignored */
Victor Stinner1ac42612014-02-21 09:27:17 +0100822#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000823 tt = mktime(&buf);
Alexander Belopolskyb7d40d12011-01-11 01:21:25 +0000824 /* Return value of -1 does not necessarily mean an error, but tm_wday
Ezio Melotti13925002011-03-16 11:05:33 +0200825 * cannot remain set to -1 if mktime succeeded. */
Victor Stinner93037492013-06-25 22:54:35 +0200826 if (tt == (time_t)(-1)
827#ifndef _AIX
828 /* Return value of -1 does not necessarily mean an error, but
829 * tm_wday cannot remain set to -1 if mktime succeeded. */
830 && buf.tm_wday == -1
831#else
832 /* on AIX, tm_wday is always sets, even on error */
833#endif
834 )
835 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000836 PyErr_SetString(PyExc_OverflowError,
837 "mktime argument out of range");
838 return NULL;
839 }
Victor Stinner4195b5c2012-02-08 23:03:19 +0100840 return PyFloat_FromDouble((double)tt);
Guido van Rossum234f9421993-06-17 12:35:49 +0000841}
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000842
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000843PyDoc_STRVAR(mktime_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000844"mktime(tuple) -> floating point number\n\
845\n\
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400846Convert a time tuple in local time to seconds since the Epoch.\n\
847Note that mktime(gmtime(0)) will not generally return zero for most\n\
848time zones; instead the returned value will either be equal to that\n\
849of the timezone or altzone attributes on the time module.");
Guido van Rossum60cd8131998-03-06 17:16:21 +0000850#endif /* HAVE_MKTIME */
Guido van Rossum234f9421993-06-17 12:35:49 +0000851
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000852#ifdef HAVE_WORKING_TZSET
Martin v. Löwis1a214512008-06-11 05:26:20 +0000853static void PyInit_timezone(PyObject *module);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000854
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000855static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000856time_tzset(PyObject *self, PyObject *unused)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000857{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000858 PyObject* m;
Fred Drake9bb74322002-04-01 14:49:59 +0000859
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000860 m = PyImport_ImportModuleNoBlock("time");
861 if (m == NULL) {
862 return NULL;
863 }
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000864
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000865 tzset();
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000866
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000867 /* Reset timezone, altzone, daylight and tzname */
868 PyInit_timezone(m);
869 Py_DECREF(m);
Victor Stinner2ff51b82013-07-17 21:42:45 +0200870 if (PyErr_Occurred())
871 return NULL;
Tim Peters1b6f7a92004-06-20 02:50:16 +0000872
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000873 Py_INCREF(Py_None);
874 return Py_None;
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000875}
876
877PyDoc_STRVAR(tzset_doc,
R. David Murray4d55bf92010-12-14 00:55:46 +0000878"tzset()\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000879\n\
880Initialize, or reinitialize, the local timezone to the value stored in\n\
881os.environ['TZ']. The TZ environment variable should be specified in\n\
Neal Norwitzdc8e1942004-07-20 22:34:37 +0000882standard Unix timezone format as documented in the tzset man page\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000883(eg. 'US/Eastern', 'Europe/Amsterdam'). Unknown timezones will silently\n\
884fall back to UTC. If the TZ environment variable is not set, the local\n\
885timezone is set to the systems best guess of wallclock time.\n\
886Changing the TZ environment variable without calling tzset *may* change\n\
887the local timezone used by methods such as localtime, but this behaviour\n\
888should not be relied on.");
889#endif /* HAVE_WORKING_TZSET */
890
Victor Stinnerae586492014-09-02 23:18:25 +0200891static PyObject *
Victor Stinnerec895392012-04-29 02:41:27 +0200892pymonotonic(_Py_clock_info_t *info)
Victor Stinnerb94b2662012-01-18 01:50:21 +0100893{
Victor Stinnerae586492014-09-02 23:18:25 +0200894 _PyTime_timeval tv;
895 if (_PyTime_monotonic_info(&tv, info) < 0) {
896 assert(info != NULL);
Victor Stinner071eca32012-03-15 01:17:09 +0100897 return NULL;
898 }
Victor Stinnerae586492014-09-02 23:18:25 +0200899 return PyFloat_FromDouble((double)tv.tv_sec + tv.tv_usec * 1e-6);
Victor Stinner8b302012012-02-07 23:29:46 +0100900}
901
Victor Stinner071eca32012-03-15 01:17:09 +0100902static PyObject *
Victor Stinnerec895392012-04-29 02:41:27 +0200903time_monotonic(PyObject *self, PyObject *unused)
Victor Stinner071eca32012-03-15 01:17:09 +0100904{
Victor Stinnerec895392012-04-29 02:41:27 +0200905 return pymonotonic(NULL);
Victor Stinner071eca32012-03-15 01:17:09 +0100906}
907
Victor Stinnerec895392012-04-29 02:41:27 +0200908PyDoc_STRVAR(monotonic_doc,
909"monotonic() -> float\n\
Victor Stinner8b302012012-02-07 23:29:46 +0100910\n\
Victor Stinnerec895392012-04-29 02:41:27 +0200911Monotonic clock, cannot go backward.");
Victor Stinnerec919cc2012-03-15 00:58:32 +0100912
Victor Stinnerec895392012-04-29 02:41:27 +0200913static PyObject*
914perf_counter(_Py_clock_info_t *info)
915{
Victor Stinner54884492014-08-29 16:51:33 +0200916#ifdef WIN32_PERF_COUNTER
917 return win_perf_counter(info);
918#else
Victor Stinnerae586492014-09-02 23:18:25 +0200919 return pymonotonic(info);
Victor Stinner54884492014-08-29 16:51:33 +0200920#endif
Victor Stinnerec895392012-04-29 02:41:27 +0200921}
922
923static PyObject *
924time_perf_counter(PyObject *self, PyObject *unused)
925{
926 return perf_counter(NULL);
927}
928
929PyDoc_STRVAR(perf_counter_doc,
930"perf_counter() -> float\n\
931\n\
932Performance counter for benchmarking.");
933
934static PyObject*
935py_process_time(_Py_clock_info_t *info)
936{
937#if defined(MS_WINDOWS)
938 HANDLE process;
939 FILETIME creation_time, exit_time, kernel_time, user_time;
940 ULARGE_INTEGER large;
941 double total;
942 BOOL ok;
943
944 process = GetCurrentProcess();
945 ok = GetProcessTimes(process, &creation_time, &exit_time, &kernel_time, &user_time);
946 if (!ok)
947 return PyErr_SetFromWindowsErr(0);
948
949 large.u.LowPart = kernel_time.dwLowDateTime;
950 large.u.HighPart = kernel_time.dwHighDateTime;
951 total = (double)large.QuadPart;
952 large.u.LowPart = user_time.dwLowDateTime;
953 large.u.HighPart = user_time.dwHighDateTime;
954 total += (double)large.QuadPart;
955 if (info) {
956 info->implementation = "GetProcessTimes()";
957 info->resolution = 1e-7;
Benjamin Peterson49a69e42012-05-01 09:38:34 -0400958 info->monotonic = 1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +0200959 info->adjustable = 0;
Victor Stinnerec895392012-04-29 02:41:27 +0200960 }
961 return PyFloat_FromDouble(total * 1e-7);
962#else
963
964#if defined(HAVE_SYS_RESOURCE_H)
965 struct rusage ru;
966#endif
967#ifdef HAVE_TIMES
968 struct tms t;
969 static long ticks_per_second = -1;
970#endif
971
972#if defined(HAVE_CLOCK_GETTIME) \
973 && (defined(CLOCK_PROCESS_CPUTIME_ID) || defined(CLOCK_PROF))
974 struct timespec tp;
975#ifdef CLOCK_PROF
976 const clockid_t clk_id = CLOCK_PROF;
977 const char *function = "clock_gettime(CLOCK_PROF)";
978#else
979 const clockid_t clk_id = CLOCK_PROCESS_CPUTIME_ID;
980 const char *function = "clock_gettime(CLOCK_PROCESS_CPUTIME_ID)";
981#endif
982
983 if (clock_gettime(clk_id, &tp) == 0) {
984 if (info) {
985 struct timespec res;
986 info->implementation = function;
Benjamin Peterson49a69e42012-05-01 09:38:34 -0400987 info->monotonic = 1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +0200988 info->adjustable = 0;
Victor Stinnerec895392012-04-29 02:41:27 +0200989 if (clock_getres(clk_id, &res) == 0)
990 info->resolution = res.tv_sec + res.tv_nsec * 1e-9;
991 else
992 info->resolution = 1e-9;
993 }
994 return PyFloat_FromDouble(tp.tv_sec + tp.tv_nsec * 1e-9);
995 }
996#endif
997
998#if defined(HAVE_SYS_RESOURCE_H)
999 if (getrusage(RUSAGE_SELF, &ru) == 0) {
1000 double total;
1001 total = ru.ru_utime.tv_sec + ru.ru_utime.tv_usec * 1e-6;
1002 total += ru.ru_stime.tv_sec + ru.ru_stime.tv_usec * 1e-6;
1003 if (info) {
1004 info->implementation = "getrusage(RUSAGE_SELF)";
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001005 info->monotonic = 1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001006 info->adjustable = 0;
Victor Stinnerec895392012-04-29 02:41:27 +02001007 info->resolution = 1e-6;
1008 }
1009 return PyFloat_FromDouble(total);
1010 }
1011#endif
1012
1013#ifdef HAVE_TIMES
1014 if (times(&t) != (clock_t)-1) {
1015 double total;
1016
1017 if (ticks_per_second == -1) {
1018#if defined(HAVE_SYSCONF) && defined(_SC_CLK_TCK)
1019 ticks_per_second = sysconf(_SC_CLK_TCK);
1020 if (ticks_per_second < 1)
1021 ticks_per_second = -1;
1022#elif defined(HZ)
1023 ticks_per_second = HZ;
1024#else
1025 ticks_per_second = 60; /* magic fallback value; may be bogus */
1026#endif
1027 }
1028
1029 if (ticks_per_second != -1) {
1030 total = (double)t.tms_utime / ticks_per_second;
1031 total += (double)t.tms_stime / ticks_per_second;
1032 if (info) {
1033 info->implementation = "times()";
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001034 info->monotonic = 1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001035 info->adjustable = 0;
Victor Stinnerec895392012-04-29 02:41:27 +02001036 info->resolution = 1.0 / ticks_per_second;
1037 }
1038 return PyFloat_FromDouble(total);
1039 }
1040 }
1041#endif
1042
1043 return floatclock(info);
1044#endif
1045}
1046
1047static PyObject *
1048time_process_time(PyObject *self, PyObject *unused)
1049{
1050 return py_process_time(NULL);
1051}
1052
1053PyDoc_STRVAR(process_time_doc,
1054"process_time() -> float\n\
1055\n\
1056Process time for profiling: sum of the kernel and user-space CPU time.");
1057
1058
Victor Stinnerec895392012-04-29 02:41:27 +02001059static PyObject *
1060time_get_clock_info(PyObject *self, PyObject *args)
1061{
1062 char *name;
Victor Stinnerec895392012-04-29 02:41:27 +02001063 _Py_clock_info_t info;
Victor Stinnerbda4b882012-06-12 22:11:44 +02001064 PyObject *obj = NULL, *dict, *ns;
Victor Stinnerec895392012-04-29 02:41:27 +02001065
1066 if (!PyArg_ParseTuple(args, "s:get_clock_info", &name))
1067 return NULL;
1068
1069#ifdef Py_DEBUG
1070 info.implementation = NULL;
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001071 info.monotonic = -1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001072 info.adjustable = -1;
Victor Stinnerec895392012-04-29 02:41:27 +02001073 info.resolution = -1.0;
1074#else
1075 info.implementation = "";
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001076 info.monotonic = 0;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001077 info.adjustable = 0;
Victor Stinnerec895392012-04-29 02:41:27 +02001078 info.resolution = 1.0;
1079#endif
1080
1081 if (strcmp(name, "time") == 0)
1082 obj = floattime(&info);
1083#ifdef PYCLOCK
1084 else if (strcmp(name, "clock") == 0)
1085 obj = pyclock(&info);
1086#endif
Victor Stinnerec895392012-04-29 02:41:27 +02001087 else if (strcmp(name, "monotonic") == 0)
1088 obj = pymonotonic(&info);
Victor Stinnerec895392012-04-29 02:41:27 +02001089 else if (strcmp(name, "perf_counter") == 0)
1090 obj = perf_counter(&info);
1091 else if (strcmp(name, "process_time") == 0)
1092 obj = py_process_time(&info);
1093 else {
1094 PyErr_SetString(PyExc_ValueError, "unknown clock");
1095 return NULL;
1096 }
1097 if (obj == NULL)
1098 return NULL;
1099 Py_DECREF(obj);
1100
Victor Stinnerbda4b882012-06-12 22:11:44 +02001101 dict = PyDict_New();
1102 if (dict == NULL)
Victor Stinnerec895392012-04-29 02:41:27 +02001103 return NULL;
1104
1105 assert(info.implementation != NULL);
1106 obj = PyUnicode_FromString(info.implementation);
1107 if (obj == NULL)
1108 goto error;
Victor Stinnerbda4b882012-06-12 22:11:44 +02001109 if (PyDict_SetItemString(dict, "implementation", obj) == -1)
1110 goto error;
1111 Py_CLEAR(obj);
Victor Stinnerec895392012-04-29 02:41:27 +02001112
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001113 assert(info.monotonic != -1);
1114 obj = PyBool_FromLong(info.monotonic);
Victor Stinnerec895392012-04-29 02:41:27 +02001115 if (obj == NULL)
1116 goto error;
Victor Stinnerbda4b882012-06-12 22:11:44 +02001117 if (PyDict_SetItemString(dict, "monotonic", obj) == -1)
1118 goto error;
1119 Py_CLEAR(obj);
Victor Stinnerec895392012-04-29 02:41:27 +02001120
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001121 assert(info.adjustable != -1);
1122 obj = PyBool_FromLong(info.adjustable);
Victor Stinnerec895392012-04-29 02:41:27 +02001123 if (obj == NULL)
1124 goto error;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001125 if (PyDict_SetItemString(dict, "adjustable", obj) == -1)
Victor Stinnerbda4b882012-06-12 22:11:44 +02001126 goto error;
1127 Py_CLEAR(obj);
Victor Stinnerec895392012-04-29 02:41:27 +02001128
1129 assert(info.resolution > 0.0);
1130 assert(info.resolution <= 1.0);
1131 obj = PyFloat_FromDouble(info.resolution);
1132 if (obj == NULL)
1133 goto error;
Victor Stinnerbda4b882012-06-12 22:11:44 +02001134 if (PyDict_SetItemString(dict, "resolution", obj) == -1)
1135 goto error;
1136 Py_CLEAR(obj);
Victor Stinnerec895392012-04-29 02:41:27 +02001137
Victor Stinnerbda4b882012-06-12 22:11:44 +02001138 ns = _PyNamespace_New(dict);
1139 Py_DECREF(dict);
1140 return ns;
Victor Stinnerec895392012-04-29 02:41:27 +02001141
1142error:
Victor Stinnerbda4b882012-06-12 22:11:44 +02001143 Py_DECREF(dict);
1144 Py_XDECREF(obj);
Victor Stinnerec895392012-04-29 02:41:27 +02001145 return NULL;
1146}
1147
1148PyDoc_STRVAR(get_clock_info_doc,
1149"get_clock_info(name: str) -> dict\n\
1150\n\
1151Get information of the specified clock.");
Victor Stinner8b302012012-02-07 23:29:46 +01001152
Martin v. Löwisd218dc12008-04-07 03:17:54 +00001153static void
Martin v. Löwis1a214512008-06-11 05:26:20 +00001154PyInit_timezone(PyObject *m) {
1155 /* This code moved from PyInit_time wholesale to allow calling it from
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001156 time_tzset. In the future, some parts of it can be moved back
1157 (for platforms that don't HAVE_WORKING_TZSET, when we know what they
1158 are), and the extraneous calls to tzset(3) should be removed.
1159 I haven't done this yet, as I don't want to change this code as
1160 little as possible when introducing the time.tzset and time.tzsetwall
1161 methods. This should simply be a method of doing the following once,
1162 at the top of this function and removing the call to tzset() from
1163 time_tzset():
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001164
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001165 #ifdef HAVE_TZSET
1166 tzset()
1167 #endif
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001168
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001169 And I'm lazy and hate C so nyer.
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001170 */
Guido van Rossum10b164a2001-09-25 13:59:01 +00001171#if defined(HAVE_TZNAME) && !defined(__GLIBC__) && !defined(__CYGWIN__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001172 PyObject *otz0, *otz1;
1173 tzset();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001174 PyModule_AddIntConstant(m, "timezone", timezone);
Guido van Rossumb6775db1994-08-01 11:34:53 +00001175#ifdef HAVE_ALTZONE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001176 PyModule_AddIntConstant(m, "altzone", altzone);
Guido van Rossumb6775db1994-08-01 11:34:53 +00001177#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001178 PyModule_AddIntConstant(m, "altzone", timezone-3600);
Guido van Rossumb6775db1994-08-01 11:34:53 +00001179#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001180 PyModule_AddIntConstant(m, "daylight", daylight);
Victor Stinner1b579672011-12-17 05:47:23 +01001181 otz0 = PyUnicode_DecodeLocale(tzname[0], "surrogateescape");
1182 otz1 = PyUnicode_DecodeLocale(tzname[1], "surrogateescape");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001183 PyModule_AddObject(m, "tzname", Py_BuildValue("(NN)", otz0, otz1));
Guido van Rossum10b164a2001-09-25 13:59:01 +00001184#else /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/
Martin v. Löwis60a5d722002-10-16 20:28:25 +00001185#ifdef HAVE_STRUCT_TM_TM_ZONE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001186 {
Guido van Rossum234f9421993-06-17 12:35:49 +00001187#define YEAR ((time_t)((365 * 24 + 6) * 3600))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001188 time_t t;
1189 struct tm *p;
1190 long janzone, julyzone;
1191 char janname[10], julyname[10];
1192 t = (time((time_t *)0) / YEAR) * YEAR;
1193 p = localtime(&t);
1194 janzone = -p->tm_gmtoff;
1195 strncpy(janname, p->tm_zone ? p->tm_zone : " ", 9);
1196 janname[9] = '\0';
1197 t += YEAR/2;
1198 p = localtime(&t);
1199 julyzone = -p->tm_gmtoff;
1200 strncpy(julyname, p->tm_zone ? p->tm_zone : " ", 9);
1201 julyname[9] = '\0';
Guido van Rossum10b164a2001-09-25 13:59:01 +00001202
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001203 if( janzone < julyzone ) {
1204 /* DST is reversed in the southern hemisphere */
1205 PyModule_AddIntConstant(m, "timezone", julyzone);
1206 PyModule_AddIntConstant(m, "altzone", janzone);
1207 PyModule_AddIntConstant(m, "daylight",
1208 janzone != julyzone);
1209 PyModule_AddObject(m, "tzname",
1210 Py_BuildValue("(zz)",
1211 julyname, janname));
1212 } else {
1213 PyModule_AddIntConstant(m, "timezone", janzone);
1214 PyModule_AddIntConstant(m, "altzone", julyzone);
1215 PyModule_AddIntConstant(m, "daylight",
1216 janzone != julyzone);
1217 PyModule_AddObject(m, "tzname",
1218 Py_BuildValue("(zz)",
1219 janname, julyname));
1220 }
1221 }
Guido van Rossume6a4b7b1997-10-08 15:27:56 +00001222#else
Martin v. Löwis60a5d722002-10-16 20:28:25 +00001223#endif /* HAVE_STRUCT_TM_TM_ZONE */
Tim Peters26ae7cd2001-03-20 03:26:49 +00001224#ifdef __CYGWIN__
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001225 tzset();
1226 PyModule_AddIntConstant(m, "timezone", _timezone);
1227 PyModule_AddIntConstant(m, "altzone", _timezone-3600);
1228 PyModule_AddIntConstant(m, "daylight", _daylight);
1229 PyModule_AddObject(m, "tzname",
1230 Py_BuildValue("(zz)", _tzname[0], _tzname[1]));
Tim Peters26ae7cd2001-03-20 03:26:49 +00001231#endif /* __CYGWIN__ */
Guido van Rossum10b164a2001-09-25 13:59:01 +00001232#endif /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/
Victor Stinnere0be4232011-10-25 13:06:09 +02001233
Victor Stinnerec895392012-04-29 02:41:27 +02001234#if defined(HAVE_CLOCK_GETTIME)
Victor Stinnere0be4232011-10-25 13:06:09 +02001235 PyModule_AddIntMacro(m, CLOCK_REALTIME);
Victor Stinnere0be4232011-10-25 13:06:09 +02001236#ifdef CLOCK_MONOTONIC
1237 PyModule_AddIntMacro(m, CLOCK_MONOTONIC);
1238#endif
1239#ifdef CLOCK_MONOTONIC_RAW
1240 PyModule_AddIntMacro(m, CLOCK_MONOTONIC_RAW);
1241#endif
Victor Stinner1470f352012-04-03 00:31:17 +02001242#ifdef CLOCK_HIGHRES
1243 PyModule_AddIntMacro(m, CLOCK_HIGHRES);
1244#endif
Victor Stinnere0be4232011-10-25 13:06:09 +02001245#ifdef CLOCK_PROCESS_CPUTIME_ID
1246 PyModule_AddIntMacro(m, CLOCK_PROCESS_CPUTIME_ID);
1247#endif
1248#ifdef CLOCK_THREAD_CPUTIME_ID
1249 PyModule_AddIntMacro(m, CLOCK_THREAD_CPUTIME_ID);
1250#endif
1251#endif /* HAVE_CLOCK_GETTIME */
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001252}
1253
1254
1255static PyMethodDef time_methods[] = {
Victor Stinner4195b5c2012-02-08 23:03:19 +01001256 {"time", time_time, METH_NOARGS, time_doc},
Victor Stinnerec895392012-04-29 02:41:27 +02001257#ifdef PYCLOCK
Victor Stinner4195b5c2012-02-08 23:03:19 +01001258 {"clock", time_clock, METH_NOARGS, clock_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001259#endif
Victor Stinnere0be4232011-10-25 13:06:09 +02001260#ifdef HAVE_CLOCK_GETTIME
Victor Stinner4195b5c2012-02-08 23:03:19 +01001261 {"clock_gettime", time_clock_gettime, METH_VARARGS, clock_gettime_doc},
Victor Stinner30d79472012-04-03 00:45:07 +02001262 {"clock_settime", time_clock_settime, METH_VARARGS, clock_settime_doc},
Victor Stinner4195b5c2012-02-08 23:03:19 +01001263 {"clock_getres", time_clock_getres, METH_VARARGS, clock_getres_doc},
Victor Stinnere0be4232011-10-25 13:06:09 +02001264#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001265 {"sleep", time_sleep, METH_VARARGS, sleep_doc},
1266 {"gmtime", time_gmtime, METH_VARARGS, gmtime_doc},
1267 {"localtime", time_localtime, METH_VARARGS, localtime_doc},
1268 {"asctime", time_asctime, METH_VARARGS, asctime_doc},
1269 {"ctime", time_ctime, METH_VARARGS, ctime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001270#ifdef HAVE_MKTIME
Victor Stinner4195b5c2012-02-08 23:03:19 +01001271 {"mktime", time_mktime, METH_O, mktime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001272#endif
1273#ifdef HAVE_STRFTIME
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001274 {"strftime", time_strftime, METH_VARARGS, strftime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001275#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001276 {"strptime", time_strptime, METH_VARARGS, strptime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001277#ifdef HAVE_WORKING_TZSET
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001278 {"tzset", time_tzset, METH_NOARGS, tzset_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001279#endif
Victor Stinnerec895392012-04-29 02:41:27 +02001280 {"monotonic", time_monotonic, METH_NOARGS, monotonic_doc},
Victor Stinnerec895392012-04-29 02:41:27 +02001281 {"process_time", time_process_time, METH_NOARGS, process_time_doc},
1282 {"perf_counter", time_perf_counter, METH_NOARGS, perf_counter_doc},
1283 {"get_clock_info", time_get_clock_info, METH_VARARGS, get_clock_info_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001284 {NULL, NULL} /* sentinel */
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001285};
1286
1287
1288PyDoc_STRVAR(module_doc,
1289"This module provides various functions to manipulate time values.\n\
1290\n\
1291There are two standard representations of time. One is the number\n\
1292of seconds since the Epoch, in UTC (a.k.a. GMT). It may be an integer\n\
1293or a floating point number (to represent fractions of seconds).\n\
1294The Epoch is system-defined; on Unix, it is generally January 1st, 1970.\n\
1295The actual value can be retrieved by calling gmtime(0).\n\
1296\n\
1297The other representation is a tuple of 9 integers giving local time.\n\
1298The tuple items are:\n\
Alexander Belopolsky03163ac2011-05-02 12:20:52 -04001299 year (including century, e.g. 1998)\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001300 month (1-12)\n\
1301 day (1-31)\n\
1302 hours (0-23)\n\
1303 minutes (0-59)\n\
1304 seconds (0-59)\n\
1305 weekday (0-6, Monday is 0)\n\
1306 Julian day (day in the year, 1-366)\n\
1307 DST (Daylight Savings Time) flag (-1, 0 or 1)\n\
1308If the DST flag is 0, the time is given in the regular time zone;\n\
1309if it is 1, the time is given in the DST time zone;\n\
1310if it is -1, mktime() should guess based on the date and time.\n\
1311\n\
1312Variables:\n\
1313\n\
1314timezone -- difference in seconds between UTC and local standard time\n\
1315altzone -- difference in seconds between UTC and local DST time\n\
1316daylight -- whether local time should reflect DST\n\
1317tzname -- tuple of (standard time zone name, DST time zone name)\n\
1318\n\
1319Functions:\n\
1320\n\
1321time() -- return current time in seconds since the Epoch as a float\n\
1322clock() -- return CPU time since process start as a float\n\
1323sleep() -- delay for a number of seconds given as a float\n\
1324gmtime() -- convert seconds since Epoch to UTC tuple\n\
1325localtime() -- convert seconds since Epoch to local time tuple\n\
1326asctime() -- convert time tuple to string\n\
1327ctime() -- convert time in seconds to string\n\
1328mktime() -- convert local time tuple to seconds since Epoch\n\
1329strftime() -- convert time tuple to string according to format specification\n\
1330strptime() -- parse string to time tuple according to format specification\n\
1331tzset() -- change the local timezone");
1332
1333
Martin v. Löwis1a214512008-06-11 05:26:20 +00001334
1335static struct PyModuleDef timemodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001336 PyModuleDef_HEAD_INIT,
1337 "time",
1338 module_doc,
1339 -1,
1340 time_methods,
1341 NULL,
1342 NULL,
1343 NULL,
1344 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00001345};
1346
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001347PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00001348PyInit_time(void)
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001349{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001350 PyObject *m;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001351 m = PyModule_Create(&timemodule);
1352 if (m == NULL)
1353 return NULL;
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001355 /* Set, or reset, module variables like time.timezone */
1356 PyInit_timezone(m);
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001357
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001358 if (!initialized) {
Victor Stinner1c8f0592013-07-22 22:24:54 +02001359 if (PyStructSequence_InitType2(&StructTimeType,
1360 &struct_time_type_desc) < 0)
1361 return NULL;
Victor Stinnerec895392012-04-29 02:41:27 +02001362
Victor Stinnerec895392012-04-29 02:41:27 +02001363#ifdef MS_WINDOWS
1364 winver.dwOSVersionInfoSize = sizeof(winver);
1365 if (!GetVersionEx((OSVERSIONINFO*)&winver)) {
1366 Py_DECREF(m);
1367 PyErr_SetFromWindowsErr(0);
1368 return NULL;
1369 }
1370#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001371 }
1372 Py_INCREF(&StructTimeType);
Alexander Belopolskyc142bba2012-06-13 22:15:26 -04001373#ifdef HAVE_STRUCT_TM_TM_ZONE
1374 PyModule_AddIntConstant(m, "_STRUCT_TM_ITEMS", 11);
1375#else
1376 PyModule_AddIntConstant(m, "_STRUCT_TM_ITEMS", 9);
1377#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001378 PyModule_AddObject(m, "struct_time", (PyObject*) &StructTimeType);
1379 initialized = 1;
1380 return m;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001381}
1382
Victor Stinner071eca32012-03-15 01:17:09 +01001383static PyObject*
Victor Stinnerec895392012-04-29 02:41:27 +02001384floattime(_Py_clock_info_t *info)
Victor Stinner4195b5c2012-02-08 23:03:19 +01001385{
1386 _PyTime_timeval t;
Victor Stinner00111242014-08-29 16:31:59 +02001387 if (_PyTime_gettimeofday_info(&t, info) < 0) {
1388 assert(info != NULL);
1389 return NULL;
1390 }
Victor Stinner70b2e1e2012-03-26 22:08:02 +02001391 return PyFloat_FromDouble((double)t.tv_sec + t.tv_usec * 1e-6);
Victor Stinner4195b5c2012-02-08 23:03:19 +01001392}
1393
1394
Guido van Rossumb6775db1994-08-01 11:34:53 +00001395/* Implement floatsleep() for various platforms.
1396 When interrupted (or when another error occurs), return -1 and
1397 set an exception; else return 0. */
1398
1399static int
Guido van Rossuma320fd31995-03-09 12:14:15 +00001400floatsleep(double secs)
Guido van Rossum426035c1991-02-19 12:27:35 +00001401{
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001402/* XXX Should test for MS_WINDOWS first! */
Skip Montanaroeb33e5a2007-08-17 12:57:41 +00001403#if defined(HAVE_SELECT) && !defined(__EMX__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001404 struct timeval t;
1405 double frac;
Victor Stinner48b1ce52011-07-01 13:50:09 +02001406 int err;
1407
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001408 frac = fmod(secs, 1.0);
1409 secs = floor(secs);
1410 t.tv_sec = (long)secs;
1411 t.tv_usec = (long)(frac*1000000.0);
1412 Py_BEGIN_ALLOW_THREADS
Victor Stinner48b1ce52011-07-01 13:50:09 +02001413 err = select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &t);
1414 Py_END_ALLOW_THREADS
1415 if (err != 0) {
Guido van Rossum09cbb011999-11-08 15:32:27 +00001416#ifdef EINTR
Victor Stinner48b1ce52011-07-01 13:50:09 +02001417 if (errno == EINTR) {
1418 if (PyErr_CheckSignals())
1419 return -1;
1420 }
1421 else
Guido van Rossum09cbb011999-11-08 15:32:27 +00001422#endif
Victor Stinner48b1ce52011-07-01 13:50:09 +02001423 {
Victor Stinnera734af32014-07-31 13:07:17 +02001424 PyErr_SetFromErrno(PyExc_OSError);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001425 return -1;
1426 }
1427 }
Martin v. Löwis02af9642002-01-16 11:04:06 +00001428#elif defined(__WATCOMC__) && !defined(__QNX__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001429 /* XXX Can't interrupt this sleep */
1430 Py_BEGIN_ALLOW_THREADS
1431 delay((int)(secs * 1000 + 0.5)); /* delay() uses milliseconds */
1432 Py_END_ALLOW_THREADS
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001433#elif defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001434 {
1435 double millisecs = secs * 1000.0;
1436 unsigned long ul_millis;
Tim Peters513a1cd2003-01-19 04:54:58 +00001437
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001438 if (millisecs > (double)ULONG_MAX) {
1439 PyErr_SetString(PyExc_OverflowError,
1440 "sleep length is too large");
1441 return -1;
1442 }
1443 Py_BEGIN_ALLOW_THREADS
1444 /* Allow sleep(0) to maintain win32 semantics, and as decreed
1445 * by Guido, only the main thread can be interrupted.
1446 */
1447 ul_millis = (unsigned long)millisecs;
Antoine Pitrou6dd381e2011-11-21 21:26:56 +01001448 if (ul_millis == 0 || !_PyOS_IsMainThread())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001449 Sleep(ul_millis);
1450 else {
1451 DWORD rc;
Antoine Pitrou6dd381e2011-11-21 21:26:56 +01001452 HANDLE hInterruptEvent = _PyOS_SigintEvent();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001453 ResetEvent(hInterruptEvent);
Martin v. Löwisb26a9b12013-01-25 14:25:48 +01001454 rc = WaitForSingleObjectEx(hInterruptEvent, ul_millis, FALSE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001455 if (rc == WAIT_OBJECT_0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001456 Py_BLOCK_THREADS
1457 errno = EINTR;
Victor Stinnera734af32014-07-31 13:07:17 +02001458 PyErr_SetFromErrno(PyExc_OSError);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001459 return -1;
1460 }
1461 }
1462 Py_END_ALLOW_THREADS
1463 }
Martin v. Löwis02af9642002-01-16 11:04:06 +00001464#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001465 /* XXX Can't interrupt this sleep */
1466 Py_BEGIN_ALLOW_THREADS
1467 sleep((int)secs);
1468 Py_END_ALLOW_THREADS
Martin v. Löwis02af9642002-01-16 11:04:06 +00001469#endif
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001470
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001471 return 0;
Guido van Rossum80c9d881991-04-16 08:47:51 +00001472}