blob: 6ebd3efc97820744311ddfd7f896fd42474263b5 [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"
Alexander Belopolsky6fc4ade2010-08-05 17:34:27 +00004#include "_time.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +00005
Guido van Rossum87ce7bb1998-06-09 16:30:31 +00006#include <ctype.h>
7
Thomas Wouters0e3f5912006-08-11 14:57:12 +00008#ifdef HAVE_SYS_TYPES_H
Guido van Rossumb6775db1994-08-01 11:34:53 +00009#include <sys/types.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +000010#endif /* HAVE_SYS_TYPES_H */
Guido van Rossum6d946f91992-08-14 13:49:30 +000011
Guido van Rossumb6775db1994-08-01 11:34:53 +000012#ifdef QUICKWIN
13#include <io.h>
14#endif
15
Guido van Rossum7bf22de1997-12-02 20:34:19 +000016#if defined(__WATCOMC__) && !defined(__QNX__)
Guido van Rossumbceeac81996-05-23 22:53:47 +000017#include <i86.h>
18#else
Guido van Rossumcac6c721996-09-06 13:34:02 +000019#ifdef MS_WINDOWS
Mark Hammond975e3922002-07-16 01:29:19 +000020#define WIN32_LEAN_AND_MEAN
Guido van Rossum258ccd42001-03-02 06:53:29 +000021#include <windows.h>
Mark Hammond975e3922002-07-16 01:29:19 +000022#include "pythread.h"
23
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000024#if defined(__BORLANDC__)
Guido van Rossumb2fb3641996-09-07 00:47:35 +000025/* These overrides not needed for Win32 */
Guido van Rossumb6775db1994-08-01 11:34:53 +000026#define timezone _timezone
Guido van Rossumcc081121995-03-14 15:05:41 +000027#define tzname _tzname
28#define daylight _daylight
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000029#endif /* __BORLANDC__ */
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
Andrew MacIntyre7bf68332002-03-03 02:59:16 +000033#if defined(PYOS_OS2)
34#define INCL_DOS
35#define INCL_ERRORS
36#include <os2.h>
37#endif
38
Guido van Rossum8e9ebfd1997-11-22 21:53:48 +000039#if defined(PYCC_VACPP)
Guido van Rossum26452411998-09-28 22:07:11 +000040#include <sys/time.h>
Guido van Rossum8e9ebfd1997-11-22 21:53:48 +000041#endif
42
Victor Stinnera8ec5ea2012-03-13 00:25:42 +010043#if defined(__APPLE__)
44#include <mach/mach_time.h>
45#endif
46
Guido van Rossum234f9421993-06-17 12:35:49 +000047/* Forward declarations */
Tim Petersdbd9ba62000-07-09 03:09:57 +000048static int floatsleep(double);
Victor Stinner4195b5c2012-02-08 23:03:19 +010049static double floattime(void);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000050
Barry Warsaw9a2a8a81996-12-06 23:32:14 +000051static PyObject *
Victor Stinner4195b5c2012-02-08 23:03:19 +010052time_time(PyObject *self, PyObject *unused)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000053{
Victor Stinner4195b5c2012-02-08 23:03:19 +010054 double secs;
55 secs = floattime();
56 if (secs == 0.0) {
57 PyErr_SetFromErrno(PyExc_IOError);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000058 return NULL;
Victor Stinner4195b5c2012-02-08 23:03:19 +010059 }
60 return PyFloat_FromDouble(secs);
Guido van Rossumb6775db1994-08-01 11:34:53 +000061}
62
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000063PyDoc_STRVAR(time_doc,
Victor Stinner4195b5c2012-02-08 23:03:19 +010064"time() -> floating point number\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +000065\n\
66Return the current time in seconds since the Epoch.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000067Fractions of a second may be present if the system clock provides them.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +000068
Victor Stinner85fdfa82012-01-27 00:38:48 +010069#if defined(HAVE_CLOCK)
70
71#ifndef CLOCKS_PER_SEC
72#ifdef CLK_TCK
73#define CLOCKS_PER_SEC CLK_TCK
74#else
75#define CLOCKS_PER_SEC 1000000
76#endif
77#endif
78
Victor Stinner4195b5c2012-02-08 23:03:19 +010079static PyObject *
80pyclock(void)
Victor Stinner85fdfa82012-01-27 00:38:48 +010081{
Victor Stinner4195b5c2012-02-08 23:03:19 +010082 clock_t value;
83 value = clock();
84 if (value == (clock_t)-1) {
Victor Stinner85fdfa82012-01-27 00:38:48 +010085 PyErr_SetString(PyExc_RuntimeError,
86 "the processor time used is not available "
87 "or its value cannot be represented");
Victor Stinner4195b5c2012-02-08 23:03:19 +010088 return NULL;
Victor Stinner85fdfa82012-01-27 00:38:48 +010089 }
Victor Stinner4195b5c2012-02-08 23:03:19 +010090 return PyFloat_FromDouble((double)value / CLOCKS_PER_SEC);
Victor Stinner85fdfa82012-01-27 00:38:48 +010091}
92#endif /* HAVE_CLOCK */
93
Thomas Wouters477c8d52006-05-27 19:21:47 +000094#if defined(MS_WINDOWS) && !defined(__BORLANDC__)
Victor Stinner9122fdd2011-07-04 13:55:40 +020095/* Win32 has better clock replacement; we have our own version, due to Mark
96 Hammond and Tim Peters */
Victor Stinner4195b5c2012-02-08 23:03:19 +010097static PyObject *
98win32_clock(int fallback)
Guido van Rossum3917c221997-04-02 05:35:28 +000099{
Victor Stinner8b302012012-02-07 23:29:46 +0100100 static LONGLONG cpu_frequency = 0;
Victor Stinner4195b5c2012-02-08 23:03:19 +0100101 static LONGLONG ctrStart;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000102 LARGE_INTEGER now;
Victor Stinner4195b5c2012-02-08 23:03:19 +0100103 double diff;
Guido van Rossum3917c221997-04-02 05:35:28 +0000104
Victor Stinner8b302012012-02-07 23:29:46 +0100105 if (cpu_frequency == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000106 LARGE_INTEGER freq;
Victor Stinner8b302012012-02-07 23:29:46 +0100107 QueryPerformanceCounter(&now);
Victor Stinner4195b5c2012-02-08 23:03:19 +0100108 ctrStart = now.QuadPart;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000109 if (!QueryPerformanceFrequency(&freq) || freq.QuadPart == 0) {
110 /* Unlikely to happen - this works on all intel
111 machines at least! Revert to clock() */
Victor Stinner4195b5c2012-02-08 23:03:19 +0100112 if (fallback)
113 return pyclock();
114 else
115 return PyErr_SetFromWindowsErr(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000116 }
Victor Stinner8b302012012-02-07 23:29:46 +0100117 cpu_frequency = freq.QuadPart;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000118 }
119 QueryPerformanceCounter(&now);
Victor Stinner4195b5c2012-02-08 23:03:19 +0100120 diff = (double)(now.QuadPart - ctrStart);
121 return PyFloat_FromDouble(diff / (double)cpu_frequency);
Guido van Rossum3917c221997-04-02 05:35:28 +0000122}
Victor Stinner8b302012012-02-07 23:29:46 +0100123#endif
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000124
Victor Stinner8b302012012-02-07 23:29:46 +0100125#if (defined(MS_WINDOWS) && !defined(__BORLANDC__)) || defined(HAVE_CLOCK)
Victor Stinner9122fdd2011-07-04 13:55:40 +0200126static PyObject *
Victor Stinner4195b5c2012-02-08 23:03:19 +0100127time_clock(PyObject *self, PyObject *unused)
Victor Stinner9122fdd2011-07-04 13:55:40 +0200128{
Victor Stinner8b302012012-02-07 23:29:46 +0100129#if defined(MS_WINDOWS) && !defined(__BORLANDC__)
Victor Stinner4195b5c2012-02-08 23:03:19 +0100130 return win32_clock(1);
Victor Stinner8b302012012-02-07 23:29:46 +0100131#else
Victor Stinner4195b5c2012-02-08 23:03:19 +0100132 return pyclock();
Victor Stinner8b302012012-02-07 23:29:46 +0100133#endif
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;
149 clockid_t clk_id;
150 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 Stinnere0be4232011-10-25 13:06:09 +0200157 PyErr_SetFromErrno(PyExc_IOError);
Antoine Pitrou2c085602012-01-18 01:41:44 +0100158 return NULL;
159 }
Victor Stinner4195b5c2012-02-08 23:03:19 +0100160
161 return PyFloat_FromDouble(tp.tv_sec + tp.tv_nsec * 1e-9);
Victor Stinnere0be4232011-10-25 13:06:09 +0200162}
163
164PyDoc_STRVAR(clock_gettime_doc,
Victor Stinner4195b5c2012-02-08 23:03:19 +0100165"clock_gettime(clk_id) -> floating point number\n\
Victor Stinnere0be4232011-10-25 13:06:09 +0200166\n\
167Return the time of the specified clock clk_id.");
168#endif
169
170#ifdef HAVE_CLOCK_GETRES
171static PyObject *
Victor Stinner4195b5c2012-02-08 23:03:19 +0100172time_clock_getres(PyObject *self, PyObject *args)
Victor Stinnere0be4232011-10-25 13:06:09 +0200173{
174 int ret;
175 clockid_t clk_id;
176 struct timespec tp;
177
Victor Stinner4195b5c2012-02-08 23:03:19 +0100178 if (!PyArg_ParseTuple(args, "i:clock_getres", &clk_id))
Victor Stinnere0be4232011-10-25 13:06:09 +0200179 return NULL;
180
181 ret = clock_getres((clockid_t)clk_id, &tp);
Antoine Pitrou2c085602012-01-18 01:41:44 +0100182 if (ret != 0) {
Victor Stinnere0be4232011-10-25 13:06:09 +0200183 PyErr_SetFromErrno(PyExc_IOError);
Antoine Pitrou2c085602012-01-18 01:41:44 +0100184 return NULL;
185 }
Victor Stinner4195b5c2012-02-08 23:03:19 +0100186
187 return PyFloat_FromDouble(tp.tv_sec + tp.tv_nsec * 1e-9);
Victor Stinnere0be4232011-10-25 13:06:09 +0200188}
189
190PyDoc_STRVAR(clock_getres_doc,
Victor Stinner4195b5c2012-02-08 23:03:19 +0100191"clock_getres(clk_id) -> floating point number\n\
Victor Stinnere0be4232011-10-25 13:06:09 +0200192\n\
193Return the resolution (precision) of the specified clock clk_id.");
194#endif
195
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000196static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000197time_sleep(PyObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000198{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000199 double secs;
200 if (!PyArg_ParseTuple(args, "d:sleep", &secs))
201 return NULL;
Victor Stinner7f53a502011-07-05 22:00:25 +0200202 if (secs < 0) {
203 PyErr_SetString(PyExc_ValueError,
204 "sleep length must be non-negative");
205 return NULL;
206 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000207 if (floatsleep(secs) != 0)
208 return NULL;
209 Py_INCREF(Py_None);
210 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000211}
212
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000213PyDoc_STRVAR(sleep_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000214"sleep(seconds)\n\
215\n\
216Delay execution for a given number of seconds. The argument may be\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000217a floating point number for subsecond precision.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000218
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000219static PyStructSequence_Field struct_time_type_fields[] = {
Alexander Belopolsky69f3fd02010-06-05 15:04:51 +0000220 {"tm_year", "year, for example, 1993"},
221 {"tm_mon", "month of year, range [1, 12]"},
222 {"tm_mday", "day of month, range [1, 31]"},
223 {"tm_hour", "hours, range [0, 23]"},
224 {"tm_min", "minutes, range [0, 59]"},
225 {"tm_sec", "seconds, range [0, 61])"},
226 {"tm_wday", "day of week, range [0, 6], Monday is 0"},
227 {"tm_yday", "day of year, range [1, 366]"},
228 {"tm_isdst", "1 if summer time is in effect, 0 if not, and -1 if unknown"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000229 {0}
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000230};
231
232static PyStructSequence_Desc struct_time_type_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000233 "time.struct_time",
Alexander Belopolsky69f3fd02010-06-05 15:04:51 +0000234 "The time value as returned by gmtime(), localtime(), and strptime(), and\n"
235 " accepted by asctime(), mktime() and strftime(). May be considered as a\n"
236 " sequence of 9 integers.\n\n"
237 " Note that several fields' values are not the same as those defined by\n"
238 " the C language standard for struct tm. For example, the value of the\n"
239 " field tm_year is the actual year, not year - 1900. See individual\n"
240 " fields' descriptions for details.",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000241 struct_time_type_fields,
242 9,
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000243};
Tim Peters9ad4b682002-02-13 05:14:18 +0000244
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000245static int initialized;
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000246static PyTypeObject StructTimeType;
247
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000248static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000249tmtotuple(struct tm *p)
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000250{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000251 PyObject *v = PyStructSequence_New(&StructTimeType);
252 if (v == NULL)
253 return NULL;
Tim Peters9ad4b682002-02-13 05:14:18 +0000254
Christian Heimes217cfd12007-12-02 14:31:20 +0000255#define SET(i,val) PyStructSequence_SET_ITEM(v, i, PyLong_FromLong((long) val))
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000256
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000257 SET(0, p->tm_year + 1900);
258 SET(1, p->tm_mon + 1); /* Want January == 1 */
259 SET(2, p->tm_mday);
260 SET(3, p->tm_hour);
261 SET(4, p->tm_min);
262 SET(5, p->tm_sec);
263 SET(6, (p->tm_wday + 6) % 7); /* Want Monday == 0 */
264 SET(7, p->tm_yday + 1); /* Want January, 1 == 1 */
265 SET(8, p->tm_isdst);
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000266#undef SET
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000267 if (PyErr_Occurred()) {
268 Py_XDECREF(v);
269 return NULL;
270 }
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000271
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000272 return v;
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000273}
274
Fred Drakef901abd2004-08-03 17:58:55 +0000275/* Parse arg tuple that can contain an optional float-or-None value;
276 format needs to be "|O:name".
277 Returns non-zero on success (parallels PyArg_ParseTuple).
278*/
279static int
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100280parse_time_t_args(PyObject *args, char *format, time_t *pwhen)
Fred Drakef901abd2004-08-03 17:58:55 +0000281{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000282 PyObject *ot = NULL;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100283 time_t whent;
Fred Drakef901abd2004-08-03 17:58:55 +0000284
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000285 if (!PyArg_ParseTuple(args, format, &ot))
286 return 0;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100287 if (ot == NULL || ot == Py_None) {
288 whent = time(NULL);
289 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000290 else {
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100291 double d = PyFloat_AsDouble(ot);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000292 if (PyErr_Occurred())
293 return 0;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100294 whent = _PyTime_DoubleToTimet(d);
295 if (whent == (time_t)-1 && PyErr_Occurred())
296 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000297 }
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100298 *pwhen = whent;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000299 return 1;
Fred Drakef901abd2004-08-03 17:58:55 +0000300}
301
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000302static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000303time_gmtime(PyObject *self, PyObject *args)
Guido van Rossum234f9421993-06-17 12:35:49 +0000304{
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100305 time_t when;
306 struct tm buf, *local;
307
308 if (!parse_time_t_args(args, "|O:gmtime", &when))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000309 return NULL;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100310
311 errno = 0;
312 local = gmtime(&when);
313 if (local == NULL) {
314#ifdef EINVAL
315 if (errno == 0)
316 errno = EINVAL;
317#endif
318 return PyErr_SetFromErrno(PyExc_OSError);
319 }
320 buf = *local;
321 return tmtotuple(&buf);
Guido van Rossum234f9421993-06-17 12:35:49 +0000322}
323
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000324PyDoc_STRVAR(gmtime_doc,
Christian Heimes9a371592007-12-28 14:08:13 +0000325"gmtime([seconds]) -> (tm_year, tm_mon, tm_mday, tm_hour, tm_min,\n\
Fred Drake193a3f62002-03-12 21:38:49 +0000326 tm_sec, tm_wday, tm_yday, tm_isdst)\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000327\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000328Convert seconds since the Epoch to a time tuple expressing UTC (a.k.a.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000329GMT). When 'seconds' is not passed in, convert the current time instead.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000330
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100331static int
332pylocaltime(time_t *timep, struct tm *result)
333{
334 struct tm *local;
335
336 assert (timep != NULL);
337 local = localtime(timep);
338 if (local == NULL) {
339 /* unconvertible time */
340#ifdef EINVAL
341 if (errno == 0)
342 errno = EINVAL;
343#endif
344 PyErr_SetFromErrno(PyExc_OSError);
345 return -1;
346 }
347 *result = *local;
348 return 0;
349}
350
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000351static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000352time_localtime(PyObject *self, PyObject *args)
Guido van Rossum234f9421993-06-17 12:35:49 +0000353{
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100354 time_t when;
355 struct tm buf;
356
357 if (!parse_time_t_args(args, "|O:localtime", &when))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000358 return NULL;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100359 if (pylocaltime(&when, &buf) == 1)
360 return NULL;
361 return tmtotuple(&buf);
Guido van Rossum234f9421993-06-17 12:35:49 +0000362}
363
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000364PyDoc_STRVAR(localtime_doc,
Christian Heimes9a371592007-12-28 14:08:13 +0000365"localtime([seconds]) -> (tm_year,tm_mon,tm_mday,tm_hour,tm_min,\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000366 tm_sec,tm_wday,tm_yday,tm_isdst)\n\
Martin v. Löwisb3cfc1d2001-12-02 12:27:43 +0000367\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000368Convert seconds since the Epoch to a time tuple expressing local time.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000369When 'seconds' is not passed in, convert the current time instead.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000370
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000371/* Convert 9-item tuple to tm structure. Return 1 on success, set
372 * an exception and return 0 on error.
373 */
Guido van Rossum9e90a671993-06-24 11:10:19 +0000374static int
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000375gettmarg(PyObject *args, struct tm *p)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000376{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000377 int y;
Guido van Rossumcfbaecc1998-08-25 14:51:12 +0000378
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000379 memset((void *) p, '\0', sizeof(struct tm));
Guido van Rossumb9081262007-08-25 03:14:09 +0000380
Alexander Belopolsky610e5442011-01-06 21:57:06 +0000381 if (!PyTuple_Check(args)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000382 PyErr_SetString(PyExc_TypeError,
383 "Tuple or struct_time argument required");
384 return 0;
385 }
Skip Montanaro41cfce92007-08-24 21:11:00 +0000386
Alexander Belopolsky610e5442011-01-06 21:57:06 +0000387 if (!PyArg_ParseTuple(args, "iiiiiiiii",
388 &y, &p->tm_mon, &p->tm_mday,
389 &p->tm_hour, &p->tm_min, &p->tm_sec,
390 &p->tm_wday, &p->tm_yday, &p->tm_isdst))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000391 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000392 p->tm_year = y - 1900;
393 p->tm_mon--;
394 p->tm_wday = (p->tm_wday + 1) % 7;
395 p->tm_yday--;
396 return 1;
Guido van Rossum9e90a671993-06-24 11:10:19 +0000397}
398
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000399/* Check values of the struct tm fields before it is passed to strftime() and
400 * asctime(). Return 1 if all values are valid, otherwise set an exception
401 * and returns 0.
402 */
Victor Stinneref128102010-10-07 01:00:52 +0000403static int
404checktm(struct tm* buf)
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000405{
Victor Stinneref128102010-10-07 01:00:52 +0000406 /* Checks added to make sure strftime() and asctime() does not crash Python by
407 indexing blindly into some array for a textual representation
408 by some bad index (fixes bug #897625 and #6608).
409
410 Also support values of zero from Python code for arguments in which
411 that is out of range by forcing that value to the lowest value that
412 is valid (fixed bug #1520914).
413
414 Valid ranges based on what is allowed in struct tm:
415
416 - tm_year: [0, max(int)] (1)
417 - tm_mon: [0, 11] (2)
418 - tm_mday: [1, 31]
419 - tm_hour: [0, 23]
420 - tm_min: [0, 59]
421 - tm_sec: [0, 60]
422 - tm_wday: [0, 6] (1)
423 - tm_yday: [0, 365] (2)
424 - tm_isdst: [-max(int), max(int)]
425
426 (1) gettmarg() handles bounds-checking.
427 (2) Python's acceptable range is one greater than the range in C,
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000428 thus need to check against automatic decrement by gettmarg().
429 */
430 if (buf->tm_mon == -1)
431 buf->tm_mon = 0;
432 else if (buf->tm_mon < 0 || buf->tm_mon > 11) {
433 PyErr_SetString(PyExc_ValueError, "month out of range");
434 return 0;
435 }
436 if (buf->tm_mday == 0)
437 buf->tm_mday = 1;
438 else if (buf->tm_mday < 0 || buf->tm_mday > 31) {
439 PyErr_SetString(PyExc_ValueError, "day of month out of range");
440 return 0;
441 }
442 if (buf->tm_hour < 0 || buf->tm_hour > 23) {
443 PyErr_SetString(PyExc_ValueError, "hour out of range");
444 return 0;
445 }
446 if (buf->tm_min < 0 || buf->tm_min > 59) {
447 PyErr_SetString(PyExc_ValueError, "minute out of range");
448 return 0;
449 }
450 if (buf->tm_sec < 0 || buf->tm_sec > 61) {
451 PyErr_SetString(PyExc_ValueError, "seconds out of range");
452 return 0;
453 }
454 /* tm_wday does not need checking of its upper-bound since taking
455 ``% 7`` in gettmarg() automatically restricts the range. */
456 if (buf->tm_wday < 0) {
457 PyErr_SetString(PyExc_ValueError, "day of week out of range");
458 return 0;
459 }
460 if (buf->tm_yday == -1)
461 buf->tm_yday = 0;
462 else if (buf->tm_yday < 0 || buf->tm_yday > 365) {
463 PyErr_SetString(PyExc_ValueError, "day of year out of range");
464 return 0;
465 }
466 return 1;
467}
468
Victor Stinnerc1f32ca2011-10-14 02:36:13 +0200469#ifdef MS_WINDOWS
470 /* wcsftime() doesn't format correctly time zones, see issue #10653 */
471# undef HAVE_WCSFTIME
472#endif
473
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000474#ifdef HAVE_STRFTIME
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000475#ifdef HAVE_WCSFTIME
476#define time_char wchar_t
477#define format_time wcsftime
478#define time_strlen wcslen
479#else
480#define time_char char
481#define format_time strftime
482#define time_strlen strlen
483#endif
484
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000485static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000486time_strftime(PyObject *self, PyObject *args)
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000487{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000488 PyObject *tup = NULL;
489 struct tm buf;
490 const time_char *fmt;
Victor Stinnerb2904782010-09-29 10:34:19 +0000491#ifdef HAVE_WCSFTIME
492 wchar_t *format;
493#else
494 PyObject *format;
495#endif
Victor Stinneref128102010-10-07 01:00:52 +0000496 PyObject *format_arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000497 size_t fmtlen, buflen;
Victor Stinnerb2904782010-09-29 10:34:19 +0000498 time_char *outbuf = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000499 size_t i;
Victor Stinnerb2904782010-09-29 10:34:19 +0000500 PyObject *ret = NULL;
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000501
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000502 memset((void *) &buf, '\0', sizeof(buf));
Guido van Rossum1f41f841998-04-27 19:04:26 +0000503
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000504 /* Will always expect a unicode string to be passed as format.
505 Given that there's no str type anymore in py3k this seems safe.
506 */
Victor Stinneref128102010-10-07 01:00:52 +0000507 if (!PyArg_ParseTuple(args, "U|O:strftime", &format_arg, &tup))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000508 return NULL;
Thomas Woutersfe385252001-01-19 23:16:56 +0000509
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000510 if (tup == NULL) {
511 time_t tt = time(NULL);
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100512 if (pylocaltime(&tt, &buf) == -1)
513 return NULL;
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000514 }
515 else if (!gettmarg(tup, &buf) || !checktm(&buf))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000516 return NULL;
Guido van Rossum10b164a2001-09-25 13:59:01 +0000517
Victor Stinner06ec45e2011-01-08 03:35:36 +0000518#if defined(_MSC_VER) || defined(sun)
Victor Stinner73ea29c2011-01-08 01:56:31 +0000519 if (buf.tm_year + 1900 < 1 || 9999 < buf.tm_year + 1900) {
Victor Stinner6f0e4f92011-03-21 02:14:53 +0100520 PyErr_SetString(PyExc_ValueError,
521 "strftime() requires year in [1; 9999]");
Alexander Belopolsky0dd06f42011-01-08 01:23:02 +0000522 return NULL;
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000523 }
Victor Stinner73ea29c2011-01-08 01:56:31 +0000524#endif
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000525
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000526 /* Normalize tm_isdst just in case someone foolishly implements %Z
527 based on the assumption that tm_isdst falls within the range of
528 [-1, 1] */
529 if (buf.tm_isdst < -1)
530 buf.tm_isdst = -1;
531 else if (buf.tm_isdst > 1)
532 buf.tm_isdst = 1;
Brett Cannond1080a32004-03-02 04:38:10 +0000533
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000534#ifdef HAVE_WCSFTIME
Victor Stinnerbeb4135b2010-10-07 01:02:42 +0000535 format = PyUnicode_AsWideCharString(format_arg, NULL);
Victor Stinnerb2904782010-09-29 10:34:19 +0000536 if (format == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000537 return NULL;
Victor Stinnerb2904782010-09-29 10:34:19 +0000538 fmt = format;
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000539#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000540 /* Convert the unicode string to an ascii one */
Victor Stinner1b579672011-12-17 05:47:23 +0100541 format = PyUnicode_EncodeLocale(format_arg, "surrogateescape");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000542 if (format == NULL)
543 return NULL;
544 fmt = PyBytes_AS_STRING(format);
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000545#endif
Amaury Forgeot d'Arcb5be6d42009-03-02 23:52:57 +0000546
Stefan Krah4aea7d32012-02-27 16:30:26 +0100547#if defined(MS_WINDOWS) && !defined(HAVE_WCSFTIME)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000548 /* check that the format string contains only valid directives */
Victor Stinner5a3ff792011-10-16 19:08:23 +0200549 for(outbuf = strchr(fmt, '%');
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000550 outbuf != NULL;
Victor Stinner5a3ff792011-10-16 19:08:23 +0200551 outbuf = strchr(outbuf+2, '%'))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000552 {
553 if (outbuf[1]=='#')
554 ++outbuf; /* not documented by python, */
555 if (outbuf[1]=='\0' ||
Victor Stinner5a3ff792011-10-16 19:08:23 +0200556 !strchr("aAbBcdHIjmMpSUwWxXyYzZ%", outbuf[1]))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000557 {
558 PyErr_SetString(PyExc_ValueError, "Invalid format string");
Stefan Krah4aea7d32012-02-27 16:30:26 +0100559 Py_DECREF(format);
560 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000561 }
562 }
Amaury Forgeot d'Arcb5be6d42009-03-02 23:52:57 +0000563#endif
564
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000565 fmtlen = time_strlen(fmt);
Guido van Rossumc222ec21999-02-23 00:00:10 +0000566
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000567 /* I hate these functions that presume you know how big the output
568 * will be ahead of time...
569 */
570 for (i = 1024; ; i += i) {
Victor Stinner136ea492011-12-17 22:37:18 +0100571#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100572 int err;
Victor Stinner136ea492011-12-17 22:37:18 +0100573#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000574 outbuf = (time_char *)PyMem_Malloc(i*sizeof(time_char));
575 if (outbuf == NULL) {
Victor Stinnerb2904782010-09-29 10:34:19 +0000576 PyErr_NoMemory();
577 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000578 }
579 buflen = format_time(outbuf, i, fmt, &buf);
Victor Stinner136ea492011-12-17 22:37:18 +0100580#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100581 err = errno;
Victor Stinner136ea492011-12-17 22:37:18 +0100582#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000583 if (buflen > 0 || i >= 256 * fmtlen) {
584 /* If the buffer is 256 times as long as the format,
585 it's probably not failing for lack of room!
586 More likely, the format yields an empty result,
587 e.g. an empty format, or %Z when the timezone
588 is unknown. */
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000589#ifdef HAVE_WCSFTIME
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000590 ret = PyUnicode_FromWideChar(outbuf, buflen);
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000591#else
Victor Stinner1b579672011-12-17 05:47:23 +0100592 ret = PyUnicode_DecodeLocaleAndSize(outbuf, buflen,
593 "surrogateescape");
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000594#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000595 PyMem_Free(outbuf);
Victor Stinnerb2904782010-09-29 10:34:19 +0000596 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000597 }
598 PyMem_Free(outbuf);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000599#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000600 /* VisualStudio .NET 2005 does this properly */
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100601 if (buflen == 0 && err == EINVAL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000602 PyErr_SetString(PyExc_ValueError, "Invalid format string");
Victor Stinnerb2904782010-09-29 10:34:19 +0000603 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000604 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000605#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000606 }
Victor Stinnerb2904782010-09-29 10:34:19 +0000607#ifdef HAVE_WCSFTIME
608 PyMem_Free(format);
609#else
610 Py_DECREF(format);
611#endif
612 return ret;
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000613}
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000614
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000615#undef time_char
616#undef format_time
617
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000618PyDoc_STRVAR(strftime_doc,
Thomas Woutersfe385252001-01-19 23:16:56 +0000619"strftime(format[, tuple]) -> string\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000620\n\
621Convert a time tuple to a string according to a format specification.\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000622See the library reference manual for formatting codes. When the time tuple\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000623is not present, current time as returned by localtime() is used.");
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000624#endif /* HAVE_STRFTIME */
625
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000626static PyObject *
627time_strptime(PyObject *self, PyObject *args)
628{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000629 PyObject *strptime_module = PyImport_ImportModuleNoBlock("_strptime");
630 PyObject *strptime_result;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200631 _Py_IDENTIFIER(_strptime_time);
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000632
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000633 if (!strptime_module)
634 return NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200635 strptime_result = _PyObject_CallMethodId(strptime_module,
636 &PyId__strptime_time, "O", args);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000637 Py_DECREF(strptime_module);
638 return strptime_result;
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000639}
640
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000641
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000642PyDoc_STRVAR(strptime_doc,
Brett Cannon20def8b2003-07-01 05:16:08 +0000643"strptime(string, format) -> struct_time\n\
Martin v. Löwisb3cfc1d2001-12-02 12:27:43 +0000644\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000645Parse a string to a time tuple according to a format specification.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000646See the library reference manual for formatting codes (same as strftime()).");
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000647
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000648static PyObject *
649_asctime(struct tm *timeptr)
650{
651 /* Inspired by Open Group reference implementation available at
652 * http://pubs.opengroup.org/onlinepubs/009695399/functions/asctime.html */
Victor Stinner499dfcf2011-03-21 13:26:24 +0100653 static char wday_name[7][4] = {
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000654 "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
655 };
Victor Stinner499dfcf2011-03-21 13:26:24 +0100656 static char mon_name[12][4] = {
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000657 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
658 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
659 };
Victor Stinner499dfcf2011-03-21 13:26:24 +0100660 return PyUnicode_FromFormat(
661 "%s %s%3d %.2d:%.2d:%.2d %d",
662 wday_name[timeptr->tm_wday],
663 mon_name[timeptr->tm_mon],
664 timeptr->tm_mday, timeptr->tm_hour,
665 timeptr->tm_min, timeptr->tm_sec,
666 1900 + timeptr->tm_year);
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000667}
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000668
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000669static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000670time_asctime(PyObject *self, PyObject *args)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000671{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000672 PyObject *tup = NULL;
673 struct tm buf;
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000674
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000675 if (!PyArg_UnpackTuple(args, "asctime", 0, 1, &tup))
676 return NULL;
677 if (tup == NULL) {
678 time_t tt = time(NULL);
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100679 if (pylocaltime(&tt, &buf) == -1)
680 return NULL;
681
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000682 } else if (!gettmarg(tup, &buf) || !checktm(&buf))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000683 return NULL;
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000684 return _asctime(&buf);
Guido van Rossum9e90a671993-06-24 11:10:19 +0000685}
686
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000687PyDoc_STRVAR(asctime_doc,
Thomas Woutersfe385252001-01-19 23:16:56 +0000688"asctime([tuple]) -> string\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000689\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000690Convert a time tuple to a string, e.g. 'Sat Jun 06 16:26:11 1998'.\n\
691When the time tuple is not present, current time as returned by localtime()\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000692is used.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000693
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000694static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000695time_ctime(PyObject *self, PyObject *args)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000696{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000697 time_t tt;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100698 struct tm buf;
699 if (!parse_time_t_args(args, "|O:ctime", &tt))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000700 return NULL;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100701 if (pylocaltime(&tt, &buf) == -1)
Alexander Belopolsky5da468f2011-01-04 17:15:52 +0000702 return NULL;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100703 return _asctime(&buf);
Guido van Rossum9e90a671993-06-24 11:10:19 +0000704}
705
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000706PyDoc_STRVAR(ctime_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000707"ctime(seconds) -> string\n\
708\n\
709Convert a time in seconds since the Epoch to a string in local time.\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000710This is equivalent to asctime(localtime(seconds)). When the time tuple is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000711not present, current time as returned by localtime() is used.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000712
Guido van Rossum60cd8131998-03-06 17:16:21 +0000713#ifdef HAVE_MKTIME
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000714static PyObject *
Victor Stinner4195b5c2012-02-08 23:03:19 +0100715time_mktime(PyObject *self, PyObject *tup)
Guido van Rossum234f9421993-06-17 12:35:49 +0000716{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000717 struct tm buf;
718 time_t tt;
719 if (!gettmarg(tup, &buf))
720 return NULL;
Alexander Belopolskyb7d40d12011-01-11 01:21:25 +0000721 buf.tm_wday = -1; /* sentinel; original value ignored */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000722 tt = mktime(&buf);
Alexander Belopolskyb7d40d12011-01-11 01:21:25 +0000723 /* Return value of -1 does not necessarily mean an error, but tm_wday
Ezio Melotti13925002011-03-16 11:05:33 +0200724 * cannot remain set to -1 if mktime succeeded. */
Alexander Belopolskyb7d40d12011-01-11 01:21:25 +0000725 if (tt == (time_t)(-1) && buf.tm_wday == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000726 PyErr_SetString(PyExc_OverflowError,
727 "mktime argument out of range");
728 return NULL;
729 }
Victor Stinner4195b5c2012-02-08 23:03:19 +0100730 return PyFloat_FromDouble((double)tt);
Guido van Rossum234f9421993-06-17 12:35:49 +0000731}
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000732
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000733PyDoc_STRVAR(mktime_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000734"mktime(tuple) -> floating point number\n\
735\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000736Convert a time tuple in local time to seconds since the Epoch.");
Guido van Rossum60cd8131998-03-06 17:16:21 +0000737#endif /* HAVE_MKTIME */
Guido van Rossum234f9421993-06-17 12:35:49 +0000738
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000739#ifdef HAVE_WORKING_TZSET
Martin v. Löwis1a214512008-06-11 05:26:20 +0000740static void PyInit_timezone(PyObject *module);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000741
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000742static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000743time_tzset(PyObject *self, PyObject *unused)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000744{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000745 PyObject* m;
Fred Drake9bb74322002-04-01 14:49:59 +0000746
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000747 m = PyImport_ImportModuleNoBlock("time");
748 if (m == NULL) {
749 return NULL;
750 }
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000751
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000752 tzset();
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000753
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000754 /* Reset timezone, altzone, daylight and tzname */
755 PyInit_timezone(m);
756 Py_DECREF(m);
Tim Peters1b6f7a92004-06-20 02:50:16 +0000757
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000758 Py_INCREF(Py_None);
759 return Py_None;
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000760}
761
762PyDoc_STRVAR(tzset_doc,
R. David Murray4d55bf92010-12-14 00:55:46 +0000763"tzset()\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000764\n\
765Initialize, or reinitialize, the local timezone to the value stored in\n\
766os.environ['TZ']. The TZ environment variable should be specified in\n\
Neal Norwitzdc8e1942004-07-20 22:34:37 +0000767standard Unix timezone format as documented in the tzset man page\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000768(eg. 'US/Eastern', 'Europe/Amsterdam'). Unknown timezones will silently\n\
769fall back to UTC. If the TZ environment variable is not set, the local\n\
770timezone is set to the systems best guess of wallclock time.\n\
771Changing the TZ environment variable without calling tzset *may* change\n\
772the local timezone used by methods such as localtime, but this behaviour\n\
773should not be relied on.");
774#endif /* HAVE_WORKING_TZSET */
775
Victor Stinner4195b5c2012-02-08 23:03:19 +0100776static PyObject *
777time_wallclock(PyObject *self, PyObject *unused)
Victor Stinnerb94b2662012-01-18 01:50:21 +0100778{
779#if defined(MS_WINDOWS) && !defined(__BORLANDC__)
Victor Stinner4195b5c2012-02-08 23:03:19 +0100780 return win32_clock(1);
781#elif defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_MONOTONIC)
Victor Stinnerb94b2662012-01-18 01:50:21 +0100782 static int clk_index = 0;
783 clockid_t clk_ids[] = {
784#ifdef CLOCK_MONOTONIC_RAW
785 CLOCK_MONOTONIC_RAW,
786#endif
787 CLOCK_MONOTONIC
788#ifdef CLOCK_REALTIME
789 /* On Linux, CLOCK_REALTIME uses the same clock than gettimeofday(),
790 but clock_gettime() has a nanosecond resolution. */
791 , CLOCK_REALTIME
792#endif
793 };
794 int ret;
795 struct timespec tp;
796
797 while (0 <= clk_index) {
798 clockid_t clk_id = clk_ids[clk_index];
799 ret = clock_gettime(clk_id, &tp);
800 if (ret == 0)
Victor Stinner4195b5c2012-02-08 23:03:19 +0100801 return PyFloat_FromDouble(tp.tv_sec + tp.tv_nsec * 1e-9);
Victor Stinnerb94b2662012-01-18 01:50:21 +0100802
803 clk_index++;
804 if (Py_ARRAY_LENGTH(clk_ids) <= clk_index)
805 clk_index = -1;
806 }
Victor Stinner4195b5c2012-02-08 23:03:19 +0100807 return time_time(self, NULL);
808#else
809 return time_time(self, NULL);
Victor Stinnerb94b2662012-01-18 01:50:21 +0100810#endif
811}
812
813PyDoc_STRVAR(wallclock_doc,
Victor Stinner4195b5c2012-02-08 23:03:19 +0100814"wallclock() -> float\n\
Victor Stinnerb94b2662012-01-18 01:50:21 +0100815\n\
816Return the current time in fractions of a second to the system's best\n\
817ability. Use this when the most accurate representation of wall-clock is\n\
Victor Stinner855889b2012-01-18 01:57:19 +0100818required, i.e. when \"processor time\" is inappropriate. The reference point\n\
Victor Stinnerb94b2662012-01-18 01:50:21 +0100819of the returned value is undefined so only the difference of consecutive\n\
820calls is valid.");
821
Victor Stinner8b302012012-02-07 23:29:46 +0100822#if (defined(MS_WINDOWS) && !defined(__BORLANDC__)) \
Victor Stinnera8ec5ea2012-03-13 00:25:42 +0100823 || (defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_MONOTONIC)) \
824 || (defined(__APPLE__))
Victor Stinner8b302012012-02-07 23:29:46 +0100825# define HAVE_PYTIME_MONOTONIC
826#endif
827
828#ifdef HAVE_PYTIME_MONOTONIC
829static PyObject *
Victor Stinner4195b5c2012-02-08 23:03:19 +0100830time_monotonic(PyObject *self, PyObject *unused)
Victor Stinner8b302012012-02-07 23:29:46 +0100831{
Victor Stinner4195b5c2012-02-08 23:03:19 +0100832#if defined(MS_WINDOWS) && !defined(__BORLANDC__)
833 return win32_clock(0);
Victor Stinnera8ec5ea2012-03-13 00:25:42 +0100834#elif defined(__APPLE__)
835 uint64_t time = mach_absolute_time();
836 double secs;
837
838 static mach_timebase_info_data_t timebase;
839 if (timebase.denom == 0)
840 mach_timebase_info(&timebase);
841
842 secs = (double)time * timebase.numer / timebase.denom * 1e-9;
843
844 return PyFloat_FromDouble(secs);
Victor Stinner4195b5c2012-02-08 23:03:19 +0100845#else
Victor Stinner8b302012012-02-07 23:29:46 +0100846 static int clk_index = 0;
847 clockid_t clk_ids[] = {
848#ifdef CLOCK_MONOTONIC_RAW
849 CLOCK_MONOTONIC_RAW,
850#endif
851 CLOCK_MONOTONIC
852 };
853 int ret;
854 struct timespec tp;
855
856 while (0 <= clk_index) {
857 clockid_t clk_id = clk_ids[clk_index];
858 ret = clock_gettime(clk_id, &tp);
859 if (ret == 0)
Victor Stinner4195b5c2012-02-08 23:03:19 +0100860 return PyFloat_FromDouble(tp.tv_sec + tp.tv_nsec * 1e-9);
Victor Stinner8b302012012-02-07 23:29:46 +0100861
862 clk_index++;
863 if (Py_ARRAY_LENGTH(clk_ids) <= clk_index)
864 clk_index = -1;
865 }
866 PyErr_SetFromErrno(PyExc_OSError);
867 return NULL;
868#endif
869}
870
871PyDoc_STRVAR(monotonic_doc,
872"monotonic() -> float\n\
873\n\
874Monotonic clock. The reference point of the returned value is undefined so\n\
875only the difference of consecutive calls is valid.");
876#endif
877
Martin v. Löwisd218dc12008-04-07 03:17:54 +0000878static void
Martin v. Löwis1a214512008-06-11 05:26:20 +0000879PyInit_timezone(PyObject *m) {
880 /* This code moved from PyInit_time wholesale to allow calling it from
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000881 time_tzset. In the future, some parts of it can be moved back
882 (for platforms that don't HAVE_WORKING_TZSET, when we know what they
883 are), and the extraneous calls to tzset(3) should be removed.
884 I haven't done this yet, as I don't want to change this code as
885 little as possible when introducing the time.tzset and time.tzsetwall
886 methods. This should simply be a method of doing the following once,
887 at the top of this function and removing the call to tzset() from
888 time_tzset():
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000889
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000890 #ifdef HAVE_TZSET
891 tzset()
892 #endif
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000893
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000894 And I'm lazy and hate C so nyer.
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000895 */
Guido van Rossum10b164a2001-09-25 13:59:01 +0000896#if defined(HAVE_TZNAME) && !defined(__GLIBC__) && !defined(__CYGWIN__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000897 PyObject *otz0, *otz1;
898 tzset();
Guido van Rossum26452411998-09-28 22:07:11 +0000899#ifdef PYOS_OS2
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000900 PyModule_AddIntConstant(m, "timezone", _timezone);
Guido van Rossum26452411998-09-28 22:07:11 +0000901#else /* !PYOS_OS2 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000902 PyModule_AddIntConstant(m, "timezone", timezone);
Guido van Rossum26452411998-09-28 22:07:11 +0000903#endif /* PYOS_OS2 */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000904#ifdef HAVE_ALTZONE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000905 PyModule_AddIntConstant(m, "altzone", altzone);
Guido van Rossumb6775db1994-08-01 11:34:53 +0000906#else
Guido van Rossum26452411998-09-28 22:07:11 +0000907#ifdef PYOS_OS2
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000908 PyModule_AddIntConstant(m, "altzone", _timezone-3600);
Guido van Rossum26452411998-09-28 22:07:11 +0000909#else /* !PYOS_OS2 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000910 PyModule_AddIntConstant(m, "altzone", timezone-3600);
Guido van Rossum26452411998-09-28 22:07:11 +0000911#endif /* PYOS_OS2 */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000912#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000913 PyModule_AddIntConstant(m, "daylight", daylight);
Victor Stinner1b579672011-12-17 05:47:23 +0100914 otz0 = PyUnicode_DecodeLocale(tzname[0], "surrogateescape");
915 otz1 = PyUnicode_DecodeLocale(tzname[1], "surrogateescape");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000916 PyModule_AddObject(m, "tzname", Py_BuildValue("(NN)", otz0, otz1));
Guido van Rossum10b164a2001-09-25 13:59:01 +0000917#else /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/
Martin v. Löwis60a5d722002-10-16 20:28:25 +0000918#ifdef HAVE_STRUCT_TM_TM_ZONE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000919 {
Guido van Rossum234f9421993-06-17 12:35:49 +0000920#define YEAR ((time_t)((365 * 24 + 6) * 3600))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000921 time_t t;
922 struct tm *p;
923 long janzone, julyzone;
924 char janname[10], julyname[10];
925 t = (time((time_t *)0) / YEAR) * YEAR;
926 p = localtime(&t);
927 janzone = -p->tm_gmtoff;
928 strncpy(janname, p->tm_zone ? p->tm_zone : " ", 9);
929 janname[9] = '\0';
930 t += YEAR/2;
931 p = localtime(&t);
932 julyzone = -p->tm_gmtoff;
933 strncpy(julyname, p->tm_zone ? p->tm_zone : " ", 9);
934 julyname[9] = '\0';
Guido van Rossum10b164a2001-09-25 13:59:01 +0000935
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000936 if( janzone < julyzone ) {
937 /* DST is reversed in the southern hemisphere */
938 PyModule_AddIntConstant(m, "timezone", julyzone);
939 PyModule_AddIntConstant(m, "altzone", janzone);
940 PyModule_AddIntConstant(m, "daylight",
941 janzone != julyzone);
942 PyModule_AddObject(m, "tzname",
943 Py_BuildValue("(zz)",
944 julyname, janname));
945 } else {
946 PyModule_AddIntConstant(m, "timezone", janzone);
947 PyModule_AddIntConstant(m, "altzone", julyzone);
948 PyModule_AddIntConstant(m, "daylight",
949 janzone != julyzone);
950 PyModule_AddObject(m, "tzname",
951 Py_BuildValue("(zz)",
952 janname, julyname));
953 }
954 }
Guido van Rossume6a4b7b1997-10-08 15:27:56 +0000955#else
Martin v. Löwis60a5d722002-10-16 20:28:25 +0000956#endif /* HAVE_STRUCT_TM_TM_ZONE */
Tim Peters26ae7cd2001-03-20 03:26:49 +0000957#ifdef __CYGWIN__
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000958 tzset();
959 PyModule_AddIntConstant(m, "timezone", _timezone);
960 PyModule_AddIntConstant(m, "altzone", _timezone-3600);
961 PyModule_AddIntConstant(m, "daylight", _daylight);
962 PyModule_AddObject(m, "tzname",
963 Py_BuildValue("(zz)", _tzname[0], _tzname[1]));
Tim Peters26ae7cd2001-03-20 03:26:49 +0000964#endif /* __CYGWIN__ */
Guido van Rossum10b164a2001-09-25 13:59:01 +0000965#endif /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/
Victor Stinnere0be4232011-10-25 13:06:09 +0200966
967#if defined(HAVE_CLOCK_GETTIME) || defined(HAVE_CLOCK_GETRES)
968#ifdef CLOCK_REALTIME
969 PyModule_AddIntMacro(m, CLOCK_REALTIME);
970#endif
971#ifdef CLOCK_MONOTONIC
972 PyModule_AddIntMacro(m, CLOCK_MONOTONIC);
973#endif
974#ifdef CLOCK_MONOTONIC_RAW
975 PyModule_AddIntMacro(m, CLOCK_MONOTONIC_RAW);
976#endif
977#ifdef CLOCK_PROCESS_CPUTIME_ID
978 PyModule_AddIntMacro(m, CLOCK_PROCESS_CPUTIME_ID);
979#endif
980#ifdef CLOCK_THREAD_CPUTIME_ID
981 PyModule_AddIntMacro(m, CLOCK_THREAD_CPUTIME_ID);
982#endif
983#endif /* HAVE_CLOCK_GETTIME */
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000984}
985
986
987static PyMethodDef time_methods[] = {
Victor Stinner4195b5c2012-02-08 23:03:19 +0100988 {"time", time_time, METH_NOARGS, time_doc},
989#if (defined(MS_WINDOWS) && !defined(__BORLANDC__)) || defined(HAVE_CLOCK)
990 {"clock", time_clock, METH_NOARGS, clock_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000991#endif
Victor Stinnere0be4232011-10-25 13:06:09 +0200992#ifdef HAVE_CLOCK_GETTIME
Victor Stinner4195b5c2012-02-08 23:03:19 +0100993 {"clock_gettime", time_clock_gettime, METH_VARARGS, clock_gettime_doc},
Victor Stinnere0be4232011-10-25 13:06:09 +0200994#endif
995#ifdef HAVE_CLOCK_GETRES
Victor Stinner4195b5c2012-02-08 23:03:19 +0100996 {"clock_getres", time_clock_getres, METH_VARARGS, clock_getres_doc},
Victor Stinnere0be4232011-10-25 13:06:09 +0200997#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000998 {"sleep", time_sleep, METH_VARARGS, sleep_doc},
999 {"gmtime", time_gmtime, METH_VARARGS, gmtime_doc},
1000 {"localtime", time_localtime, METH_VARARGS, localtime_doc},
1001 {"asctime", time_asctime, METH_VARARGS, asctime_doc},
1002 {"ctime", time_ctime, METH_VARARGS, ctime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001003#ifdef HAVE_MKTIME
Victor Stinner4195b5c2012-02-08 23:03:19 +01001004 {"mktime", time_mktime, METH_O, mktime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001005#endif
Victor Stinner8b302012012-02-07 23:29:46 +01001006#ifdef HAVE_PYTIME_MONOTONIC
Victor Stinner4195b5c2012-02-08 23:03:19 +01001007 {"monotonic", time_monotonic, METH_NOARGS, monotonic_doc},
Victor Stinner8b302012012-02-07 23:29:46 +01001008#endif
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001009#ifdef HAVE_STRFTIME
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001010 {"strftime", time_strftime, METH_VARARGS, strftime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001011#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001012 {"strptime", time_strptime, METH_VARARGS, strptime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001013#ifdef HAVE_WORKING_TZSET
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001014 {"tzset", time_tzset, METH_NOARGS, tzset_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001015#endif
Victor Stinner4195b5c2012-02-08 23:03:19 +01001016 {"wallclock", time_wallclock, METH_NOARGS, wallclock_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001017 {NULL, NULL} /* sentinel */
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001018};
1019
1020
1021PyDoc_STRVAR(module_doc,
1022"This module provides various functions to manipulate time values.\n\
1023\n\
1024There are two standard representations of time. One is the number\n\
1025of seconds since the Epoch, in UTC (a.k.a. GMT). It may be an integer\n\
1026or a floating point number (to represent fractions of seconds).\n\
1027The Epoch is system-defined; on Unix, it is generally January 1st, 1970.\n\
1028The actual value can be retrieved by calling gmtime(0).\n\
1029\n\
1030The other representation is a tuple of 9 integers giving local time.\n\
1031The tuple items are:\n\
Alexander Belopolsky03163ac2011-05-02 12:20:52 -04001032 year (including century, e.g. 1998)\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001033 month (1-12)\n\
1034 day (1-31)\n\
1035 hours (0-23)\n\
1036 minutes (0-59)\n\
1037 seconds (0-59)\n\
1038 weekday (0-6, Monday is 0)\n\
1039 Julian day (day in the year, 1-366)\n\
1040 DST (Daylight Savings Time) flag (-1, 0 or 1)\n\
1041If the DST flag is 0, the time is given in the regular time zone;\n\
1042if it is 1, the time is given in the DST time zone;\n\
1043if it is -1, mktime() should guess based on the date and time.\n\
1044\n\
1045Variables:\n\
1046\n\
1047timezone -- difference in seconds between UTC and local standard time\n\
1048altzone -- difference in seconds between UTC and local DST time\n\
1049daylight -- whether local time should reflect DST\n\
1050tzname -- tuple of (standard time zone name, DST time zone name)\n\
1051\n\
1052Functions:\n\
1053\n\
1054time() -- return current time in seconds since the Epoch as a float\n\
1055clock() -- return CPU time since process start as a float\n\
1056sleep() -- delay for a number of seconds given as a float\n\
1057gmtime() -- convert seconds since Epoch to UTC tuple\n\
1058localtime() -- convert seconds since Epoch to local time tuple\n\
1059asctime() -- convert time tuple to string\n\
1060ctime() -- convert time in seconds to string\n\
1061mktime() -- convert local time tuple to seconds since Epoch\n\
1062strftime() -- convert time tuple to string according to format specification\n\
1063strptime() -- parse string to time tuple according to format specification\n\
1064tzset() -- change the local timezone");
1065
1066
Martin v. Löwis1a214512008-06-11 05:26:20 +00001067
1068static struct PyModuleDef timemodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001069 PyModuleDef_HEAD_INIT,
1070 "time",
1071 module_doc,
1072 -1,
1073 time_methods,
1074 NULL,
1075 NULL,
1076 NULL,
1077 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00001078};
1079
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001080PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00001081PyInit_time(void)
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001082{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001083 PyObject *m;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001084 m = PyModule_Create(&timemodule);
1085 if (m == NULL)
1086 return NULL;
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001087
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001088 /* Set, or reset, module variables like time.timezone */
1089 PyInit_timezone(m);
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001090
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001091 if (!initialized) {
1092 PyStructSequence_InitType(&StructTimeType,
1093 &struct_time_type_desc);
1094 }
1095 Py_INCREF(&StructTimeType);
1096 PyModule_AddObject(m, "struct_time", (PyObject*) &StructTimeType);
1097 initialized = 1;
1098 return m;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001099}
1100
Victor Stinner4195b5c2012-02-08 23:03:19 +01001101static double
1102floattime(void)
1103{
1104 _PyTime_timeval t;
1105 _PyTime_gettimeofday(&t);
1106 return (double)t.tv_sec + t.tv_usec*0.000001;
1107}
1108
1109
Guido van Rossumb6775db1994-08-01 11:34:53 +00001110/* Implement floatsleep() for various platforms.
1111 When interrupted (or when another error occurs), return -1 and
1112 set an exception; else return 0. */
1113
1114static int
Guido van Rossuma320fd31995-03-09 12:14:15 +00001115floatsleep(double secs)
Guido van Rossum426035c1991-02-19 12:27:35 +00001116{
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001117/* XXX Should test for MS_WINDOWS first! */
Skip Montanaroeb33e5a2007-08-17 12:57:41 +00001118#if defined(HAVE_SELECT) && !defined(__EMX__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001119 struct timeval t;
1120 double frac;
Victor Stinner48b1ce52011-07-01 13:50:09 +02001121 int err;
1122
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001123 frac = fmod(secs, 1.0);
1124 secs = floor(secs);
1125 t.tv_sec = (long)secs;
1126 t.tv_usec = (long)(frac*1000000.0);
1127 Py_BEGIN_ALLOW_THREADS
Victor Stinner48b1ce52011-07-01 13:50:09 +02001128 err = select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &t);
1129 Py_END_ALLOW_THREADS
1130 if (err != 0) {
Guido van Rossum09cbb011999-11-08 15:32:27 +00001131#ifdef EINTR
Victor Stinner48b1ce52011-07-01 13:50:09 +02001132 if (errno == EINTR) {
1133 if (PyErr_CheckSignals())
1134 return -1;
1135 }
1136 else
Guido van Rossum09cbb011999-11-08 15:32:27 +00001137#endif
Victor Stinner48b1ce52011-07-01 13:50:09 +02001138 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001139 PyErr_SetFromErrno(PyExc_IOError);
1140 return -1;
1141 }
1142 }
Martin v. Löwis02af9642002-01-16 11:04:06 +00001143#elif defined(__WATCOMC__) && !defined(__QNX__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001144 /* XXX Can't interrupt this sleep */
1145 Py_BEGIN_ALLOW_THREADS
1146 delay((int)(secs * 1000 + 0.5)); /* delay() uses milliseconds */
1147 Py_END_ALLOW_THREADS
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001148#elif defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001149 {
1150 double millisecs = secs * 1000.0;
1151 unsigned long ul_millis;
Tim Peters513a1cd2003-01-19 04:54:58 +00001152
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001153 if (millisecs > (double)ULONG_MAX) {
1154 PyErr_SetString(PyExc_OverflowError,
1155 "sleep length is too large");
1156 return -1;
1157 }
1158 Py_BEGIN_ALLOW_THREADS
1159 /* Allow sleep(0) to maintain win32 semantics, and as decreed
1160 * by Guido, only the main thread can be interrupted.
1161 */
1162 ul_millis = (unsigned long)millisecs;
Antoine Pitrou6dd381e2011-11-21 21:26:56 +01001163 if (ul_millis == 0 || !_PyOS_IsMainThread())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001164 Sleep(ul_millis);
1165 else {
1166 DWORD rc;
Antoine Pitrou6dd381e2011-11-21 21:26:56 +01001167 HANDLE hInterruptEvent = _PyOS_SigintEvent();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001168 ResetEvent(hInterruptEvent);
1169 rc = WaitForSingleObject(hInterruptEvent, ul_millis);
1170 if (rc == WAIT_OBJECT_0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001171 Py_BLOCK_THREADS
1172 errno = EINTR;
1173 PyErr_SetFromErrno(PyExc_IOError);
1174 return -1;
1175 }
1176 }
1177 Py_END_ALLOW_THREADS
1178 }
Martin v. Löwis02af9642002-01-16 11:04:06 +00001179#elif defined(PYOS_OS2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001180 /* This Sleep *IS* Interruptable by Exceptions */
1181 Py_BEGIN_ALLOW_THREADS
1182 if (DosSleep(secs * 1000) != NO_ERROR) {
1183 Py_BLOCK_THREADS
1184 PyErr_SetFromErrno(PyExc_IOError);
1185 return -1;
1186 }
1187 Py_END_ALLOW_THREADS
Martin v. Löwis02af9642002-01-16 11:04:06 +00001188#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001189 /* XXX Can't interrupt this sleep */
1190 Py_BEGIN_ALLOW_THREADS
1191 sleep((int)secs);
1192 Py_END_ALLOW_THREADS
Martin v. Löwis02af9642002-01-16 11:04:06 +00001193#endif
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001194
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001195 return 0;
Guido van Rossum80c9d881991-04-16 08:47:51 +00001196}