blob: 30a01f58c29946d876b16f76653b99ea18f90df8 [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
Guido van Rossum234f9421993-06-17 12:35:49 +000043/* Forward declarations */
Tim Petersdbd9ba62000-07-09 03:09:57 +000044static int floatsleep(double);
Thomas Woutersed77bac2000-07-24 15:26:39 +000045static double floattime(void);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000046
Barry Warsaw9a2a8a81996-12-06 23:32:14 +000047static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000048time_time(PyObject *self, PyObject *unused)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000049{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000050 double secs;
51 secs = floattime();
52 if (secs == 0.0) {
53 PyErr_SetFromErrno(PyExc_IOError);
54 return NULL;
55 }
56 return PyFloat_FromDouble(secs);
Guido van Rossumb6775db1994-08-01 11:34:53 +000057}
58
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000059PyDoc_STRVAR(time_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +000060"time() -> floating point number\n\
61\n\
62Return the current time in seconds since the Epoch.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000063Fractions of a second may be present if the system clock provides them.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +000064
Victor Stinner85fdfa82012-01-27 00:38:48 +010065#if defined(HAVE_CLOCK)
66
67#ifndef CLOCKS_PER_SEC
68#ifdef CLK_TCK
69#define CLOCKS_PER_SEC CLK_TCK
70#else
71#define CLOCKS_PER_SEC 1000000
72#endif
73#endif
74
75static PyObject *
76pyclock(void)
77{
78 clock_t value;
79 value = clock();
80 if (value == (clock_t)-1) {
81 PyErr_SetString(PyExc_RuntimeError,
82 "the processor time used is not available "
83 "or its value cannot be represented");
84 return NULL;
85 }
86 return PyFloat_FromDouble((double)value / CLOCKS_PER_SEC);
87}
88#endif /* HAVE_CLOCK */
89
Thomas Wouters477c8d52006-05-27 19:21:47 +000090#if defined(MS_WINDOWS) && !defined(__BORLANDC__)
Victor Stinner9122fdd2011-07-04 13:55:40 +020091/* Win32 has better clock replacement; we have our own version, due to Mark
92 Hammond and Tim Peters */
Guido van Rossum3917c221997-04-02 05:35:28 +000093static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000094time_clock(PyObject *self, PyObject *unused)
Guido van Rossum3917c221997-04-02 05:35:28 +000095{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000096 static LARGE_INTEGER ctrStart;
97 static double divisor = 0.0;
98 LARGE_INTEGER now;
99 double diff;
Guido van Rossum3917c221997-04-02 05:35:28 +0000100
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000101 if (divisor == 0.0) {
102 LARGE_INTEGER freq;
103 QueryPerformanceCounter(&ctrStart);
104 if (!QueryPerformanceFrequency(&freq) || freq.QuadPart == 0) {
105 /* Unlikely to happen - this works on all intel
106 machines at least! Revert to clock() */
Victor Stinner85fdfa82012-01-27 00:38:48 +0100107 return pyclock();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000108 }
109 divisor = (double)freq.QuadPart;
110 }
111 QueryPerformanceCounter(&now);
112 diff = (double)(now.QuadPart - ctrStart.QuadPart);
113 return PyFloat_FromDouble(diff / divisor);
Guido van Rossum3917c221997-04-02 05:35:28 +0000114}
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000115
Victor Stinner9122fdd2011-07-04 13:55:40 +0200116#elif defined(HAVE_CLOCK)
117
Victor Stinner9122fdd2011-07-04 13:55:40 +0200118static PyObject *
119time_clock(PyObject *self, PyObject *unused)
120{
Victor Stinner85fdfa82012-01-27 00:38:48 +0100121 return pyclock();
Victor Stinner9122fdd2011-07-04 13:55:40 +0200122}
123#endif /* HAVE_CLOCK */
124
Guido van Rossum3917c221997-04-02 05:35:28 +0000125
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000126#ifdef HAVE_CLOCK
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000127PyDoc_STRVAR(clock_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000128"clock() -> floating point number\n\
129\n\
130Return the CPU time or real time since the start of the process or since\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000131the first call to clock(). This has as much precision as the system\n\
132records.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000133#endif
134
Victor Stinnere0be4232011-10-25 13:06:09 +0200135#ifdef HAVE_CLOCK_GETTIME
136static PyObject *
137time_clock_gettime(PyObject *self, PyObject *args)
138{
139 int ret;
140 clockid_t clk_id;
141 struct timespec tp;
142
143 if (!PyArg_ParseTuple(args, "i:clock_gettime", &clk_id))
144 return NULL;
145
146 ret = clock_gettime((clockid_t)clk_id, &tp);
Antoine Pitrou2c085602012-01-18 01:41:44 +0100147 if (ret != 0) {
Victor Stinnere0be4232011-10-25 13:06:09 +0200148 PyErr_SetFromErrno(PyExc_IOError);
Antoine Pitrou2c085602012-01-18 01:41:44 +0100149 return NULL;
150 }
Victor Stinnere0be4232011-10-25 13:06:09 +0200151
152 return PyFloat_FromDouble(tp.tv_sec + tp.tv_nsec * 1e-9);
153}
154
155PyDoc_STRVAR(clock_gettime_doc,
156"clock_gettime(clk_id) -> floating point number\n\
157\n\
158Return the time of the specified clock clk_id.");
159#endif
160
161#ifdef HAVE_CLOCK_GETRES
162static PyObject *
163time_clock_getres(PyObject *self, PyObject *args)
164{
165 int ret;
166 clockid_t clk_id;
167 struct timespec tp;
168
169 if (!PyArg_ParseTuple(args, "i:clock_getres", &clk_id))
170 return NULL;
171
172 ret = clock_getres((clockid_t)clk_id, &tp);
Antoine Pitrou2c085602012-01-18 01:41:44 +0100173 if (ret != 0) {
Victor Stinnere0be4232011-10-25 13:06:09 +0200174 PyErr_SetFromErrno(PyExc_IOError);
Antoine Pitrou2c085602012-01-18 01:41:44 +0100175 return NULL;
176 }
Victor Stinnere0be4232011-10-25 13:06:09 +0200177
178 return PyFloat_FromDouble(tp.tv_sec + tp.tv_nsec * 1e-9);
179}
180
181PyDoc_STRVAR(clock_getres_doc,
182"clock_getres(clk_id) -> floating point number\n\
183\n\
184Return the resolution (precision) of the specified clock clk_id.");
185#endif
186
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000187static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000188time_sleep(PyObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000189{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000190 double secs;
191 if (!PyArg_ParseTuple(args, "d:sleep", &secs))
192 return NULL;
Victor Stinner7f53a502011-07-05 22:00:25 +0200193 if (secs < 0) {
194 PyErr_SetString(PyExc_ValueError,
195 "sleep length must be non-negative");
196 return NULL;
197 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000198 if (floatsleep(secs) != 0)
199 return NULL;
200 Py_INCREF(Py_None);
201 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000202}
203
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000204PyDoc_STRVAR(sleep_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000205"sleep(seconds)\n\
206\n\
207Delay execution for a given number of seconds. The argument may be\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000208a floating point number for subsecond precision.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000209
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000210static PyStructSequence_Field struct_time_type_fields[] = {
Alexander Belopolsky69f3fd02010-06-05 15:04:51 +0000211 {"tm_year", "year, for example, 1993"},
212 {"tm_mon", "month of year, range [1, 12]"},
213 {"tm_mday", "day of month, range [1, 31]"},
214 {"tm_hour", "hours, range [0, 23]"},
215 {"tm_min", "minutes, range [0, 59]"},
216 {"tm_sec", "seconds, range [0, 61])"},
217 {"tm_wday", "day of week, range [0, 6], Monday is 0"},
218 {"tm_yday", "day of year, range [1, 366]"},
219 {"tm_isdst", "1 if summer time is in effect, 0 if not, and -1 if unknown"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000220 {0}
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000221};
222
223static PyStructSequence_Desc struct_time_type_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000224 "time.struct_time",
Alexander Belopolsky69f3fd02010-06-05 15:04:51 +0000225 "The time value as returned by gmtime(), localtime(), and strptime(), and\n"
226 " accepted by asctime(), mktime() and strftime(). May be considered as a\n"
227 " sequence of 9 integers.\n\n"
228 " Note that several fields' values are not the same as those defined by\n"
229 " the C language standard for struct tm. For example, the value of the\n"
230 " field tm_year is the actual year, not year - 1900. See individual\n"
231 " fields' descriptions for details.",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000232 struct_time_type_fields,
233 9,
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000234};
Tim Peters9ad4b682002-02-13 05:14:18 +0000235
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000236static int initialized;
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000237static PyTypeObject StructTimeType;
238
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000239static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000240tmtotuple(struct tm *p)
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000241{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000242 PyObject *v = PyStructSequence_New(&StructTimeType);
243 if (v == NULL)
244 return NULL;
Tim Peters9ad4b682002-02-13 05:14:18 +0000245
Christian Heimes217cfd12007-12-02 14:31:20 +0000246#define SET(i,val) PyStructSequence_SET_ITEM(v, i, PyLong_FromLong((long) val))
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000247
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000248 SET(0, p->tm_year + 1900);
249 SET(1, p->tm_mon + 1); /* Want January == 1 */
250 SET(2, p->tm_mday);
251 SET(3, p->tm_hour);
252 SET(4, p->tm_min);
253 SET(5, p->tm_sec);
254 SET(6, (p->tm_wday + 6) % 7); /* Want Monday == 0 */
255 SET(7, p->tm_yday + 1); /* Want January, 1 == 1 */
256 SET(8, p->tm_isdst);
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000257#undef SET
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000258 if (PyErr_Occurred()) {
259 Py_XDECREF(v);
260 return NULL;
261 }
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000262
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000263 return v;
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000264}
265
Fred Drakef901abd2004-08-03 17:58:55 +0000266/* Parse arg tuple that can contain an optional float-or-None value;
267 format needs to be "|O:name".
268 Returns non-zero on success (parallels PyArg_ParseTuple).
269*/
270static int
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100271parse_time_t_args(PyObject *args, char *format, time_t *pwhen)
Fred Drakef901abd2004-08-03 17:58:55 +0000272{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000273 PyObject *ot = NULL;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100274 time_t whent;
Fred Drakef901abd2004-08-03 17:58:55 +0000275
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000276 if (!PyArg_ParseTuple(args, format, &ot))
277 return 0;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100278 if (ot == NULL || ot == Py_None) {
279 whent = time(NULL);
280 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000281 else {
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100282 double d = PyFloat_AsDouble(ot);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000283 if (PyErr_Occurred())
284 return 0;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100285 whent = _PyTime_DoubleToTimet(d);
286 if (whent == (time_t)-1 && PyErr_Occurred())
287 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000288 }
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100289 *pwhen = whent;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000290 return 1;
Fred Drakef901abd2004-08-03 17:58:55 +0000291}
292
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000293static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000294time_gmtime(PyObject *self, PyObject *args)
Guido van Rossum234f9421993-06-17 12:35:49 +0000295{
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100296 time_t when;
297 struct tm buf, *local;
298
299 if (!parse_time_t_args(args, "|O:gmtime", &when))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000300 return NULL;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100301
302 errno = 0;
303 local = gmtime(&when);
304 if (local == NULL) {
305#ifdef EINVAL
306 if (errno == 0)
307 errno = EINVAL;
308#endif
309 return PyErr_SetFromErrno(PyExc_OSError);
310 }
311 buf = *local;
312 return tmtotuple(&buf);
Guido van Rossum234f9421993-06-17 12:35:49 +0000313}
314
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000315PyDoc_STRVAR(gmtime_doc,
Christian Heimes9a371592007-12-28 14:08:13 +0000316"gmtime([seconds]) -> (tm_year, tm_mon, tm_mday, tm_hour, tm_min,\n\
Fred Drake193a3f62002-03-12 21:38:49 +0000317 tm_sec, tm_wday, tm_yday, tm_isdst)\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000318\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000319Convert seconds since the Epoch to a time tuple expressing UTC (a.k.a.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000320GMT). When 'seconds' is not passed in, convert the current time instead.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000321
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100322static int
323pylocaltime(time_t *timep, struct tm *result)
324{
325 struct tm *local;
326
327 assert (timep != NULL);
328 local = localtime(timep);
329 if (local == NULL) {
330 /* unconvertible time */
331#ifdef EINVAL
332 if (errno == 0)
333 errno = EINVAL;
334#endif
335 PyErr_SetFromErrno(PyExc_OSError);
336 return -1;
337 }
338 *result = *local;
339 return 0;
340}
341
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000342static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000343time_localtime(PyObject *self, PyObject *args)
Guido van Rossum234f9421993-06-17 12:35:49 +0000344{
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100345 time_t when;
346 struct tm buf;
347
348 if (!parse_time_t_args(args, "|O:localtime", &when))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000349 return NULL;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100350 if (pylocaltime(&when, &buf) == 1)
351 return NULL;
352 return tmtotuple(&buf);
Guido van Rossum234f9421993-06-17 12:35:49 +0000353}
354
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000355PyDoc_STRVAR(localtime_doc,
Christian Heimes9a371592007-12-28 14:08:13 +0000356"localtime([seconds]) -> (tm_year,tm_mon,tm_mday,tm_hour,tm_min,\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000357 tm_sec,tm_wday,tm_yday,tm_isdst)\n\
Martin v. Löwisb3cfc1d2001-12-02 12:27:43 +0000358\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000359Convert seconds since the Epoch to a time tuple expressing local time.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000360When 'seconds' is not passed in, convert the current time instead.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000361
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000362/* Convert 9-item tuple to tm structure. Return 1 on success, set
363 * an exception and return 0 on error.
364 */
Guido van Rossum9e90a671993-06-24 11:10:19 +0000365static int
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000366gettmarg(PyObject *args, struct tm *p)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000367{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000368 int y;
Guido van Rossumcfbaecc1998-08-25 14:51:12 +0000369
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000370 memset((void *) p, '\0', sizeof(struct tm));
Guido van Rossumb9081262007-08-25 03:14:09 +0000371
Alexander Belopolsky610e5442011-01-06 21:57:06 +0000372 if (!PyTuple_Check(args)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000373 PyErr_SetString(PyExc_TypeError,
374 "Tuple or struct_time argument required");
375 return 0;
376 }
Skip Montanaro41cfce92007-08-24 21:11:00 +0000377
Alexander Belopolsky610e5442011-01-06 21:57:06 +0000378 if (!PyArg_ParseTuple(args, "iiiiiiiii",
379 &y, &p->tm_mon, &p->tm_mday,
380 &p->tm_hour, &p->tm_min, &p->tm_sec,
381 &p->tm_wday, &p->tm_yday, &p->tm_isdst))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000382 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000383 p->tm_year = y - 1900;
384 p->tm_mon--;
385 p->tm_wday = (p->tm_wday + 1) % 7;
386 p->tm_yday--;
387 return 1;
Guido van Rossum9e90a671993-06-24 11:10:19 +0000388}
389
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000390/* Check values of the struct tm fields before it is passed to strftime() and
391 * asctime(). Return 1 if all values are valid, otherwise set an exception
392 * and returns 0.
393 */
Victor Stinneref128102010-10-07 01:00:52 +0000394static int
395checktm(struct tm* buf)
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000396{
Victor Stinneref128102010-10-07 01:00:52 +0000397 /* Checks added to make sure strftime() and asctime() does not crash Python by
398 indexing blindly into some array for a textual representation
399 by some bad index (fixes bug #897625 and #6608).
400
401 Also support values of zero from Python code for arguments in which
402 that is out of range by forcing that value to the lowest value that
403 is valid (fixed bug #1520914).
404
405 Valid ranges based on what is allowed in struct tm:
406
407 - tm_year: [0, max(int)] (1)
408 - tm_mon: [0, 11] (2)
409 - tm_mday: [1, 31]
410 - tm_hour: [0, 23]
411 - tm_min: [0, 59]
412 - tm_sec: [0, 60]
413 - tm_wday: [0, 6] (1)
414 - tm_yday: [0, 365] (2)
415 - tm_isdst: [-max(int), max(int)]
416
417 (1) gettmarg() handles bounds-checking.
418 (2) Python's acceptable range is one greater than the range in C,
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000419 thus need to check against automatic decrement by gettmarg().
420 */
421 if (buf->tm_mon == -1)
422 buf->tm_mon = 0;
423 else if (buf->tm_mon < 0 || buf->tm_mon > 11) {
424 PyErr_SetString(PyExc_ValueError, "month out of range");
425 return 0;
426 }
427 if (buf->tm_mday == 0)
428 buf->tm_mday = 1;
429 else if (buf->tm_mday < 0 || buf->tm_mday > 31) {
430 PyErr_SetString(PyExc_ValueError, "day of month out of range");
431 return 0;
432 }
433 if (buf->tm_hour < 0 || buf->tm_hour > 23) {
434 PyErr_SetString(PyExc_ValueError, "hour out of range");
435 return 0;
436 }
437 if (buf->tm_min < 0 || buf->tm_min > 59) {
438 PyErr_SetString(PyExc_ValueError, "minute out of range");
439 return 0;
440 }
441 if (buf->tm_sec < 0 || buf->tm_sec > 61) {
442 PyErr_SetString(PyExc_ValueError, "seconds out of range");
443 return 0;
444 }
445 /* tm_wday does not need checking of its upper-bound since taking
446 ``% 7`` in gettmarg() automatically restricts the range. */
447 if (buf->tm_wday < 0) {
448 PyErr_SetString(PyExc_ValueError, "day of week out of range");
449 return 0;
450 }
451 if (buf->tm_yday == -1)
452 buf->tm_yday = 0;
453 else if (buf->tm_yday < 0 || buf->tm_yday > 365) {
454 PyErr_SetString(PyExc_ValueError, "day of year out of range");
455 return 0;
456 }
457 return 1;
458}
459
Victor Stinnerc1f32ca2011-10-14 02:36:13 +0200460#ifdef MS_WINDOWS
461 /* wcsftime() doesn't format correctly time zones, see issue #10653 */
462# undef HAVE_WCSFTIME
463#endif
464
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000465#ifdef HAVE_STRFTIME
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000466#ifdef HAVE_WCSFTIME
467#define time_char wchar_t
468#define format_time wcsftime
469#define time_strlen wcslen
470#else
471#define time_char char
472#define format_time strftime
473#define time_strlen strlen
474#endif
475
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000476static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000477time_strftime(PyObject *self, PyObject *args)
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000478{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000479 PyObject *tup = NULL;
480 struct tm buf;
481 const time_char *fmt;
Victor Stinnerb2904782010-09-29 10:34:19 +0000482#ifdef HAVE_WCSFTIME
483 wchar_t *format;
484#else
485 PyObject *format;
486#endif
Victor Stinneref128102010-10-07 01:00:52 +0000487 PyObject *format_arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000488 size_t fmtlen, buflen;
Victor Stinnerb2904782010-09-29 10:34:19 +0000489 time_char *outbuf = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000490 size_t i;
Victor Stinnerb2904782010-09-29 10:34:19 +0000491 PyObject *ret = NULL;
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000492
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000493 memset((void *) &buf, '\0', sizeof(buf));
Guido van Rossum1f41f841998-04-27 19:04:26 +0000494
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000495 /* Will always expect a unicode string to be passed as format.
496 Given that there's no str type anymore in py3k this seems safe.
497 */
Victor Stinneref128102010-10-07 01:00:52 +0000498 if (!PyArg_ParseTuple(args, "U|O:strftime", &format_arg, &tup))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000499 return NULL;
Thomas Woutersfe385252001-01-19 23:16:56 +0000500
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000501 if (tup == NULL) {
502 time_t tt = time(NULL);
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100503 if (pylocaltime(&tt, &buf) == -1)
504 return NULL;
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000505 }
506 else if (!gettmarg(tup, &buf) || !checktm(&buf))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000507 return NULL;
Guido van Rossum10b164a2001-09-25 13:59:01 +0000508
Victor Stinner06ec45e2011-01-08 03:35:36 +0000509#if defined(_MSC_VER) || defined(sun)
Victor Stinner73ea29c2011-01-08 01:56:31 +0000510 if (buf.tm_year + 1900 < 1 || 9999 < buf.tm_year + 1900) {
Victor Stinner6f0e4f92011-03-21 02:14:53 +0100511 PyErr_SetString(PyExc_ValueError,
512 "strftime() requires year in [1; 9999]");
Alexander Belopolsky0dd06f42011-01-08 01:23:02 +0000513 return NULL;
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000514 }
Victor Stinner73ea29c2011-01-08 01:56:31 +0000515#endif
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000516
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000517 /* Normalize tm_isdst just in case someone foolishly implements %Z
518 based on the assumption that tm_isdst falls within the range of
519 [-1, 1] */
520 if (buf.tm_isdst < -1)
521 buf.tm_isdst = -1;
522 else if (buf.tm_isdst > 1)
523 buf.tm_isdst = 1;
Brett Cannond1080a32004-03-02 04:38:10 +0000524
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000525#ifdef HAVE_WCSFTIME
Victor Stinnerbeb4135b2010-10-07 01:02:42 +0000526 format = PyUnicode_AsWideCharString(format_arg, NULL);
Victor Stinnerb2904782010-09-29 10:34:19 +0000527 if (format == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000528 return NULL;
Victor Stinnerb2904782010-09-29 10:34:19 +0000529 fmt = format;
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000530#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000531 /* Convert the unicode string to an ascii one */
Victor Stinner1b579672011-12-17 05:47:23 +0100532 format = PyUnicode_EncodeLocale(format_arg, "surrogateescape");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000533 if (format == NULL)
534 return NULL;
535 fmt = PyBytes_AS_STRING(format);
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000536#endif
Amaury Forgeot d'Arcb5be6d42009-03-02 23:52:57 +0000537
Victor Stinner5a3ff792011-10-16 19:08:23 +0200538#if defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000539 /* check that the format string contains only valid directives */
Victor Stinner5a3ff792011-10-16 19:08:23 +0200540 for(outbuf = strchr(fmt, '%');
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000541 outbuf != NULL;
Victor Stinner5a3ff792011-10-16 19:08:23 +0200542 outbuf = strchr(outbuf+2, '%'))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000543 {
544 if (outbuf[1]=='#')
545 ++outbuf; /* not documented by python, */
546 if (outbuf[1]=='\0' ||
Victor Stinner5a3ff792011-10-16 19:08:23 +0200547 !strchr("aAbBcdHIjmMpSUwWxXyYzZ%", outbuf[1]))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000548 {
549 PyErr_SetString(PyExc_ValueError, "Invalid format string");
550 return 0;
551 }
552 }
Amaury Forgeot d'Arcb5be6d42009-03-02 23:52:57 +0000553#endif
554
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000555 fmtlen = time_strlen(fmt);
Guido van Rossumc222ec21999-02-23 00:00:10 +0000556
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000557 /* I hate these functions that presume you know how big the output
558 * will be ahead of time...
559 */
560 for (i = 1024; ; i += i) {
Victor Stinner136ea492011-12-17 22:37:18 +0100561#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100562 int err;
Victor Stinner136ea492011-12-17 22:37:18 +0100563#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000564 outbuf = (time_char *)PyMem_Malloc(i*sizeof(time_char));
565 if (outbuf == NULL) {
Victor Stinnerb2904782010-09-29 10:34:19 +0000566 PyErr_NoMemory();
567 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000568 }
569 buflen = format_time(outbuf, i, fmt, &buf);
Victor Stinner136ea492011-12-17 22:37:18 +0100570#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100571 err = errno;
Victor Stinner136ea492011-12-17 22:37:18 +0100572#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000573 if (buflen > 0 || i >= 256 * fmtlen) {
574 /* If the buffer is 256 times as long as the format,
575 it's probably not failing for lack of room!
576 More likely, the format yields an empty result,
577 e.g. an empty format, or %Z when the timezone
578 is unknown. */
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000579#ifdef HAVE_WCSFTIME
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000580 ret = PyUnicode_FromWideChar(outbuf, buflen);
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000581#else
Victor Stinner1b579672011-12-17 05:47:23 +0100582 ret = PyUnicode_DecodeLocaleAndSize(outbuf, buflen,
583 "surrogateescape");
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000584#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000585 PyMem_Free(outbuf);
Victor Stinnerb2904782010-09-29 10:34:19 +0000586 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000587 }
588 PyMem_Free(outbuf);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000589#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000590 /* VisualStudio .NET 2005 does this properly */
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100591 if (buflen == 0 && err == EINVAL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000592 PyErr_SetString(PyExc_ValueError, "Invalid format string");
Victor Stinnerb2904782010-09-29 10:34:19 +0000593 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000594 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000595#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000596 }
Victor Stinnerb2904782010-09-29 10:34:19 +0000597#ifdef HAVE_WCSFTIME
598 PyMem_Free(format);
599#else
600 Py_DECREF(format);
601#endif
602 return ret;
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000603}
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000604
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000605#undef time_char
606#undef format_time
607
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000608PyDoc_STRVAR(strftime_doc,
Thomas Woutersfe385252001-01-19 23:16:56 +0000609"strftime(format[, tuple]) -> string\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000610\n\
611Convert a time tuple to a string according to a format specification.\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000612See the library reference manual for formatting codes. When the time tuple\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000613is not present, current time as returned by localtime() is used.");
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000614#endif /* HAVE_STRFTIME */
615
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000616static PyObject *
617time_strptime(PyObject *self, PyObject *args)
618{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000619 PyObject *strptime_module = PyImport_ImportModuleNoBlock("_strptime");
620 PyObject *strptime_result;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200621 _Py_IDENTIFIER(_strptime_time);
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000622
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000623 if (!strptime_module)
624 return NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200625 strptime_result = _PyObject_CallMethodId(strptime_module,
626 &PyId__strptime_time, "O", args);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000627 Py_DECREF(strptime_module);
628 return strptime_result;
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000629}
630
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000631
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000632PyDoc_STRVAR(strptime_doc,
Brett Cannon20def8b2003-07-01 05:16:08 +0000633"strptime(string, format) -> struct_time\n\
Martin v. Löwisb3cfc1d2001-12-02 12:27:43 +0000634\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000635Parse a string to a time tuple according to a format specification.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000636See the library reference manual for formatting codes (same as strftime()).");
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000637
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000638static PyObject *
639_asctime(struct tm *timeptr)
640{
641 /* Inspired by Open Group reference implementation available at
642 * http://pubs.opengroup.org/onlinepubs/009695399/functions/asctime.html */
Victor Stinner499dfcf2011-03-21 13:26:24 +0100643 static char wday_name[7][4] = {
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000644 "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
645 };
Victor Stinner499dfcf2011-03-21 13:26:24 +0100646 static char mon_name[12][4] = {
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000647 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
648 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
649 };
Victor Stinner499dfcf2011-03-21 13:26:24 +0100650 return PyUnicode_FromFormat(
651 "%s %s%3d %.2d:%.2d:%.2d %d",
652 wday_name[timeptr->tm_wday],
653 mon_name[timeptr->tm_mon],
654 timeptr->tm_mday, timeptr->tm_hour,
655 timeptr->tm_min, timeptr->tm_sec,
656 1900 + timeptr->tm_year);
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000657}
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000658
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000659static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000660time_asctime(PyObject *self, PyObject *args)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000661{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000662 PyObject *tup = NULL;
663 struct tm buf;
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000664
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000665 if (!PyArg_UnpackTuple(args, "asctime", 0, 1, &tup))
666 return NULL;
667 if (tup == NULL) {
668 time_t tt = time(NULL);
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100669 if (pylocaltime(&tt, &buf) == -1)
670 return NULL;
671
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000672 } else if (!gettmarg(tup, &buf) || !checktm(&buf))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000673 return NULL;
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000674 return _asctime(&buf);
Guido van Rossum9e90a671993-06-24 11:10:19 +0000675}
676
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000677PyDoc_STRVAR(asctime_doc,
Thomas Woutersfe385252001-01-19 23:16:56 +0000678"asctime([tuple]) -> string\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000679\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000680Convert a time tuple to a string, e.g. 'Sat Jun 06 16:26:11 1998'.\n\
681When the time tuple is not present, current time as returned by localtime()\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000682is used.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000683
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000684static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000685time_ctime(PyObject *self, PyObject *args)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000686{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000687 time_t tt;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100688 struct tm buf;
689 if (!parse_time_t_args(args, "|O:ctime", &tt))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000690 return NULL;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100691 if (pylocaltime(&tt, &buf) == -1)
Alexander Belopolsky5da468f2011-01-04 17:15:52 +0000692 return NULL;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100693 return _asctime(&buf);
Guido van Rossum9e90a671993-06-24 11:10:19 +0000694}
695
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000696PyDoc_STRVAR(ctime_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000697"ctime(seconds) -> string\n\
698\n\
699Convert a time in seconds since the Epoch to a string in local time.\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000700This is equivalent to asctime(localtime(seconds)). When the time tuple is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000701not present, current time as returned by localtime() is used.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000702
Guido van Rossum60cd8131998-03-06 17:16:21 +0000703#ifdef HAVE_MKTIME
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000704static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000705time_mktime(PyObject *self, PyObject *tup)
Guido van Rossum234f9421993-06-17 12:35:49 +0000706{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000707 struct tm buf;
708 time_t tt;
709 if (!gettmarg(tup, &buf))
710 return NULL;
Alexander Belopolskyb7d40d12011-01-11 01:21:25 +0000711 buf.tm_wday = -1; /* sentinel; original value ignored */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000712 tt = mktime(&buf);
Alexander Belopolskyb7d40d12011-01-11 01:21:25 +0000713 /* Return value of -1 does not necessarily mean an error, but tm_wday
Ezio Melotti13925002011-03-16 11:05:33 +0200714 * cannot remain set to -1 if mktime succeeded. */
Alexander Belopolskyb7d40d12011-01-11 01:21:25 +0000715 if (tt == (time_t)(-1) && buf.tm_wday == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000716 PyErr_SetString(PyExc_OverflowError,
717 "mktime argument out of range");
718 return NULL;
719 }
720 return PyFloat_FromDouble((double)tt);
Guido van Rossum234f9421993-06-17 12:35:49 +0000721}
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000722
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000723PyDoc_STRVAR(mktime_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000724"mktime(tuple) -> floating point number\n\
725\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000726Convert a time tuple in local time to seconds since the Epoch.");
Guido van Rossum60cd8131998-03-06 17:16:21 +0000727#endif /* HAVE_MKTIME */
Guido van Rossum234f9421993-06-17 12:35:49 +0000728
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000729#ifdef HAVE_WORKING_TZSET
Martin v. Löwis1a214512008-06-11 05:26:20 +0000730static void PyInit_timezone(PyObject *module);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000731
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000732static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000733time_tzset(PyObject *self, PyObject *unused)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000734{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000735 PyObject* m;
Fred Drake9bb74322002-04-01 14:49:59 +0000736
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000737 m = PyImport_ImportModuleNoBlock("time");
738 if (m == NULL) {
739 return NULL;
740 }
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000741
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000742 tzset();
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000743
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000744 /* Reset timezone, altzone, daylight and tzname */
745 PyInit_timezone(m);
746 Py_DECREF(m);
Tim Peters1b6f7a92004-06-20 02:50:16 +0000747
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000748 Py_INCREF(Py_None);
749 return Py_None;
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000750}
751
752PyDoc_STRVAR(tzset_doc,
R. David Murray4d55bf92010-12-14 00:55:46 +0000753"tzset()\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000754\n\
755Initialize, or reinitialize, the local timezone to the value stored in\n\
756os.environ['TZ']. The TZ environment variable should be specified in\n\
Neal Norwitzdc8e1942004-07-20 22:34:37 +0000757standard Unix timezone format as documented in the tzset man page\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000758(eg. 'US/Eastern', 'Europe/Amsterdam'). Unknown timezones will silently\n\
759fall back to UTC. If the TZ environment variable is not set, the local\n\
760timezone is set to the systems best guess of wallclock time.\n\
761Changing the TZ environment variable without calling tzset *may* change\n\
762the local timezone used by methods such as localtime, but this behaviour\n\
763should not be relied on.");
764#endif /* HAVE_WORKING_TZSET */
765
Victor Stinnerb94b2662012-01-18 01:50:21 +0100766static PyObject *
767time_wallclock(PyObject *self, PyObject *unused)
768{
769#if defined(MS_WINDOWS) && !defined(__BORLANDC__)
770 return time_clock(self, NULL);
771#elif defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_MONOTONIC)
772 static int clk_index = 0;
773 clockid_t clk_ids[] = {
774#ifdef CLOCK_MONOTONIC_RAW
775 CLOCK_MONOTONIC_RAW,
776#endif
777 CLOCK_MONOTONIC
778#ifdef CLOCK_REALTIME
779 /* On Linux, CLOCK_REALTIME uses the same clock than gettimeofday(),
780 but clock_gettime() has a nanosecond resolution. */
781 , CLOCK_REALTIME
782#endif
783 };
784 int ret;
785 struct timespec tp;
786
787 while (0 <= clk_index) {
788 clockid_t clk_id = clk_ids[clk_index];
789 ret = clock_gettime(clk_id, &tp);
790 if (ret == 0)
791 return PyFloat_FromDouble(tp.tv_sec + tp.tv_nsec * 1e-9);
792
793 clk_index++;
794 if (Py_ARRAY_LENGTH(clk_ids) <= clk_index)
795 clk_index = -1;
796 }
797 return time_time(self, NULL);
798#else
799 return time_time(self, NULL);
800#endif
801}
802
803PyDoc_STRVAR(wallclock_doc,
804"wallclock() -> float\n\
805\n\
806Return the current time in fractions of a second to the system's best\n\
807ability. Use this when the most accurate representation of wall-clock is\n\
Victor Stinner855889b2012-01-18 01:57:19 +0100808required, i.e. when \"processor time\" is inappropriate. The reference point\n\
Victor Stinnerb94b2662012-01-18 01:50:21 +0100809of the returned value is undefined so only the difference of consecutive\n\
810calls is valid.");
811
Martin v. Löwisd218dc12008-04-07 03:17:54 +0000812static void
Martin v. Löwis1a214512008-06-11 05:26:20 +0000813PyInit_timezone(PyObject *m) {
814 /* This code moved from PyInit_time wholesale to allow calling it from
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000815 time_tzset. In the future, some parts of it can be moved back
816 (for platforms that don't HAVE_WORKING_TZSET, when we know what they
817 are), and the extraneous calls to tzset(3) should be removed.
818 I haven't done this yet, as I don't want to change this code as
819 little as possible when introducing the time.tzset and time.tzsetwall
820 methods. This should simply be a method of doing the following once,
821 at the top of this function and removing the call to tzset() from
822 time_tzset():
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000823
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000824 #ifdef HAVE_TZSET
825 tzset()
826 #endif
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000827
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000828 And I'm lazy and hate C so nyer.
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000829 */
Guido van Rossum10b164a2001-09-25 13:59:01 +0000830#if defined(HAVE_TZNAME) && !defined(__GLIBC__) && !defined(__CYGWIN__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000831 PyObject *otz0, *otz1;
832 tzset();
Guido van Rossum26452411998-09-28 22:07:11 +0000833#ifdef PYOS_OS2
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000834 PyModule_AddIntConstant(m, "timezone", _timezone);
Guido van Rossum26452411998-09-28 22:07:11 +0000835#else /* !PYOS_OS2 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000836 PyModule_AddIntConstant(m, "timezone", timezone);
Guido van Rossum26452411998-09-28 22:07:11 +0000837#endif /* PYOS_OS2 */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000838#ifdef HAVE_ALTZONE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000839 PyModule_AddIntConstant(m, "altzone", altzone);
Guido van Rossumb6775db1994-08-01 11:34:53 +0000840#else
Guido van Rossum26452411998-09-28 22:07:11 +0000841#ifdef PYOS_OS2
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000842 PyModule_AddIntConstant(m, "altzone", _timezone-3600);
Guido van Rossum26452411998-09-28 22:07:11 +0000843#else /* !PYOS_OS2 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000844 PyModule_AddIntConstant(m, "altzone", timezone-3600);
Guido van Rossum26452411998-09-28 22:07:11 +0000845#endif /* PYOS_OS2 */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000846#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000847 PyModule_AddIntConstant(m, "daylight", daylight);
Victor Stinner1b579672011-12-17 05:47:23 +0100848 otz0 = PyUnicode_DecodeLocale(tzname[0], "surrogateescape");
849 otz1 = PyUnicode_DecodeLocale(tzname[1], "surrogateescape");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000850 PyModule_AddObject(m, "tzname", Py_BuildValue("(NN)", otz0, otz1));
Guido van Rossum10b164a2001-09-25 13:59:01 +0000851#else /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/
Martin v. Löwis60a5d722002-10-16 20:28:25 +0000852#ifdef HAVE_STRUCT_TM_TM_ZONE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000853 {
Guido van Rossum234f9421993-06-17 12:35:49 +0000854#define YEAR ((time_t)((365 * 24 + 6) * 3600))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000855 time_t t;
856 struct tm *p;
857 long janzone, julyzone;
858 char janname[10], julyname[10];
859 t = (time((time_t *)0) / YEAR) * YEAR;
860 p = localtime(&t);
861 janzone = -p->tm_gmtoff;
862 strncpy(janname, p->tm_zone ? p->tm_zone : " ", 9);
863 janname[9] = '\0';
864 t += YEAR/2;
865 p = localtime(&t);
866 julyzone = -p->tm_gmtoff;
867 strncpy(julyname, p->tm_zone ? p->tm_zone : " ", 9);
868 julyname[9] = '\0';
Guido van Rossum10b164a2001-09-25 13:59:01 +0000869
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000870 if( janzone < julyzone ) {
871 /* DST is reversed in the southern hemisphere */
872 PyModule_AddIntConstant(m, "timezone", julyzone);
873 PyModule_AddIntConstant(m, "altzone", janzone);
874 PyModule_AddIntConstant(m, "daylight",
875 janzone != julyzone);
876 PyModule_AddObject(m, "tzname",
877 Py_BuildValue("(zz)",
878 julyname, janname));
879 } else {
880 PyModule_AddIntConstant(m, "timezone", janzone);
881 PyModule_AddIntConstant(m, "altzone", julyzone);
882 PyModule_AddIntConstant(m, "daylight",
883 janzone != julyzone);
884 PyModule_AddObject(m, "tzname",
885 Py_BuildValue("(zz)",
886 janname, julyname));
887 }
888 }
Guido van Rossume6a4b7b1997-10-08 15:27:56 +0000889#else
Martin v. Löwis60a5d722002-10-16 20:28:25 +0000890#endif /* HAVE_STRUCT_TM_TM_ZONE */
Tim Peters26ae7cd2001-03-20 03:26:49 +0000891#ifdef __CYGWIN__
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000892 tzset();
893 PyModule_AddIntConstant(m, "timezone", _timezone);
894 PyModule_AddIntConstant(m, "altzone", _timezone-3600);
895 PyModule_AddIntConstant(m, "daylight", _daylight);
896 PyModule_AddObject(m, "tzname",
897 Py_BuildValue("(zz)", _tzname[0], _tzname[1]));
Tim Peters26ae7cd2001-03-20 03:26:49 +0000898#endif /* __CYGWIN__ */
Guido van Rossum10b164a2001-09-25 13:59:01 +0000899#endif /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/
Victor Stinnere0be4232011-10-25 13:06:09 +0200900
901#if defined(HAVE_CLOCK_GETTIME) || defined(HAVE_CLOCK_GETRES)
902#ifdef CLOCK_REALTIME
903 PyModule_AddIntMacro(m, CLOCK_REALTIME);
904#endif
905#ifdef CLOCK_MONOTONIC
906 PyModule_AddIntMacro(m, CLOCK_MONOTONIC);
907#endif
908#ifdef CLOCK_MONOTONIC_RAW
909 PyModule_AddIntMacro(m, CLOCK_MONOTONIC_RAW);
910#endif
911#ifdef CLOCK_PROCESS_CPUTIME_ID
912 PyModule_AddIntMacro(m, CLOCK_PROCESS_CPUTIME_ID);
913#endif
914#ifdef CLOCK_THREAD_CPUTIME_ID
915 PyModule_AddIntMacro(m, CLOCK_THREAD_CPUTIME_ID);
916#endif
917#endif /* HAVE_CLOCK_GETTIME */
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000918}
919
920
921static PyMethodDef time_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000922 {"time", time_time, METH_NOARGS, time_doc},
Victor Stinner9122fdd2011-07-04 13:55:40 +0200923#if (defined(MS_WINDOWS) && !defined(__BORLANDC__)) || defined(HAVE_CLOCK)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000924 {"clock", time_clock, METH_NOARGS, clock_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000925#endif
Victor Stinnere0be4232011-10-25 13:06:09 +0200926#ifdef HAVE_CLOCK_GETTIME
927 {"clock_gettime", time_clock_gettime, METH_VARARGS, clock_gettime_doc},
928#endif
929#ifdef HAVE_CLOCK_GETRES
930 {"clock_getres", time_clock_getres, METH_VARARGS, clock_getres_doc},
931#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000932 {"sleep", time_sleep, METH_VARARGS, sleep_doc},
933 {"gmtime", time_gmtime, METH_VARARGS, gmtime_doc},
934 {"localtime", time_localtime, METH_VARARGS, localtime_doc},
935 {"asctime", time_asctime, METH_VARARGS, asctime_doc},
936 {"ctime", time_ctime, METH_VARARGS, ctime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000937#ifdef HAVE_MKTIME
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000938 {"mktime", time_mktime, METH_O, mktime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000939#endif
940#ifdef HAVE_STRFTIME
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000941 {"strftime", time_strftime, METH_VARARGS, strftime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000942#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000943 {"strptime", time_strptime, METH_VARARGS, strptime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000944#ifdef HAVE_WORKING_TZSET
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000945 {"tzset", time_tzset, METH_NOARGS, tzset_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000946#endif
Victor Stinnerb94b2662012-01-18 01:50:21 +0100947 {"wallclock", time_wallclock, METH_NOARGS, wallclock_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000948 {NULL, NULL} /* sentinel */
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000949};
950
951
952PyDoc_STRVAR(module_doc,
953"This module provides various functions to manipulate time values.\n\
954\n\
955There are two standard representations of time. One is the number\n\
956of seconds since the Epoch, in UTC (a.k.a. GMT). It may be an integer\n\
957or a floating point number (to represent fractions of seconds).\n\
958The Epoch is system-defined; on Unix, it is generally January 1st, 1970.\n\
959The actual value can be retrieved by calling gmtime(0).\n\
960\n\
961The other representation is a tuple of 9 integers giving local time.\n\
962The tuple items are:\n\
Alexander Belopolsky03163ac2011-05-02 12:20:52 -0400963 year (including century, e.g. 1998)\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000964 month (1-12)\n\
965 day (1-31)\n\
966 hours (0-23)\n\
967 minutes (0-59)\n\
968 seconds (0-59)\n\
969 weekday (0-6, Monday is 0)\n\
970 Julian day (day in the year, 1-366)\n\
971 DST (Daylight Savings Time) flag (-1, 0 or 1)\n\
972If the DST flag is 0, the time is given in the regular time zone;\n\
973if it is 1, the time is given in the DST time zone;\n\
974if it is -1, mktime() should guess based on the date and time.\n\
975\n\
976Variables:\n\
977\n\
978timezone -- difference in seconds between UTC and local standard time\n\
979altzone -- difference in seconds between UTC and local DST time\n\
980daylight -- whether local time should reflect DST\n\
981tzname -- tuple of (standard time zone name, DST time zone name)\n\
982\n\
983Functions:\n\
984\n\
985time() -- return current time in seconds since the Epoch as a float\n\
986clock() -- return CPU time since process start as a float\n\
987sleep() -- delay for a number of seconds given as a float\n\
988gmtime() -- convert seconds since Epoch to UTC tuple\n\
989localtime() -- convert seconds since Epoch to local time tuple\n\
990asctime() -- convert time tuple to string\n\
991ctime() -- convert time in seconds to string\n\
992mktime() -- convert local time tuple to seconds since Epoch\n\
993strftime() -- convert time tuple to string according to format specification\n\
994strptime() -- parse string to time tuple according to format specification\n\
995tzset() -- change the local timezone");
996
997
Martin v. Löwis1a214512008-06-11 05:26:20 +0000998
999static struct PyModuleDef timemodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001000 PyModuleDef_HEAD_INIT,
1001 "time",
1002 module_doc,
1003 -1,
1004 time_methods,
1005 NULL,
1006 NULL,
1007 NULL,
1008 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00001009};
1010
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001011PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00001012PyInit_time(void)
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001013{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001014 PyObject *m;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001015 m = PyModule_Create(&timemodule);
1016 if (m == NULL)
1017 return NULL;
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001018
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001019 /* Set, or reset, module variables like time.timezone */
1020 PyInit_timezone(m);
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001021
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001022 if (!initialized) {
1023 PyStructSequence_InitType(&StructTimeType,
1024 &struct_time_type_desc);
1025 }
1026 Py_INCREF(&StructTimeType);
1027 PyModule_AddObject(m, "struct_time", (PyObject*) &StructTimeType);
1028 initialized = 1;
1029 return m;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001030}
1031
Guido van Rossumb6775db1994-08-01 11:34:53 +00001032static double
Thomas Woutersf3f33dc2000-07-21 06:00:07 +00001033floattime(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001034{
Alexander Belopolsky6fc4ade2010-08-05 17:34:27 +00001035 _PyTime_timeval t;
1036 _PyTime_gettimeofday(&t);
1037 return (double)t.tv_sec + t.tv_usec*0.000001;
Guido van Rossum426035c1991-02-19 12:27:35 +00001038}
1039
Guido van Rossumb6775db1994-08-01 11:34:53 +00001040
1041/* Implement floatsleep() for various platforms.
1042 When interrupted (or when another error occurs), return -1 and
1043 set an exception; else return 0. */
1044
1045static int
Guido van Rossuma320fd31995-03-09 12:14:15 +00001046floatsleep(double secs)
Guido van Rossum426035c1991-02-19 12:27:35 +00001047{
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001048/* XXX Should test for MS_WINDOWS first! */
Skip Montanaroeb33e5a2007-08-17 12:57:41 +00001049#if defined(HAVE_SELECT) && !defined(__EMX__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001050 struct timeval t;
1051 double frac;
Victor Stinner48b1ce52011-07-01 13:50:09 +02001052 int err;
1053
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001054 frac = fmod(secs, 1.0);
1055 secs = floor(secs);
1056 t.tv_sec = (long)secs;
1057 t.tv_usec = (long)(frac*1000000.0);
1058 Py_BEGIN_ALLOW_THREADS
Victor Stinner48b1ce52011-07-01 13:50:09 +02001059 err = select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &t);
1060 Py_END_ALLOW_THREADS
1061 if (err != 0) {
Guido van Rossum09cbb011999-11-08 15:32:27 +00001062#ifdef EINTR
Victor Stinner48b1ce52011-07-01 13:50:09 +02001063 if (errno == EINTR) {
1064 if (PyErr_CheckSignals())
1065 return -1;
1066 }
1067 else
Guido van Rossum09cbb011999-11-08 15:32:27 +00001068#endif
Victor Stinner48b1ce52011-07-01 13:50:09 +02001069 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001070 PyErr_SetFromErrno(PyExc_IOError);
1071 return -1;
1072 }
1073 }
Martin v. Löwis02af9642002-01-16 11:04:06 +00001074#elif defined(__WATCOMC__) && !defined(__QNX__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001075 /* XXX Can't interrupt this sleep */
1076 Py_BEGIN_ALLOW_THREADS
1077 delay((int)(secs * 1000 + 0.5)); /* delay() uses milliseconds */
1078 Py_END_ALLOW_THREADS
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001079#elif defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001080 {
1081 double millisecs = secs * 1000.0;
1082 unsigned long ul_millis;
Tim Peters513a1cd2003-01-19 04:54:58 +00001083
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001084 if (millisecs > (double)ULONG_MAX) {
1085 PyErr_SetString(PyExc_OverflowError,
1086 "sleep length is too large");
1087 return -1;
1088 }
1089 Py_BEGIN_ALLOW_THREADS
1090 /* Allow sleep(0) to maintain win32 semantics, and as decreed
1091 * by Guido, only the main thread can be interrupted.
1092 */
1093 ul_millis = (unsigned long)millisecs;
Antoine Pitrou6dd381e2011-11-21 21:26:56 +01001094 if (ul_millis == 0 || !_PyOS_IsMainThread())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001095 Sleep(ul_millis);
1096 else {
1097 DWORD rc;
Antoine Pitrou6dd381e2011-11-21 21:26:56 +01001098 HANDLE hInterruptEvent = _PyOS_SigintEvent();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001099 ResetEvent(hInterruptEvent);
1100 rc = WaitForSingleObject(hInterruptEvent, ul_millis);
1101 if (rc == WAIT_OBJECT_0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001102 Py_BLOCK_THREADS
1103 errno = EINTR;
1104 PyErr_SetFromErrno(PyExc_IOError);
1105 return -1;
1106 }
1107 }
1108 Py_END_ALLOW_THREADS
1109 }
Martin v. Löwis02af9642002-01-16 11:04:06 +00001110#elif defined(PYOS_OS2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001111 /* This Sleep *IS* Interruptable by Exceptions */
1112 Py_BEGIN_ALLOW_THREADS
1113 if (DosSleep(secs * 1000) != NO_ERROR) {
1114 Py_BLOCK_THREADS
1115 PyErr_SetFromErrno(PyExc_IOError);
1116 return -1;
1117 }
1118 Py_END_ALLOW_THREADS
Martin v. Löwis02af9642002-01-16 11:04:06 +00001119#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001120 /* XXX Can't interrupt this sleep */
1121 Py_BEGIN_ALLOW_THREADS
1122 sleep((int)secs);
1123 Py_END_ALLOW_THREADS
Martin v. Löwis02af9642002-01-16 11:04:06 +00001124#endif
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001125
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001126 return 0;
Guido van Rossum80c9d881991-04-16 08:47:51 +00001127}