blob: 771db839b8a44fbd99f6bb45beb8a8bba863e203 [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
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007#ifdef HAVE_SYS_TYPES_H
Guido van Rossumb6775db1994-08-01 11:34:53 +00008#include <sys/types.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009#endif /* HAVE_SYS_TYPES_H */
Guido van Rossum6d946f91992-08-14 13:49:30 +000010
Guido van Rossumb6775db1994-08-01 11:34:53 +000011#ifdef QUICKWIN
12#include <io.h>
13#endif
14
Guido van Rossum7bf22de1997-12-02 20:34:19 +000015#if defined(__WATCOMC__) && !defined(__QNX__)
Guido van Rossumbceeac81996-05-23 22:53:47 +000016#include <i86.h>
17#else
Guido van Rossumcac6c721996-09-06 13:34:02 +000018#ifdef MS_WINDOWS
Mark Hammond975e3922002-07-16 01:29:19 +000019#define WIN32_LEAN_AND_MEAN
Guido van Rossum258ccd42001-03-02 06:53:29 +000020#include <windows.h>
Mark Hammond975e3922002-07-16 01:29:19 +000021#include "pythread.h"
22
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000023#if defined(__BORLANDC__)
Guido van Rossumb2fb3641996-09-07 00:47:35 +000024/* These overrides not needed for Win32 */
Guido van Rossumb6775db1994-08-01 11:34:53 +000025#define timezone _timezone
Guido van Rossumcc081121995-03-14 15:05:41 +000026#define tzname _tzname
27#define daylight _daylight
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000028#endif /* __BORLANDC__ */
Guido van Rossumcac6c721996-09-06 13:34:02 +000029#endif /* MS_WINDOWS */
Guido van Rossum7bf22de1997-12-02 20:34:19 +000030#endif /* !__WATCOMC__ || __QNX__ */
Guido van Rossum234f9421993-06-17 12:35:49 +000031
Andrew MacIntyre7bf68332002-03-03 02:59:16 +000032#if defined(PYOS_OS2)
33#define INCL_DOS
34#define INCL_ERRORS
35#include <os2.h>
36#endif
37
Guido van Rossum8e9ebfd1997-11-22 21:53:48 +000038#if defined(PYCC_VACPP)
Guido van Rossum26452411998-09-28 22:07:11 +000039#include <sys/time.h>
Guido van Rossum8e9ebfd1997-11-22 21:53:48 +000040#endif
41
Victor Stinnera8ec5ea2012-03-13 00:25:42 +010042#if defined(__APPLE__)
43#include <mach/mach_time.h>
44#endif
45
Guido van Rossum234f9421993-06-17 12:35:49 +000046/* Forward declarations */
Tim Petersdbd9ba62000-07-09 03:09:57 +000047static int floatsleep(double);
Victor Stinner071eca32012-03-15 01:17:09 +010048static PyObject* floattime(void);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000049
Barry Warsaw9a2a8a81996-12-06 23:32:14 +000050static PyObject *
Victor Stinner4195b5c2012-02-08 23:03:19 +010051time_time(PyObject *self, PyObject *unused)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000052{
Victor Stinner071eca32012-03-15 01:17:09 +010053 return floattime();
Guido van Rossumb6775db1994-08-01 11:34:53 +000054}
55
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000056PyDoc_STRVAR(time_doc,
Victor Stinner4195b5c2012-02-08 23:03:19 +010057"time() -> floating point number\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +000058\n\
59Return the current time in seconds since the Epoch.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000060Fractions of a second may be present if the system clock provides them.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +000061
Victor Stinner85fdfa82012-01-27 00:38:48 +010062#if defined(HAVE_CLOCK)
63
64#ifndef CLOCKS_PER_SEC
65#ifdef CLK_TCK
66#define CLOCKS_PER_SEC CLK_TCK
67#else
68#define CLOCKS_PER_SEC 1000000
69#endif
70#endif
71
Victor Stinner4195b5c2012-02-08 23:03:19 +010072static PyObject *
73pyclock(void)
Victor Stinner85fdfa82012-01-27 00:38:48 +010074{
Victor Stinner4195b5c2012-02-08 23:03:19 +010075 clock_t value;
76 value = clock();
77 if (value == (clock_t)-1) {
Victor Stinner85fdfa82012-01-27 00:38:48 +010078 PyErr_SetString(PyExc_RuntimeError,
79 "the processor time used is not available "
80 "or its value cannot be represented");
Victor Stinner4195b5c2012-02-08 23:03:19 +010081 return NULL;
Victor Stinner85fdfa82012-01-27 00:38:48 +010082 }
Victor Stinner4195b5c2012-02-08 23:03:19 +010083 return PyFloat_FromDouble((double)value / CLOCKS_PER_SEC);
Victor Stinner85fdfa82012-01-27 00:38:48 +010084}
85#endif /* HAVE_CLOCK */
86
Thomas Wouters477c8d52006-05-27 19:21:47 +000087#if defined(MS_WINDOWS) && !defined(__BORLANDC__)
Victor Stinner9122fdd2011-07-04 13:55:40 +020088/* Win32 has better clock replacement; we have our own version, due to Mark
89 Hammond and Tim Peters */
Victor Stinner4195b5c2012-02-08 23:03:19 +010090static PyObject *
91win32_clock(int fallback)
Guido van Rossum3917c221997-04-02 05:35:28 +000092{
Victor Stinner8b302012012-02-07 23:29:46 +010093 static LONGLONG cpu_frequency = 0;
Victor Stinner4195b5c2012-02-08 23:03:19 +010094 static LONGLONG ctrStart;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000095 LARGE_INTEGER now;
Victor Stinner4195b5c2012-02-08 23:03:19 +010096 double diff;
Guido van Rossum3917c221997-04-02 05:35:28 +000097
Victor Stinner8b302012012-02-07 23:29:46 +010098 if (cpu_frequency == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000099 LARGE_INTEGER freq;
Victor Stinner8b302012012-02-07 23:29:46 +0100100 QueryPerformanceCounter(&now);
Victor Stinner4195b5c2012-02-08 23:03:19 +0100101 ctrStart = now.QuadPart;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000102 if (!QueryPerformanceFrequency(&freq) || freq.QuadPart == 0) {
103 /* Unlikely to happen - this works on all intel
104 machines at least! Revert to clock() */
Victor Stinner4195b5c2012-02-08 23:03:19 +0100105 if (fallback)
106 return pyclock();
107 else
108 return PyErr_SetFromWindowsErr(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000109 }
Victor Stinner8b302012012-02-07 23:29:46 +0100110 cpu_frequency = freq.QuadPart;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000111 }
112 QueryPerformanceCounter(&now);
Victor Stinner4195b5c2012-02-08 23:03:19 +0100113 diff = (double)(now.QuadPart - ctrStart);
114 return PyFloat_FromDouble(diff / (double)cpu_frequency);
Guido van Rossum3917c221997-04-02 05:35:28 +0000115}
Victor Stinner8b302012012-02-07 23:29:46 +0100116#endif
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000117
Victor Stinner8b302012012-02-07 23:29:46 +0100118#if (defined(MS_WINDOWS) && !defined(__BORLANDC__)) || defined(HAVE_CLOCK)
Victor Stinner9122fdd2011-07-04 13:55:40 +0200119static PyObject *
Victor Stinner4195b5c2012-02-08 23:03:19 +0100120time_clock(PyObject *self, PyObject *unused)
Victor Stinner9122fdd2011-07-04 13:55:40 +0200121{
Victor Stinner8b302012012-02-07 23:29:46 +0100122#if defined(MS_WINDOWS) && !defined(__BORLANDC__)
Victor Stinner4195b5c2012-02-08 23:03:19 +0100123 return win32_clock(1);
Victor Stinner8b302012012-02-07 23:29:46 +0100124#else
Victor Stinner4195b5c2012-02-08 23:03:19 +0100125 return pyclock();
Victor Stinner8b302012012-02-07 23:29:46 +0100126#endif
Victor Stinner9122fdd2011-07-04 13:55:40 +0200127}
Victor Stinner9122fdd2011-07-04 13:55:40 +0200128
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000129PyDoc_STRVAR(clock_doc,
Victor Stinner4195b5c2012-02-08 23:03:19 +0100130"clock() -> floating point number\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000131\n\
132Return the CPU time or real time since the start of the process or since\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000133the first call to clock(). This has as much precision as the system\n\
134records.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000135#endif
136
Victor Stinnere0be4232011-10-25 13:06:09 +0200137#ifdef HAVE_CLOCK_GETTIME
138static PyObject *
Victor Stinner4195b5c2012-02-08 23:03:19 +0100139time_clock_gettime(PyObject *self, PyObject *args)
Victor Stinnere0be4232011-10-25 13:06:09 +0200140{
141 int ret;
Victor Stinnerb8d01692012-04-13 23:44:05 +0200142 int clk_id;
Victor Stinnere0be4232011-10-25 13:06:09 +0200143 struct timespec tp;
144
Victor Stinner4195b5c2012-02-08 23:03:19 +0100145 if (!PyArg_ParseTuple(args, "i:clock_gettime", &clk_id))
Victor Stinnere0be4232011-10-25 13:06:09 +0200146 return NULL;
147
148 ret = clock_gettime((clockid_t)clk_id, &tp);
Antoine Pitrou2c085602012-01-18 01:41:44 +0100149 if (ret != 0) {
Victor Stinnere0be4232011-10-25 13:06:09 +0200150 PyErr_SetFromErrno(PyExc_IOError);
Antoine Pitrou2c085602012-01-18 01:41:44 +0100151 return NULL;
152 }
Victor Stinner4195b5c2012-02-08 23:03:19 +0100153
154 return PyFloat_FromDouble(tp.tv_sec + tp.tv_nsec * 1e-9);
Victor Stinnere0be4232011-10-25 13:06:09 +0200155}
156
157PyDoc_STRVAR(clock_gettime_doc,
Victor Stinner4195b5c2012-02-08 23:03:19 +0100158"clock_gettime(clk_id) -> floating point number\n\
Victor Stinnere0be4232011-10-25 13:06:09 +0200159\n\
160Return the time of the specified clock clk_id.");
Victor Stinner30d79472012-04-03 00:45:07 +0200161
162static PyObject *
163time_clock_settime(PyObject *self, PyObject *args)
164{
Victor Stinnerb8d01692012-04-13 23:44:05 +0200165 int clk_id;
Victor Stinner30d79472012-04-03 00:45:07 +0200166 PyObject *obj;
167 struct timespec tp;
168 int ret;
169
170 if (!PyArg_ParseTuple(args, "iO:clock_settime", &clk_id, &obj))
171 return NULL;
172
173 if (_PyTime_ObjectToTimespec(obj, &tp.tv_sec, &tp.tv_nsec) == -1)
174 return NULL;
175
176 ret = clock_settime((clockid_t)clk_id, &tp);
177 if (ret != 0) {
178 PyErr_SetFromErrno(PyExc_IOError);
179 return NULL;
180 }
181 Py_RETURN_NONE;
182}
183
184PyDoc_STRVAR(clock_settime_doc,
185"clock_settime(clk_id, time)\n\
186\n\
187Set the time of the specified clock clk_id.");
Victor Stinnere0be4232011-10-25 13:06:09 +0200188
Victor Stinnere0be4232011-10-25 13:06:09 +0200189static PyObject *
Victor Stinner4195b5c2012-02-08 23:03:19 +0100190time_clock_getres(PyObject *self, PyObject *args)
Victor Stinnere0be4232011-10-25 13:06:09 +0200191{
192 int ret;
Victor Stinnerb8d01692012-04-13 23:44:05 +0200193 int clk_id;
Victor Stinnere0be4232011-10-25 13:06:09 +0200194 struct timespec tp;
195
Victor Stinner4195b5c2012-02-08 23:03:19 +0100196 if (!PyArg_ParseTuple(args, "i:clock_getres", &clk_id))
Victor Stinnere0be4232011-10-25 13:06:09 +0200197 return NULL;
198
199 ret = clock_getres((clockid_t)clk_id, &tp);
Antoine Pitrou2c085602012-01-18 01:41:44 +0100200 if (ret != 0) {
Victor Stinnere0be4232011-10-25 13:06:09 +0200201 PyErr_SetFromErrno(PyExc_IOError);
Antoine Pitrou2c085602012-01-18 01:41:44 +0100202 return NULL;
203 }
Victor Stinner4195b5c2012-02-08 23:03:19 +0100204
205 return PyFloat_FromDouble(tp.tv_sec + tp.tv_nsec * 1e-9);
Victor Stinnere0be4232011-10-25 13:06:09 +0200206}
207
208PyDoc_STRVAR(clock_getres_doc,
Victor Stinner4195b5c2012-02-08 23:03:19 +0100209"clock_getres(clk_id) -> floating point number\n\
Victor Stinnere0be4232011-10-25 13:06:09 +0200210\n\
211Return the resolution (precision) of the specified clock clk_id.");
Victor Stinnerb8d01692012-04-13 23:44:05 +0200212#endif /* HAVE_CLOCK_GETTIME */
Victor Stinnere0be4232011-10-25 13:06:09 +0200213
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000214static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000215time_sleep(PyObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000216{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000217 double secs;
218 if (!PyArg_ParseTuple(args, "d:sleep", &secs))
219 return NULL;
Victor Stinner7f53a502011-07-05 22:00:25 +0200220 if (secs < 0) {
221 PyErr_SetString(PyExc_ValueError,
222 "sleep length must be non-negative");
223 return NULL;
224 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000225 if (floatsleep(secs) != 0)
226 return NULL;
227 Py_INCREF(Py_None);
228 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000229}
230
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000231PyDoc_STRVAR(sleep_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000232"sleep(seconds)\n\
233\n\
234Delay execution for a given number of seconds. The argument may be\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000235a floating point number for subsecond precision.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000236
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000237static PyStructSequence_Field struct_time_type_fields[] = {
Alexander Belopolsky69f3fd02010-06-05 15:04:51 +0000238 {"tm_year", "year, for example, 1993"},
239 {"tm_mon", "month of year, range [1, 12]"},
240 {"tm_mday", "day of month, range [1, 31]"},
241 {"tm_hour", "hours, range [0, 23]"},
242 {"tm_min", "minutes, range [0, 59]"},
243 {"tm_sec", "seconds, range [0, 61])"},
244 {"tm_wday", "day of week, range [0, 6], Monday is 0"},
245 {"tm_yday", "day of year, range [1, 366]"},
246 {"tm_isdst", "1 if summer time is in effect, 0 if not, and -1 if unknown"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000247 {0}
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000248};
249
250static PyStructSequence_Desc struct_time_type_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000251 "time.struct_time",
Alexander Belopolsky69f3fd02010-06-05 15:04:51 +0000252 "The time value as returned by gmtime(), localtime(), and strptime(), and\n"
253 " accepted by asctime(), mktime() and strftime(). May be considered as a\n"
254 " sequence of 9 integers.\n\n"
255 " Note that several fields' values are not the same as those defined by\n"
256 " the C language standard for struct tm. For example, the value of the\n"
257 " field tm_year is the actual year, not year - 1900. See individual\n"
258 " fields' descriptions for details.",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000259 struct_time_type_fields,
260 9,
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000261};
Tim Peters9ad4b682002-02-13 05:14:18 +0000262
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000263static int initialized;
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000264static PyTypeObject StructTimeType;
265
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000266static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000267tmtotuple(struct tm *p)
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000268{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000269 PyObject *v = PyStructSequence_New(&StructTimeType);
270 if (v == NULL)
271 return NULL;
Tim Peters9ad4b682002-02-13 05:14:18 +0000272
Christian Heimes217cfd12007-12-02 14:31:20 +0000273#define SET(i,val) PyStructSequence_SET_ITEM(v, i, PyLong_FromLong((long) val))
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000274
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000275 SET(0, p->tm_year + 1900);
276 SET(1, p->tm_mon + 1); /* Want January == 1 */
277 SET(2, p->tm_mday);
278 SET(3, p->tm_hour);
279 SET(4, p->tm_min);
280 SET(5, p->tm_sec);
281 SET(6, (p->tm_wday + 6) % 7); /* Want Monday == 0 */
282 SET(7, p->tm_yday + 1); /* Want January, 1 == 1 */
283 SET(8, p->tm_isdst);
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000284#undef SET
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000285 if (PyErr_Occurred()) {
286 Py_XDECREF(v);
287 return NULL;
288 }
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000289
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000290 return v;
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000291}
292
Fred Drakef901abd2004-08-03 17:58:55 +0000293/* Parse arg tuple that can contain an optional float-or-None value;
294 format needs to be "|O:name".
295 Returns non-zero on success (parallels PyArg_ParseTuple).
296*/
297static int
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100298parse_time_t_args(PyObject *args, char *format, time_t *pwhen)
Fred Drakef901abd2004-08-03 17:58:55 +0000299{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000300 PyObject *ot = NULL;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100301 time_t whent;
Fred Drakef901abd2004-08-03 17:58:55 +0000302
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000303 if (!PyArg_ParseTuple(args, format, &ot))
304 return 0;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100305 if (ot == NULL || ot == Py_None) {
306 whent = time(NULL);
307 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000308 else {
Victor Stinner5d272cc2012-03-13 13:35:55 +0100309 if (_PyTime_ObjectToTime_t(ot, &whent) == -1)
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100310 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000311 }
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100312 *pwhen = whent;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000313 return 1;
Fred Drakef901abd2004-08-03 17:58:55 +0000314}
315
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000316static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000317time_gmtime(PyObject *self, PyObject *args)
Guido van Rossum234f9421993-06-17 12:35:49 +0000318{
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100319 time_t when;
320 struct tm buf, *local;
321
322 if (!parse_time_t_args(args, "|O:gmtime", &when))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000323 return NULL;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100324
325 errno = 0;
326 local = gmtime(&when);
327 if (local == NULL) {
328#ifdef EINVAL
329 if (errno == 0)
330 errno = EINVAL;
331#endif
332 return PyErr_SetFromErrno(PyExc_OSError);
333 }
334 buf = *local;
335 return tmtotuple(&buf);
Guido van Rossum234f9421993-06-17 12:35:49 +0000336}
337
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000338PyDoc_STRVAR(gmtime_doc,
Christian Heimes9a371592007-12-28 14:08:13 +0000339"gmtime([seconds]) -> (tm_year, tm_mon, tm_mday, tm_hour, tm_min,\n\
Fred Drake193a3f62002-03-12 21:38:49 +0000340 tm_sec, tm_wday, tm_yday, tm_isdst)\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000341\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000342Convert seconds since the Epoch to a time tuple expressing UTC (a.k.a.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000343GMT). When 'seconds' is not passed in, convert the current time instead.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000344
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100345static int
346pylocaltime(time_t *timep, struct tm *result)
347{
348 struct tm *local;
349
350 assert (timep != NULL);
351 local = localtime(timep);
352 if (local == NULL) {
353 /* unconvertible time */
354#ifdef EINVAL
355 if (errno == 0)
356 errno = EINVAL;
357#endif
358 PyErr_SetFromErrno(PyExc_OSError);
359 return -1;
360 }
361 *result = *local;
362 return 0;
363}
364
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000365static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000366time_localtime(PyObject *self, PyObject *args)
Guido van Rossum234f9421993-06-17 12:35:49 +0000367{
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100368 time_t when;
369 struct tm buf;
370
371 if (!parse_time_t_args(args, "|O:localtime", &when))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000372 return NULL;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100373 if (pylocaltime(&when, &buf) == 1)
374 return NULL;
375 return tmtotuple(&buf);
Guido van Rossum234f9421993-06-17 12:35:49 +0000376}
377
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000378PyDoc_STRVAR(localtime_doc,
Christian Heimes9a371592007-12-28 14:08:13 +0000379"localtime([seconds]) -> (tm_year,tm_mon,tm_mday,tm_hour,tm_min,\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000380 tm_sec,tm_wday,tm_yday,tm_isdst)\n\
Martin v. Löwisb3cfc1d2001-12-02 12:27:43 +0000381\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000382Convert seconds since the Epoch to a time tuple expressing local time.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000383When 'seconds' is not passed in, convert the current time instead.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000384
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000385/* Convert 9-item tuple to tm structure. Return 1 on success, set
386 * an exception and return 0 on error.
387 */
Guido van Rossum9e90a671993-06-24 11:10:19 +0000388static int
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000389gettmarg(PyObject *args, struct tm *p)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000390{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000391 int y;
Guido van Rossumcfbaecc1998-08-25 14:51:12 +0000392
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000393 memset((void *) p, '\0', sizeof(struct tm));
Guido van Rossumb9081262007-08-25 03:14:09 +0000394
Alexander Belopolsky610e5442011-01-06 21:57:06 +0000395 if (!PyTuple_Check(args)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000396 PyErr_SetString(PyExc_TypeError,
397 "Tuple or struct_time argument required");
398 return 0;
399 }
Skip Montanaro41cfce92007-08-24 21:11:00 +0000400
Alexander Belopolsky610e5442011-01-06 21:57:06 +0000401 if (!PyArg_ParseTuple(args, "iiiiiiiii",
402 &y, &p->tm_mon, &p->tm_mday,
403 &p->tm_hour, &p->tm_min, &p->tm_sec,
404 &p->tm_wday, &p->tm_yday, &p->tm_isdst))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000405 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000406 p->tm_year = y - 1900;
407 p->tm_mon--;
408 p->tm_wday = (p->tm_wday + 1) % 7;
409 p->tm_yday--;
410 return 1;
Guido van Rossum9e90a671993-06-24 11:10:19 +0000411}
412
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000413/* Check values of the struct tm fields before it is passed to strftime() and
414 * asctime(). Return 1 if all values are valid, otherwise set an exception
415 * and returns 0.
416 */
Victor Stinneref128102010-10-07 01:00:52 +0000417static int
418checktm(struct tm* buf)
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000419{
Victor Stinneref128102010-10-07 01:00:52 +0000420 /* Checks added to make sure strftime() and asctime() does not crash Python by
421 indexing blindly into some array for a textual representation
422 by some bad index (fixes bug #897625 and #6608).
423
424 Also support values of zero from Python code for arguments in which
425 that is out of range by forcing that value to the lowest value that
426 is valid (fixed bug #1520914).
427
428 Valid ranges based on what is allowed in struct tm:
429
430 - tm_year: [0, max(int)] (1)
431 - tm_mon: [0, 11] (2)
432 - tm_mday: [1, 31]
433 - tm_hour: [0, 23]
434 - tm_min: [0, 59]
435 - tm_sec: [0, 60]
436 - tm_wday: [0, 6] (1)
437 - tm_yday: [0, 365] (2)
438 - tm_isdst: [-max(int), max(int)]
439
440 (1) gettmarg() handles bounds-checking.
441 (2) Python's acceptable range is one greater than the range in C,
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000442 thus need to check against automatic decrement by gettmarg().
443 */
444 if (buf->tm_mon == -1)
445 buf->tm_mon = 0;
446 else if (buf->tm_mon < 0 || buf->tm_mon > 11) {
447 PyErr_SetString(PyExc_ValueError, "month out of range");
448 return 0;
449 }
450 if (buf->tm_mday == 0)
451 buf->tm_mday = 1;
452 else if (buf->tm_mday < 0 || buf->tm_mday > 31) {
453 PyErr_SetString(PyExc_ValueError, "day of month out of range");
454 return 0;
455 }
456 if (buf->tm_hour < 0 || buf->tm_hour > 23) {
457 PyErr_SetString(PyExc_ValueError, "hour out of range");
458 return 0;
459 }
460 if (buf->tm_min < 0 || buf->tm_min > 59) {
461 PyErr_SetString(PyExc_ValueError, "minute out of range");
462 return 0;
463 }
464 if (buf->tm_sec < 0 || buf->tm_sec > 61) {
465 PyErr_SetString(PyExc_ValueError, "seconds out of range");
466 return 0;
467 }
468 /* tm_wday does not need checking of its upper-bound since taking
469 ``% 7`` in gettmarg() automatically restricts the range. */
470 if (buf->tm_wday < 0) {
471 PyErr_SetString(PyExc_ValueError, "day of week out of range");
472 return 0;
473 }
474 if (buf->tm_yday == -1)
475 buf->tm_yday = 0;
476 else if (buf->tm_yday < 0 || buf->tm_yday > 365) {
477 PyErr_SetString(PyExc_ValueError, "day of year out of range");
478 return 0;
479 }
480 return 1;
481}
482
Victor Stinnerc1f32ca2011-10-14 02:36:13 +0200483#ifdef MS_WINDOWS
484 /* wcsftime() doesn't format correctly time zones, see issue #10653 */
485# undef HAVE_WCSFTIME
486#endif
487
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000488#ifdef HAVE_STRFTIME
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000489#ifdef HAVE_WCSFTIME
490#define time_char wchar_t
491#define format_time wcsftime
492#define time_strlen wcslen
493#else
494#define time_char char
495#define format_time strftime
496#define time_strlen strlen
497#endif
498
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000499static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000500time_strftime(PyObject *self, PyObject *args)
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000501{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000502 PyObject *tup = NULL;
503 struct tm buf;
504 const time_char *fmt;
Victor Stinnerb2904782010-09-29 10:34:19 +0000505#ifdef HAVE_WCSFTIME
506 wchar_t *format;
507#else
508 PyObject *format;
509#endif
Victor Stinneref128102010-10-07 01:00:52 +0000510 PyObject *format_arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000511 size_t fmtlen, buflen;
Victor Stinnerb2904782010-09-29 10:34:19 +0000512 time_char *outbuf = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000513 size_t i;
Victor Stinnerb2904782010-09-29 10:34:19 +0000514 PyObject *ret = NULL;
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000515
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000516 memset((void *) &buf, '\0', sizeof(buf));
Guido van Rossum1f41f841998-04-27 19:04:26 +0000517
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000518 /* Will always expect a unicode string to be passed as format.
519 Given that there's no str type anymore in py3k this seems safe.
520 */
Victor Stinneref128102010-10-07 01:00:52 +0000521 if (!PyArg_ParseTuple(args, "U|O:strftime", &format_arg, &tup))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000522 return NULL;
Thomas Woutersfe385252001-01-19 23:16:56 +0000523
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000524 if (tup == NULL) {
525 time_t tt = time(NULL);
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100526 if (pylocaltime(&tt, &buf) == -1)
527 return NULL;
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000528 }
529 else if (!gettmarg(tup, &buf) || !checktm(&buf))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000530 return NULL;
Guido van Rossum10b164a2001-09-25 13:59:01 +0000531
Victor Stinner06ec45e2011-01-08 03:35:36 +0000532#if defined(_MSC_VER) || defined(sun)
Victor Stinner73ea29c2011-01-08 01:56:31 +0000533 if (buf.tm_year + 1900 < 1 || 9999 < buf.tm_year + 1900) {
Victor Stinner6f0e4f92011-03-21 02:14:53 +0100534 PyErr_SetString(PyExc_ValueError,
535 "strftime() requires year in [1; 9999]");
Alexander Belopolsky0dd06f42011-01-08 01:23:02 +0000536 return NULL;
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000537 }
Victor Stinner73ea29c2011-01-08 01:56:31 +0000538#endif
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000539
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000540 /* Normalize tm_isdst just in case someone foolishly implements %Z
541 based on the assumption that tm_isdst falls within the range of
542 [-1, 1] */
543 if (buf.tm_isdst < -1)
544 buf.tm_isdst = -1;
545 else if (buf.tm_isdst > 1)
546 buf.tm_isdst = 1;
Brett Cannond1080a32004-03-02 04:38:10 +0000547
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000548#ifdef HAVE_WCSFTIME
Victor Stinnerbeb4135b2010-10-07 01:02:42 +0000549 format = PyUnicode_AsWideCharString(format_arg, NULL);
Victor Stinnerb2904782010-09-29 10:34:19 +0000550 if (format == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000551 return NULL;
Victor Stinnerb2904782010-09-29 10:34:19 +0000552 fmt = format;
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000553#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000554 /* Convert the unicode string to an ascii one */
Victor Stinner1b579672011-12-17 05:47:23 +0100555 format = PyUnicode_EncodeLocale(format_arg, "surrogateescape");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000556 if (format == NULL)
557 return NULL;
558 fmt = PyBytes_AS_STRING(format);
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000559#endif
Amaury Forgeot d'Arcb5be6d42009-03-02 23:52:57 +0000560
Stefan Krah4aea7d32012-02-27 16:30:26 +0100561#if defined(MS_WINDOWS) && !defined(HAVE_WCSFTIME)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000562 /* check that the format string contains only valid directives */
Victor Stinner5a3ff792011-10-16 19:08:23 +0200563 for(outbuf = strchr(fmt, '%');
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000564 outbuf != NULL;
Victor Stinner5a3ff792011-10-16 19:08:23 +0200565 outbuf = strchr(outbuf+2, '%'))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000566 {
567 if (outbuf[1]=='#')
568 ++outbuf; /* not documented by python, */
569 if (outbuf[1]=='\0' ||
Victor Stinner5a3ff792011-10-16 19:08:23 +0200570 !strchr("aAbBcdHIjmMpSUwWxXyYzZ%", outbuf[1]))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000571 {
572 PyErr_SetString(PyExc_ValueError, "Invalid format string");
Stefan Krah4aea7d32012-02-27 16:30:26 +0100573 Py_DECREF(format);
574 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000575 }
576 }
Amaury Forgeot d'Arcb5be6d42009-03-02 23:52:57 +0000577#endif
578
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000579 fmtlen = time_strlen(fmt);
Guido van Rossumc222ec21999-02-23 00:00:10 +0000580
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000581 /* I hate these functions that presume you know how big the output
582 * will be ahead of time...
583 */
584 for (i = 1024; ; i += i) {
Victor Stinner136ea492011-12-17 22:37:18 +0100585#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100586 int err;
Victor Stinner136ea492011-12-17 22:37:18 +0100587#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000588 outbuf = (time_char *)PyMem_Malloc(i*sizeof(time_char));
589 if (outbuf == NULL) {
Victor Stinnerb2904782010-09-29 10:34:19 +0000590 PyErr_NoMemory();
591 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000592 }
593 buflen = format_time(outbuf, i, fmt, &buf);
Victor Stinner136ea492011-12-17 22:37:18 +0100594#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100595 err = errno;
Victor Stinner136ea492011-12-17 22:37:18 +0100596#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000597 if (buflen > 0 || i >= 256 * fmtlen) {
598 /* If the buffer is 256 times as long as the format,
599 it's probably not failing for lack of room!
600 More likely, the format yields an empty result,
601 e.g. an empty format, or %Z when the timezone
602 is unknown. */
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000603#ifdef HAVE_WCSFTIME
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000604 ret = PyUnicode_FromWideChar(outbuf, buflen);
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000605#else
Victor Stinner1b579672011-12-17 05:47:23 +0100606 ret = PyUnicode_DecodeLocaleAndSize(outbuf, buflen,
607 "surrogateescape");
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000608#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000609 PyMem_Free(outbuf);
Victor Stinnerb2904782010-09-29 10:34:19 +0000610 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000611 }
612 PyMem_Free(outbuf);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000613#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000614 /* VisualStudio .NET 2005 does this properly */
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100615 if (buflen == 0 && err == EINVAL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000616 PyErr_SetString(PyExc_ValueError, "Invalid format string");
Victor Stinnerb2904782010-09-29 10:34:19 +0000617 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000618 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000619#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000620 }
Victor Stinnerb2904782010-09-29 10:34:19 +0000621#ifdef HAVE_WCSFTIME
622 PyMem_Free(format);
623#else
624 Py_DECREF(format);
625#endif
626 return ret;
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000627}
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000628
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000629#undef time_char
630#undef format_time
631
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000632PyDoc_STRVAR(strftime_doc,
Thomas Woutersfe385252001-01-19 23:16:56 +0000633"strftime(format[, tuple]) -> string\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000634\n\
635Convert a time tuple to a string according to a format specification.\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000636See the library reference manual for formatting codes. When the time tuple\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000637is not present, current time as returned by localtime() is used.");
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000638#endif /* HAVE_STRFTIME */
639
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000640static PyObject *
641time_strptime(PyObject *self, PyObject *args)
642{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000643 PyObject *strptime_module = PyImport_ImportModuleNoBlock("_strptime");
644 PyObject *strptime_result;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200645 _Py_IDENTIFIER(_strptime_time);
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000646
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000647 if (!strptime_module)
648 return NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200649 strptime_result = _PyObject_CallMethodId(strptime_module,
650 &PyId__strptime_time, "O", args);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000651 Py_DECREF(strptime_module);
652 return strptime_result;
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000653}
654
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000655
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000656PyDoc_STRVAR(strptime_doc,
Brett Cannon20def8b2003-07-01 05:16:08 +0000657"strptime(string, format) -> struct_time\n\
Martin v. Löwisb3cfc1d2001-12-02 12:27:43 +0000658\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000659Parse a string to a time tuple according to a format specification.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000660See the library reference manual for formatting codes (same as strftime()).");
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000661
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000662static PyObject *
663_asctime(struct tm *timeptr)
664{
665 /* Inspired by Open Group reference implementation available at
666 * http://pubs.opengroup.org/onlinepubs/009695399/functions/asctime.html */
Victor Stinner499dfcf2011-03-21 13:26:24 +0100667 static char wday_name[7][4] = {
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000668 "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
669 };
Victor Stinner499dfcf2011-03-21 13:26:24 +0100670 static char mon_name[12][4] = {
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000671 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
672 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
673 };
Victor Stinner499dfcf2011-03-21 13:26:24 +0100674 return PyUnicode_FromFormat(
675 "%s %s%3d %.2d:%.2d:%.2d %d",
676 wday_name[timeptr->tm_wday],
677 mon_name[timeptr->tm_mon],
678 timeptr->tm_mday, timeptr->tm_hour,
679 timeptr->tm_min, timeptr->tm_sec,
680 1900 + timeptr->tm_year);
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000681}
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000682
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000683static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000684time_asctime(PyObject *self, PyObject *args)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000685{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000686 PyObject *tup = NULL;
687 struct tm buf;
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000688
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000689 if (!PyArg_UnpackTuple(args, "asctime", 0, 1, &tup))
690 return NULL;
691 if (tup == NULL) {
692 time_t tt = time(NULL);
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100693 if (pylocaltime(&tt, &buf) == -1)
694 return NULL;
695
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000696 } else if (!gettmarg(tup, &buf) || !checktm(&buf))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000697 return NULL;
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000698 return _asctime(&buf);
Guido van Rossum9e90a671993-06-24 11:10:19 +0000699}
700
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000701PyDoc_STRVAR(asctime_doc,
Thomas Woutersfe385252001-01-19 23:16:56 +0000702"asctime([tuple]) -> string\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000703\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000704Convert a time tuple to a string, e.g. 'Sat Jun 06 16:26:11 1998'.\n\
705When the time tuple is not present, current time as returned by localtime()\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000706is used.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000707
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000708static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000709time_ctime(PyObject *self, PyObject *args)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000710{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000711 time_t tt;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100712 struct tm buf;
713 if (!parse_time_t_args(args, "|O:ctime", &tt))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000714 return NULL;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100715 if (pylocaltime(&tt, &buf) == -1)
Alexander Belopolsky5da468f2011-01-04 17:15:52 +0000716 return NULL;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100717 return _asctime(&buf);
Guido van Rossum9e90a671993-06-24 11:10:19 +0000718}
719
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000720PyDoc_STRVAR(ctime_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000721"ctime(seconds) -> string\n\
722\n\
723Convert a time in seconds since the Epoch to a string in local time.\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000724This is equivalent to asctime(localtime(seconds)). When the time tuple is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000725not present, current time as returned by localtime() is used.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000726
Guido van Rossum60cd8131998-03-06 17:16:21 +0000727#ifdef HAVE_MKTIME
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000728static PyObject *
Victor Stinner4195b5c2012-02-08 23:03:19 +0100729time_mktime(PyObject *self, PyObject *tup)
Guido van Rossum234f9421993-06-17 12:35:49 +0000730{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000731 struct tm buf;
732 time_t tt;
733 if (!gettmarg(tup, &buf))
734 return NULL;
Alexander Belopolskyb7d40d12011-01-11 01:21:25 +0000735 buf.tm_wday = -1; /* sentinel; original value ignored */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000736 tt = mktime(&buf);
Alexander Belopolskyb7d40d12011-01-11 01:21:25 +0000737 /* Return value of -1 does not necessarily mean an error, but tm_wday
Ezio Melotti13925002011-03-16 11:05:33 +0200738 * cannot remain set to -1 if mktime succeeded. */
Alexander Belopolskyb7d40d12011-01-11 01:21:25 +0000739 if (tt == (time_t)(-1) && buf.tm_wday == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000740 PyErr_SetString(PyExc_OverflowError,
741 "mktime argument out of range");
742 return NULL;
743 }
Victor Stinner4195b5c2012-02-08 23:03:19 +0100744 return PyFloat_FromDouble((double)tt);
Guido van Rossum234f9421993-06-17 12:35:49 +0000745}
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000746
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000747PyDoc_STRVAR(mktime_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000748"mktime(tuple) -> floating point number\n\
749\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000750Convert a time tuple in local time to seconds since the Epoch.");
Guido van Rossum60cd8131998-03-06 17:16:21 +0000751#endif /* HAVE_MKTIME */
Guido van Rossum234f9421993-06-17 12:35:49 +0000752
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000753#ifdef HAVE_WORKING_TZSET
Martin v. Löwis1a214512008-06-11 05:26:20 +0000754static void PyInit_timezone(PyObject *module);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000755
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000756static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000757time_tzset(PyObject *self, PyObject *unused)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000758{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000759 PyObject* m;
Fred Drake9bb74322002-04-01 14:49:59 +0000760
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000761 m = PyImport_ImportModuleNoBlock("time");
762 if (m == NULL) {
763 return NULL;
764 }
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000765
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000766 tzset();
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000767
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000768 /* Reset timezone, altzone, daylight and tzname */
769 PyInit_timezone(m);
770 Py_DECREF(m);
Tim Peters1b6f7a92004-06-20 02:50:16 +0000771
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000772 Py_INCREF(Py_None);
773 return Py_None;
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000774}
775
776PyDoc_STRVAR(tzset_doc,
R. David Murray4d55bf92010-12-14 00:55:46 +0000777"tzset()\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000778\n\
779Initialize, or reinitialize, the local timezone to the value stored in\n\
780os.environ['TZ']. The TZ environment variable should be specified in\n\
Neal Norwitzdc8e1942004-07-20 22:34:37 +0000781standard Unix timezone format as documented in the tzset man page\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000782(eg. 'US/Eastern', 'Europe/Amsterdam'). Unknown timezones will silently\n\
783fall back to UTC. If the TZ environment variable is not set, the local\n\
784timezone is set to the systems best guess of wallclock time.\n\
785Changing the TZ environment variable without calling tzset *may* change\n\
786the local timezone used by methods such as localtime, but this behaviour\n\
787should not be relied on.");
788#endif /* HAVE_WORKING_TZSET */
789
Victor Stinner071eca32012-03-15 01:17:09 +0100790static PyObject*
791steady_clock(int strict)
Victor Stinnerb94b2662012-01-18 01:50:21 +0100792{
793#if defined(MS_WINDOWS) && !defined(__BORLANDC__)
Victor Stinner071eca32012-03-15 01:17:09 +0100794 return win32_clock(!strict);
Victor Stinnera8ec5ea2012-03-13 00:25:42 +0100795#elif defined(__APPLE__)
Victor Stinner74eb6c02012-03-28 02:50:46 +0200796 static mach_timebase_info_data_t timebase;
797 uint64_t time;
Victor Stinnera8ec5ea2012-03-13 00:25:42 +0100798 double secs;
799
Victor Stinner74eb6c02012-03-28 02:50:46 +0200800 if (timebase.denom == 0) {
801 /* According to the Technical Q&A QA1398, mach_timebase_info() cannot
802 fail: https://developer.apple.com/library/mac/#qa/qa1398/ */
803 (void)mach_timebase_info(&timebase);
804 }
Victor Stinnera8ec5ea2012-03-13 00:25:42 +0100805
Victor Stinner74eb6c02012-03-28 02:50:46 +0200806 time = mach_absolute_time();
Victor Stinnera8ec5ea2012-03-13 00:25:42 +0100807 secs = (double)time * timebase.numer / timebase.denom * 1e-9;
808
809 return PyFloat_FromDouble(secs);
Victor Stinnerec919cc2012-03-15 00:58:32 +0100810#elif defined(HAVE_CLOCK_GETTIME)
Victor Stinner84860762012-03-26 22:53:14 +0200811 static int steady_clk_index = 0;
812 static int monotonic_clk_index = 0;
813 int *clk_index;
814 clockid_t steady_clk_ids[] = {
Victor Stinner8b302012012-02-07 23:29:46 +0100815#ifdef CLOCK_MONOTONIC_RAW
816 CLOCK_MONOTONIC_RAW,
817#endif
Victor Stinnerec919cc2012-03-15 00:58:32 +0100818 CLOCK_MONOTONIC,
819 CLOCK_REALTIME
Victor Stinner8b302012012-02-07 23:29:46 +0100820 };
Victor Stinner84860762012-03-26 22:53:14 +0200821 clockid_t monotonic_clk_ids[] = {
822#ifdef CLOCK_MONOTONIC_RAW
823 CLOCK_MONOTONIC_RAW,
824#endif
825 CLOCK_MONOTONIC
826 };
827 clockid_t *clk_ids;
828 int clk_ids_len;
Victor Stinner8b302012012-02-07 23:29:46 +0100829 int ret;
830 struct timespec tp;
831
Victor Stinner84860762012-03-26 22:53:14 +0200832 if (strict) {
833 clk_index = &monotonic_clk_index;
834 clk_ids = monotonic_clk_ids;
835 clk_ids_len = Py_ARRAY_LENGTH(monotonic_clk_ids);
836 }
837 else {
838 clk_index = &steady_clk_index;
839 clk_ids = steady_clk_ids;
840 clk_ids_len = Py_ARRAY_LENGTH(steady_clk_ids);
841 }
842
843 while (0 <= *clk_index) {
844 clockid_t clk_id = clk_ids[*clk_index];
Victor Stinner8b302012012-02-07 23:29:46 +0100845 ret = clock_gettime(clk_id, &tp);
846 if (ret == 0)
Victor Stinner4195b5c2012-02-08 23:03:19 +0100847 return PyFloat_FromDouble(tp.tv_sec + tp.tv_nsec * 1e-9);
Victor Stinner8b302012012-02-07 23:29:46 +0100848
Victor Stinner84860762012-03-26 22:53:14 +0200849 (*clk_index)++;
850 if (clk_ids_len <= *clk_index)
851 (*clk_index) = -1;
Victor Stinner8b302012012-02-07 23:29:46 +0100852 }
Victor Stinner071eca32012-03-15 01:17:09 +0100853 if (strict) {
854 PyErr_SetFromErrno(PyExc_OSError);
855 return NULL;
856 }
857 return floattime();
Victor Stinnerec919cc2012-03-15 00:58:32 +0100858#else
Victor Stinner071eca32012-03-15 01:17:09 +0100859 if (strict) {
860 PyErr_SetString(PyExc_NotImplementedError,
861 "no steady clock available on your platform");
862 return NULL;
863 }
864 return floattime();
Victor Stinner8b302012012-02-07 23:29:46 +0100865#endif
866}
867
Victor Stinner071eca32012-03-15 01:17:09 +0100868static PyObject *
869time_steady(PyObject *self, PyObject *args, PyObject *kwargs)
870{
871 static char *kwlist[] = {"strict", NULL};
872 int strict = 0;
873
874 if (!PyArg_ParseTupleAndKeywords(
875 args, kwargs, "|i:steady", kwlist,
876 &strict))
877 return NULL;
878
879 return steady_clock(strict);
880}
881
Victor Stinnerec919cc2012-03-15 00:58:32 +0100882PyDoc_STRVAR(steady_doc,
Victor Stinner071eca32012-03-15 01:17:09 +0100883"steady(strict=False) -> float\n\
Victor Stinner8b302012012-02-07 23:29:46 +0100884\n\
Victor Stinnerec919cc2012-03-15 00:58:32 +0100885Return the current time as a floating point number expressed in seconds.\n\
886This clock advances at a steady rate relative to real time and it may not\n\
887be adjusted. The reference point of the returned value is undefined so only\n\
888the difference of consecutive calls is valid.");
889
Victor Stinner8b302012012-02-07 23:29:46 +0100890
Martin v. Löwisd218dc12008-04-07 03:17:54 +0000891static void
Martin v. Löwis1a214512008-06-11 05:26:20 +0000892PyInit_timezone(PyObject *m) {
893 /* This code moved from PyInit_time wholesale to allow calling it from
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000894 time_tzset. In the future, some parts of it can be moved back
895 (for platforms that don't HAVE_WORKING_TZSET, when we know what they
896 are), and the extraneous calls to tzset(3) should be removed.
897 I haven't done this yet, as I don't want to change this code as
898 little as possible when introducing the time.tzset and time.tzsetwall
899 methods. This should simply be a method of doing the following once,
900 at the top of this function and removing the call to tzset() from
901 time_tzset():
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000902
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000903 #ifdef HAVE_TZSET
904 tzset()
905 #endif
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000906
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000907 And I'm lazy and hate C so nyer.
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000908 */
Guido van Rossum10b164a2001-09-25 13:59:01 +0000909#if defined(HAVE_TZNAME) && !defined(__GLIBC__) && !defined(__CYGWIN__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000910 PyObject *otz0, *otz1;
911 tzset();
Guido van Rossum26452411998-09-28 22:07:11 +0000912#ifdef PYOS_OS2
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000913 PyModule_AddIntConstant(m, "timezone", _timezone);
Guido van Rossum26452411998-09-28 22:07:11 +0000914#else /* !PYOS_OS2 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000915 PyModule_AddIntConstant(m, "timezone", timezone);
Guido van Rossum26452411998-09-28 22:07:11 +0000916#endif /* PYOS_OS2 */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000917#ifdef HAVE_ALTZONE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000918 PyModule_AddIntConstant(m, "altzone", altzone);
Guido van Rossumb6775db1994-08-01 11:34:53 +0000919#else
Guido van Rossum26452411998-09-28 22:07:11 +0000920#ifdef PYOS_OS2
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000921 PyModule_AddIntConstant(m, "altzone", _timezone-3600);
Guido van Rossum26452411998-09-28 22:07:11 +0000922#else /* !PYOS_OS2 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000923 PyModule_AddIntConstant(m, "altzone", timezone-3600);
Guido van Rossum26452411998-09-28 22:07:11 +0000924#endif /* PYOS_OS2 */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000925#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000926 PyModule_AddIntConstant(m, "daylight", daylight);
Victor Stinner1b579672011-12-17 05:47:23 +0100927 otz0 = PyUnicode_DecodeLocale(tzname[0], "surrogateescape");
928 otz1 = PyUnicode_DecodeLocale(tzname[1], "surrogateescape");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000929 PyModule_AddObject(m, "tzname", Py_BuildValue("(NN)", otz0, otz1));
Guido van Rossum10b164a2001-09-25 13:59:01 +0000930#else /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/
Martin v. Löwis60a5d722002-10-16 20:28:25 +0000931#ifdef HAVE_STRUCT_TM_TM_ZONE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000932 {
Guido van Rossum234f9421993-06-17 12:35:49 +0000933#define YEAR ((time_t)((365 * 24 + 6) * 3600))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000934 time_t t;
935 struct tm *p;
936 long janzone, julyzone;
937 char janname[10], julyname[10];
938 t = (time((time_t *)0) / YEAR) * YEAR;
939 p = localtime(&t);
940 janzone = -p->tm_gmtoff;
941 strncpy(janname, p->tm_zone ? p->tm_zone : " ", 9);
942 janname[9] = '\0';
943 t += YEAR/2;
944 p = localtime(&t);
945 julyzone = -p->tm_gmtoff;
946 strncpy(julyname, p->tm_zone ? p->tm_zone : " ", 9);
947 julyname[9] = '\0';
Guido van Rossum10b164a2001-09-25 13:59:01 +0000948
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000949 if( janzone < julyzone ) {
950 /* DST is reversed in the southern hemisphere */
951 PyModule_AddIntConstant(m, "timezone", julyzone);
952 PyModule_AddIntConstant(m, "altzone", janzone);
953 PyModule_AddIntConstant(m, "daylight",
954 janzone != julyzone);
955 PyModule_AddObject(m, "tzname",
956 Py_BuildValue("(zz)",
957 julyname, janname));
958 } else {
959 PyModule_AddIntConstant(m, "timezone", janzone);
960 PyModule_AddIntConstant(m, "altzone", julyzone);
961 PyModule_AddIntConstant(m, "daylight",
962 janzone != julyzone);
963 PyModule_AddObject(m, "tzname",
964 Py_BuildValue("(zz)",
965 janname, julyname));
966 }
967 }
Guido van Rossume6a4b7b1997-10-08 15:27:56 +0000968#else
Martin v. Löwis60a5d722002-10-16 20:28:25 +0000969#endif /* HAVE_STRUCT_TM_TM_ZONE */
Tim Peters26ae7cd2001-03-20 03:26:49 +0000970#ifdef __CYGWIN__
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000971 tzset();
972 PyModule_AddIntConstant(m, "timezone", _timezone);
973 PyModule_AddIntConstant(m, "altzone", _timezone-3600);
974 PyModule_AddIntConstant(m, "daylight", _daylight);
975 PyModule_AddObject(m, "tzname",
976 Py_BuildValue("(zz)", _tzname[0], _tzname[1]));
Tim Peters26ae7cd2001-03-20 03:26:49 +0000977#endif /* __CYGWIN__ */
Guido van Rossum10b164a2001-09-25 13:59:01 +0000978#endif /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/
Victor Stinnere0be4232011-10-25 13:06:09 +0200979
980#if defined(HAVE_CLOCK_GETTIME) || defined(HAVE_CLOCK_GETRES)
981#ifdef CLOCK_REALTIME
982 PyModule_AddIntMacro(m, CLOCK_REALTIME);
983#endif
984#ifdef CLOCK_MONOTONIC
985 PyModule_AddIntMacro(m, CLOCK_MONOTONIC);
986#endif
987#ifdef CLOCK_MONOTONIC_RAW
988 PyModule_AddIntMacro(m, CLOCK_MONOTONIC_RAW);
989#endif
Victor Stinner1470f352012-04-03 00:31:17 +0200990#ifdef CLOCK_HIGHRES
991 PyModule_AddIntMacro(m, CLOCK_HIGHRES);
992#endif
Victor Stinnere0be4232011-10-25 13:06:09 +0200993#ifdef CLOCK_PROCESS_CPUTIME_ID
994 PyModule_AddIntMacro(m, CLOCK_PROCESS_CPUTIME_ID);
995#endif
996#ifdef CLOCK_THREAD_CPUTIME_ID
997 PyModule_AddIntMacro(m, CLOCK_THREAD_CPUTIME_ID);
998#endif
999#endif /* HAVE_CLOCK_GETTIME */
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001000}
1001
1002
1003static PyMethodDef time_methods[] = {
Victor Stinner4195b5c2012-02-08 23:03:19 +01001004 {"time", time_time, METH_NOARGS, time_doc},
1005#if (defined(MS_WINDOWS) && !defined(__BORLANDC__)) || defined(HAVE_CLOCK)
1006 {"clock", time_clock, METH_NOARGS, clock_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001007#endif
Victor Stinnere0be4232011-10-25 13:06:09 +02001008#ifdef HAVE_CLOCK_GETTIME
Victor Stinner4195b5c2012-02-08 23:03:19 +01001009 {"clock_gettime", time_clock_gettime, METH_VARARGS, clock_gettime_doc},
Victor Stinner30d79472012-04-03 00:45:07 +02001010 {"clock_settime", time_clock_settime, METH_VARARGS, clock_settime_doc},
Victor Stinner4195b5c2012-02-08 23:03:19 +01001011 {"clock_getres", time_clock_getres, METH_VARARGS, clock_getres_doc},
Victor Stinnere0be4232011-10-25 13:06:09 +02001012#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001013 {"sleep", time_sleep, METH_VARARGS, sleep_doc},
1014 {"gmtime", time_gmtime, METH_VARARGS, gmtime_doc},
1015 {"localtime", time_localtime, METH_VARARGS, localtime_doc},
1016 {"asctime", time_asctime, METH_VARARGS, asctime_doc},
1017 {"ctime", time_ctime, METH_VARARGS, ctime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001018#ifdef HAVE_MKTIME
Victor Stinner4195b5c2012-02-08 23:03:19 +01001019 {"mktime", time_mktime, METH_O, mktime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001020#endif
Victor Stinner071eca32012-03-15 01:17:09 +01001021 {"steady", (PyCFunction)time_steady, METH_VARARGS|METH_KEYWORDS,
1022 steady_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001023#ifdef HAVE_STRFTIME
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001024 {"strftime", time_strftime, METH_VARARGS, strftime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001025#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001026 {"strptime", time_strptime, METH_VARARGS, strptime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001027#ifdef HAVE_WORKING_TZSET
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 {"tzset", time_tzset, METH_NOARGS, tzset_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001029#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001030 {NULL, NULL} /* sentinel */
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001031};
1032
1033
1034PyDoc_STRVAR(module_doc,
1035"This module provides various functions to manipulate time values.\n\
1036\n\
1037There are two standard representations of time. One is the number\n\
1038of seconds since the Epoch, in UTC (a.k.a. GMT). It may be an integer\n\
1039or a floating point number (to represent fractions of seconds).\n\
1040The Epoch is system-defined; on Unix, it is generally January 1st, 1970.\n\
1041The actual value can be retrieved by calling gmtime(0).\n\
1042\n\
1043The other representation is a tuple of 9 integers giving local time.\n\
1044The tuple items are:\n\
Alexander Belopolsky03163ac2011-05-02 12:20:52 -04001045 year (including century, e.g. 1998)\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001046 month (1-12)\n\
1047 day (1-31)\n\
1048 hours (0-23)\n\
1049 minutes (0-59)\n\
1050 seconds (0-59)\n\
1051 weekday (0-6, Monday is 0)\n\
1052 Julian day (day in the year, 1-366)\n\
1053 DST (Daylight Savings Time) flag (-1, 0 or 1)\n\
1054If the DST flag is 0, the time is given in the regular time zone;\n\
1055if it is 1, the time is given in the DST time zone;\n\
1056if it is -1, mktime() should guess based on the date and time.\n\
1057\n\
1058Variables:\n\
1059\n\
1060timezone -- difference in seconds between UTC and local standard time\n\
1061altzone -- difference in seconds between UTC and local DST time\n\
1062daylight -- whether local time should reflect DST\n\
1063tzname -- tuple of (standard time zone name, DST time zone name)\n\
1064\n\
1065Functions:\n\
1066\n\
1067time() -- return current time in seconds since the Epoch as a float\n\
1068clock() -- return CPU time since process start as a float\n\
1069sleep() -- delay for a number of seconds given as a float\n\
1070gmtime() -- convert seconds since Epoch to UTC tuple\n\
1071localtime() -- convert seconds since Epoch to local time tuple\n\
1072asctime() -- convert time tuple to string\n\
1073ctime() -- convert time in seconds to string\n\
1074mktime() -- convert local time tuple to seconds since Epoch\n\
1075strftime() -- convert time tuple to string according to format specification\n\
1076strptime() -- parse string to time tuple according to format specification\n\
1077tzset() -- change the local timezone");
1078
1079
Martin v. Löwis1a214512008-06-11 05:26:20 +00001080
1081static struct PyModuleDef timemodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001082 PyModuleDef_HEAD_INIT,
1083 "time",
1084 module_doc,
1085 -1,
1086 time_methods,
1087 NULL,
1088 NULL,
1089 NULL,
1090 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00001091};
1092
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001093PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00001094PyInit_time(void)
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001095{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001096 PyObject *m;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001097 m = PyModule_Create(&timemodule);
1098 if (m == NULL)
1099 return NULL;
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001100
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001101 /* Set, or reset, module variables like time.timezone */
1102 PyInit_timezone(m);
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001103
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001104 if (!initialized) {
1105 PyStructSequence_InitType(&StructTimeType,
1106 &struct_time_type_desc);
1107 }
1108 Py_INCREF(&StructTimeType);
1109 PyModule_AddObject(m, "struct_time", (PyObject*) &StructTimeType);
1110 initialized = 1;
1111 return m;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001112}
1113
Victor Stinner071eca32012-03-15 01:17:09 +01001114static PyObject*
Victor Stinner4195b5c2012-02-08 23:03:19 +01001115floattime(void)
1116{
1117 _PyTime_timeval t;
Victor Stinnerad95c2d2012-03-28 02:54:15 +02001118#ifdef HAVE_CLOCK_GETTIME
1119 struct timespec tp;
1120 int ret;
1121
1122 /* _PyTime_gettimeofday() does not use clock_gettime()
1123 because it would require to link Python to the rt (real-time)
1124 library, at least on Linux */
1125 ret = clock_gettime(CLOCK_REALTIME, &tp);
1126 if (ret == 0)
1127 return PyFloat_FromDouble(tp.tv_sec + tp.tv_nsec * 1e-9);
1128#endif
Victor Stinner4195b5c2012-02-08 23:03:19 +01001129 _PyTime_gettimeofday(&t);
Victor Stinner70b2e1e2012-03-26 22:08:02 +02001130 return PyFloat_FromDouble((double)t.tv_sec + t.tv_usec * 1e-6);
Victor Stinner4195b5c2012-02-08 23:03:19 +01001131}
1132
1133
Guido van Rossumb6775db1994-08-01 11:34:53 +00001134/* Implement floatsleep() for various platforms.
1135 When interrupted (or when another error occurs), return -1 and
1136 set an exception; else return 0. */
1137
1138static int
Guido van Rossuma320fd31995-03-09 12:14:15 +00001139floatsleep(double secs)
Guido van Rossum426035c1991-02-19 12:27:35 +00001140{
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001141/* XXX Should test for MS_WINDOWS first! */
Skip Montanaroeb33e5a2007-08-17 12:57:41 +00001142#if defined(HAVE_SELECT) && !defined(__EMX__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001143 struct timeval t;
1144 double frac;
Victor Stinner48b1ce52011-07-01 13:50:09 +02001145 int err;
1146
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001147 frac = fmod(secs, 1.0);
1148 secs = floor(secs);
1149 t.tv_sec = (long)secs;
1150 t.tv_usec = (long)(frac*1000000.0);
1151 Py_BEGIN_ALLOW_THREADS
Victor Stinner48b1ce52011-07-01 13:50:09 +02001152 err = select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &t);
1153 Py_END_ALLOW_THREADS
1154 if (err != 0) {
Guido van Rossum09cbb011999-11-08 15:32:27 +00001155#ifdef EINTR
Victor Stinner48b1ce52011-07-01 13:50:09 +02001156 if (errno == EINTR) {
1157 if (PyErr_CheckSignals())
1158 return -1;
1159 }
1160 else
Guido van Rossum09cbb011999-11-08 15:32:27 +00001161#endif
Victor Stinner48b1ce52011-07-01 13:50:09 +02001162 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001163 PyErr_SetFromErrno(PyExc_IOError);
1164 return -1;
1165 }
1166 }
Martin v. Löwis02af9642002-01-16 11:04:06 +00001167#elif defined(__WATCOMC__) && !defined(__QNX__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001168 /* XXX Can't interrupt this sleep */
1169 Py_BEGIN_ALLOW_THREADS
1170 delay((int)(secs * 1000 + 0.5)); /* delay() uses milliseconds */
1171 Py_END_ALLOW_THREADS
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001172#elif defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001173 {
1174 double millisecs = secs * 1000.0;
1175 unsigned long ul_millis;
Tim Peters513a1cd2003-01-19 04:54:58 +00001176
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001177 if (millisecs > (double)ULONG_MAX) {
1178 PyErr_SetString(PyExc_OverflowError,
1179 "sleep length is too large");
1180 return -1;
1181 }
1182 Py_BEGIN_ALLOW_THREADS
1183 /* Allow sleep(0) to maintain win32 semantics, and as decreed
1184 * by Guido, only the main thread can be interrupted.
1185 */
1186 ul_millis = (unsigned long)millisecs;
Antoine Pitrou6dd381e2011-11-21 21:26:56 +01001187 if (ul_millis == 0 || !_PyOS_IsMainThread())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001188 Sleep(ul_millis);
1189 else {
1190 DWORD rc;
Antoine Pitrou6dd381e2011-11-21 21:26:56 +01001191 HANDLE hInterruptEvent = _PyOS_SigintEvent();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001192 ResetEvent(hInterruptEvent);
1193 rc = WaitForSingleObject(hInterruptEvent, ul_millis);
1194 if (rc == WAIT_OBJECT_0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001195 Py_BLOCK_THREADS
1196 errno = EINTR;
1197 PyErr_SetFromErrno(PyExc_IOError);
1198 return -1;
1199 }
1200 }
1201 Py_END_ALLOW_THREADS
1202 }
Martin v. Löwis02af9642002-01-16 11:04:06 +00001203#elif defined(PYOS_OS2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001204 /* This Sleep *IS* Interruptable by Exceptions */
1205 Py_BEGIN_ALLOW_THREADS
1206 if (DosSleep(secs * 1000) != NO_ERROR) {
1207 Py_BLOCK_THREADS
1208 PyErr_SetFromErrno(PyExc_IOError);
1209 return -1;
1210 }
1211 Py_END_ALLOW_THREADS
Martin v. Löwis02af9642002-01-16 11:04:06 +00001212#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001213 /* XXX Can't interrupt this sleep */
1214 Py_BEGIN_ALLOW_THREADS
1215 sleep((int)secs);
1216 Py_END_ALLOW_THREADS
Martin v. Löwis02af9642002-01-16 11:04:06 +00001217#endif
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001218
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001219 return 0;
Guido van Rossum80c9d881991-04-16 08:47:51 +00001220}