blob: b6972aec79e55d0e61a905d02f59879d96b6976a [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
Thomas Wouters477c8d52006-05-27 19:21:47 +000065#if defined(MS_WINDOWS) && !defined(__BORLANDC__)
Victor Stinner9122fdd2011-07-04 13:55:40 +020066/* Win32 has better clock replacement; we have our own version, due to Mark
67 Hammond and Tim Peters */
Guido van Rossum3917c221997-04-02 05:35:28 +000068static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000069time_clock(PyObject *self, PyObject *unused)
Guido van Rossum3917c221997-04-02 05:35:28 +000070{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000071 static LARGE_INTEGER ctrStart;
72 static double divisor = 0.0;
73 LARGE_INTEGER now;
74 double diff;
Guido van Rossum3917c221997-04-02 05:35:28 +000075
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000076 if (divisor == 0.0) {
77 LARGE_INTEGER freq;
78 QueryPerformanceCounter(&ctrStart);
79 if (!QueryPerformanceFrequency(&freq) || freq.QuadPart == 0) {
80 /* Unlikely to happen - this works on all intel
81 machines at least! Revert to clock() */
82 return PyFloat_FromDouble(((double)clock()) /
83 CLOCKS_PER_SEC);
84 }
85 divisor = (double)freq.QuadPart;
86 }
87 QueryPerformanceCounter(&now);
88 diff = (double)(now.QuadPart - ctrStart.QuadPart);
89 return PyFloat_FromDouble(diff / divisor);
Guido van Rossum3917c221997-04-02 05:35:28 +000090}
Guido van Rossum0ef577b1998-06-27 20:38:36 +000091
Victor Stinner9122fdd2011-07-04 13:55:40 +020092#elif defined(HAVE_CLOCK)
93
94#ifndef CLOCKS_PER_SEC
95#ifdef CLK_TCK
96#define CLOCKS_PER_SEC CLK_TCK
97#else
98#define CLOCKS_PER_SEC 1000000
99#endif
100#endif
101
102static PyObject *
103time_clock(PyObject *self, PyObject *unused)
104{
105 return PyFloat_FromDouble(((double)clock()) / CLOCKS_PER_SEC);
106}
107#endif /* HAVE_CLOCK */
108
Guido van Rossum3917c221997-04-02 05:35:28 +0000109
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000110#ifdef HAVE_CLOCK
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000111PyDoc_STRVAR(clock_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000112"clock() -> floating point number\n\
113\n\
114Return the CPU time or real time since the start of the process or since\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000115the first call to clock(). This has as much precision as the system\n\
116records.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000117#endif
118
Victor Stinnere0be4232011-10-25 13:06:09 +0200119#ifdef HAVE_CLOCK_GETTIME
120static PyObject *
121time_clock_gettime(PyObject *self, PyObject *args)
122{
123 int ret;
124 clockid_t clk_id;
125 struct timespec tp;
126
127 if (!PyArg_ParseTuple(args, "i:clock_gettime", &clk_id))
128 return NULL;
129
130 ret = clock_gettime((clockid_t)clk_id, &tp);
131 if (ret != 0)
132 PyErr_SetFromErrno(PyExc_IOError);
133
134 return PyFloat_FromDouble(tp.tv_sec + tp.tv_nsec * 1e-9);
135}
136
137PyDoc_STRVAR(clock_gettime_doc,
138"clock_gettime(clk_id) -> floating point number\n\
139\n\
140Return the time of the specified clock clk_id.");
141#endif
142
143#ifdef HAVE_CLOCK_GETRES
144static PyObject *
145time_clock_getres(PyObject *self, PyObject *args)
146{
147 int ret;
148 clockid_t clk_id;
149 struct timespec tp;
150
151 if (!PyArg_ParseTuple(args, "i:clock_getres", &clk_id))
152 return NULL;
153
154 ret = clock_getres((clockid_t)clk_id, &tp);
155 if (ret != 0)
156 PyErr_SetFromErrno(PyExc_IOError);
157
158 return PyFloat_FromDouble(tp.tv_sec + tp.tv_nsec * 1e-9);
159}
160
161PyDoc_STRVAR(clock_getres_doc,
162"clock_getres(clk_id) -> floating point number\n\
163\n\
164Return the resolution (precision) of the specified clock clk_id.");
165#endif
166
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000167static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000168time_sleep(PyObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000169{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000170 double secs;
171 if (!PyArg_ParseTuple(args, "d:sleep", &secs))
172 return NULL;
Victor Stinner7f53a502011-07-05 22:00:25 +0200173 if (secs < 0) {
174 PyErr_SetString(PyExc_ValueError,
175 "sleep length must be non-negative");
176 return NULL;
177 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000178 if (floatsleep(secs) != 0)
179 return NULL;
180 Py_INCREF(Py_None);
181 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000182}
183
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000184PyDoc_STRVAR(sleep_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000185"sleep(seconds)\n\
186\n\
187Delay execution for a given number of seconds. The argument may be\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000188a floating point number for subsecond precision.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000189
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000190static PyStructSequence_Field struct_time_type_fields[] = {
Alexander Belopolsky69f3fd02010-06-05 15:04:51 +0000191 {"tm_year", "year, for example, 1993"},
192 {"tm_mon", "month of year, range [1, 12]"},
193 {"tm_mday", "day of month, range [1, 31]"},
194 {"tm_hour", "hours, range [0, 23]"},
195 {"tm_min", "minutes, range [0, 59]"},
196 {"tm_sec", "seconds, range [0, 61])"},
197 {"tm_wday", "day of week, range [0, 6], Monday is 0"},
198 {"tm_yday", "day of year, range [1, 366]"},
199 {"tm_isdst", "1 if summer time is in effect, 0 if not, and -1 if unknown"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000200 {0}
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000201};
202
203static PyStructSequence_Desc struct_time_type_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000204 "time.struct_time",
Alexander Belopolsky69f3fd02010-06-05 15:04:51 +0000205 "The time value as returned by gmtime(), localtime(), and strptime(), and\n"
206 " accepted by asctime(), mktime() and strftime(). May be considered as a\n"
207 " sequence of 9 integers.\n\n"
208 " Note that several fields' values are not the same as those defined by\n"
209 " the C language standard for struct tm. For example, the value of the\n"
210 " field tm_year is the actual year, not year - 1900. See individual\n"
211 " fields' descriptions for details.",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000212 struct_time_type_fields,
213 9,
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000214};
Tim Peters9ad4b682002-02-13 05:14:18 +0000215
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000216static int initialized;
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000217static PyTypeObject StructTimeType;
218
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000219static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000220tmtotuple(struct tm *p)
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000221{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000222 PyObject *v = PyStructSequence_New(&StructTimeType);
223 if (v == NULL)
224 return NULL;
Tim Peters9ad4b682002-02-13 05:14:18 +0000225
Christian Heimes217cfd12007-12-02 14:31:20 +0000226#define SET(i,val) PyStructSequence_SET_ITEM(v, i, PyLong_FromLong((long) val))
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000227
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000228 SET(0, p->tm_year + 1900);
229 SET(1, p->tm_mon + 1); /* Want January == 1 */
230 SET(2, p->tm_mday);
231 SET(3, p->tm_hour);
232 SET(4, p->tm_min);
233 SET(5, p->tm_sec);
234 SET(6, (p->tm_wday + 6) % 7); /* Want Monday == 0 */
235 SET(7, p->tm_yday + 1); /* Want January, 1 == 1 */
236 SET(8, p->tm_isdst);
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000237#undef SET
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000238 if (PyErr_Occurred()) {
239 Py_XDECREF(v);
240 return NULL;
241 }
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000242
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000243 return v;
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000244}
245
246static PyObject *
Brett Cannon298c3802004-06-19 20:48:43 +0000247time_convert(double when, struct tm * (*function)(const time_t *))
Guido van Rossum234f9421993-06-17 12:35:49 +0000248{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000249 struct tm *p;
250 time_t whent = _PyTime_DoubleToTimet(when);
Brett Cannon298c3802004-06-19 20:48:43 +0000251
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000252 if (whent == (time_t)-1 && PyErr_Occurred())
253 return NULL;
254 errno = 0;
255 p = function(&whent);
256 if (p == NULL) {
Guido van Rossum6e8583d1996-10-08 14:19:52 +0000257#ifdef EINVAL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000258 if (errno == 0)
259 errno = EINVAL;
Guido van Rossum6e8583d1996-10-08 14:19:52 +0000260#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000261 return PyErr_SetFromErrno(PyExc_ValueError);
262 }
263 return tmtotuple(p);
Guido van Rossum234f9421993-06-17 12:35:49 +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
271parse_time_double_args(PyObject *args, char *format, double *pwhen)
272{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000273 PyObject *ot = NULL;
Fred Drakef901abd2004-08-03 17:58:55 +0000274
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000275 if (!PyArg_ParseTuple(args, format, &ot))
276 return 0;
277 if (ot == NULL || ot == Py_None)
278 *pwhen = floattime();
279 else {
280 double when = PyFloat_AsDouble(ot);
281 if (PyErr_Occurred())
282 return 0;
283 *pwhen = when;
284 }
285 return 1;
Fred Drakef901abd2004-08-03 17:58:55 +0000286}
287
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000288static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000289time_gmtime(PyObject *self, PyObject *args)
Guido van Rossum234f9421993-06-17 12:35:49 +0000290{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000291 double when;
292 if (!parse_time_double_args(args, "|O:gmtime", &when))
293 return NULL;
294 return time_convert(when, gmtime);
Guido van Rossum234f9421993-06-17 12:35:49 +0000295}
296
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000297PyDoc_STRVAR(gmtime_doc,
Christian Heimes9a371592007-12-28 14:08:13 +0000298"gmtime([seconds]) -> (tm_year, tm_mon, tm_mday, tm_hour, tm_min,\n\
Fred Drake193a3f62002-03-12 21:38:49 +0000299 tm_sec, tm_wday, tm_yday, tm_isdst)\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000300\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000301Convert seconds since the Epoch to a time tuple expressing UTC (a.k.a.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000302GMT). When 'seconds' is not passed in, convert the current time instead.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000303
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000304static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000305time_localtime(PyObject *self, PyObject *args)
Guido van Rossum234f9421993-06-17 12:35:49 +0000306{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000307 double when;
308 if (!parse_time_double_args(args, "|O:localtime", &when))
309 return NULL;
310 return time_convert(when, localtime);
Guido van Rossum234f9421993-06-17 12:35:49 +0000311}
312
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000313PyDoc_STRVAR(localtime_doc,
Christian Heimes9a371592007-12-28 14:08:13 +0000314"localtime([seconds]) -> (tm_year,tm_mon,tm_mday,tm_hour,tm_min,\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000315 tm_sec,tm_wday,tm_yday,tm_isdst)\n\
Martin v. Löwisb3cfc1d2001-12-02 12:27:43 +0000316\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000317Convert seconds since the Epoch to a time tuple expressing local time.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000318When 'seconds' is not passed in, convert the current time instead.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000319
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000320/* Convert 9-item tuple to tm structure. Return 1 on success, set
321 * an exception and return 0 on error.
322 */
Guido van Rossum9e90a671993-06-24 11:10:19 +0000323static int
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000324gettmarg(PyObject *args, struct tm *p)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000325{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000326 int y;
Guido van Rossumcfbaecc1998-08-25 14:51:12 +0000327
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000328 memset((void *) p, '\0', sizeof(struct tm));
Guido van Rossumb9081262007-08-25 03:14:09 +0000329
Alexander Belopolsky610e5442011-01-06 21:57:06 +0000330 if (!PyTuple_Check(args)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000331 PyErr_SetString(PyExc_TypeError,
332 "Tuple or struct_time argument required");
333 return 0;
334 }
Skip Montanaro41cfce92007-08-24 21:11:00 +0000335
Alexander Belopolsky610e5442011-01-06 21:57:06 +0000336 if (!PyArg_ParseTuple(args, "iiiiiiiii",
337 &y, &p->tm_mon, &p->tm_mday,
338 &p->tm_hour, &p->tm_min, &p->tm_sec,
339 &p->tm_wday, &p->tm_yday, &p->tm_isdst))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000340 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000341 p->tm_year = y - 1900;
342 p->tm_mon--;
343 p->tm_wday = (p->tm_wday + 1) % 7;
344 p->tm_yday--;
345 return 1;
Guido van Rossum9e90a671993-06-24 11:10:19 +0000346}
347
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000348/* Check values of the struct tm fields before it is passed to strftime() and
349 * asctime(). Return 1 if all values are valid, otherwise set an exception
350 * and returns 0.
351 */
Victor Stinneref128102010-10-07 01:00:52 +0000352static int
353checktm(struct tm* buf)
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000354{
Victor Stinneref128102010-10-07 01:00:52 +0000355 /* Checks added to make sure strftime() and asctime() does not crash Python by
356 indexing blindly into some array for a textual representation
357 by some bad index (fixes bug #897625 and #6608).
358
359 Also support values of zero from Python code for arguments in which
360 that is out of range by forcing that value to the lowest value that
361 is valid (fixed bug #1520914).
362
363 Valid ranges based on what is allowed in struct tm:
364
365 - tm_year: [0, max(int)] (1)
366 - tm_mon: [0, 11] (2)
367 - tm_mday: [1, 31]
368 - tm_hour: [0, 23]
369 - tm_min: [0, 59]
370 - tm_sec: [0, 60]
371 - tm_wday: [0, 6] (1)
372 - tm_yday: [0, 365] (2)
373 - tm_isdst: [-max(int), max(int)]
374
375 (1) gettmarg() handles bounds-checking.
376 (2) Python's acceptable range is one greater than the range in C,
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000377 thus need to check against automatic decrement by gettmarg().
378 */
379 if (buf->tm_mon == -1)
380 buf->tm_mon = 0;
381 else if (buf->tm_mon < 0 || buf->tm_mon > 11) {
382 PyErr_SetString(PyExc_ValueError, "month out of range");
383 return 0;
384 }
385 if (buf->tm_mday == 0)
386 buf->tm_mday = 1;
387 else if (buf->tm_mday < 0 || buf->tm_mday > 31) {
388 PyErr_SetString(PyExc_ValueError, "day of month out of range");
389 return 0;
390 }
391 if (buf->tm_hour < 0 || buf->tm_hour > 23) {
392 PyErr_SetString(PyExc_ValueError, "hour out of range");
393 return 0;
394 }
395 if (buf->tm_min < 0 || buf->tm_min > 59) {
396 PyErr_SetString(PyExc_ValueError, "minute out of range");
397 return 0;
398 }
399 if (buf->tm_sec < 0 || buf->tm_sec > 61) {
400 PyErr_SetString(PyExc_ValueError, "seconds out of range");
401 return 0;
402 }
403 /* tm_wday does not need checking of its upper-bound since taking
404 ``% 7`` in gettmarg() automatically restricts the range. */
405 if (buf->tm_wday < 0) {
406 PyErr_SetString(PyExc_ValueError, "day of week out of range");
407 return 0;
408 }
409 if (buf->tm_yday == -1)
410 buf->tm_yday = 0;
411 else if (buf->tm_yday < 0 || buf->tm_yday > 365) {
412 PyErr_SetString(PyExc_ValueError, "day of year out of range");
413 return 0;
414 }
415 return 1;
416}
417
Victor Stinnerc1f32ca2011-10-14 02:36:13 +0200418#ifdef MS_WINDOWS
419 /* wcsftime() doesn't format correctly time zones, see issue #10653 */
420# undef HAVE_WCSFTIME
421#endif
422
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000423#ifdef HAVE_STRFTIME
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000424#ifdef HAVE_WCSFTIME
425#define time_char wchar_t
426#define format_time wcsftime
427#define time_strlen wcslen
428#else
429#define time_char char
430#define format_time strftime
431#define time_strlen strlen
432#endif
433
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000434static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000435time_strftime(PyObject *self, PyObject *args)
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000436{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000437 PyObject *tup = NULL;
438 struct tm buf;
439 const time_char *fmt;
Victor Stinnerb2904782010-09-29 10:34:19 +0000440#ifdef HAVE_WCSFTIME
441 wchar_t *format;
442#else
443 PyObject *format;
444#endif
Victor Stinneref128102010-10-07 01:00:52 +0000445 PyObject *format_arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000446 size_t fmtlen, buflen;
Victor Stinnerb2904782010-09-29 10:34:19 +0000447 time_char *outbuf = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000448 size_t i;
Victor Stinnerb2904782010-09-29 10:34:19 +0000449 PyObject *ret = NULL;
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000450
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000451 memset((void *) &buf, '\0', sizeof(buf));
Guido van Rossum1f41f841998-04-27 19:04:26 +0000452
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000453 /* Will always expect a unicode string to be passed as format.
454 Given that there's no str type anymore in py3k this seems safe.
455 */
Victor Stinneref128102010-10-07 01:00:52 +0000456 if (!PyArg_ParseTuple(args, "U|O:strftime", &format_arg, &tup))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000457 return NULL;
Thomas Woutersfe385252001-01-19 23:16:56 +0000458
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000459 if (tup == NULL) {
460 time_t tt = time(NULL);
461 buf = *localtime(&tt);
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000462 }
463 else if (!gettmarg(tup, &buf) || !checktm(&buf))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000464 return NULL;
Guido van Rossum10b164a2001-09-25 13:59:01 +0000465
Victor Stinner06ec45e2011-01-08 03:35:36 +0000466#if defined(_MSC_VER) || defined(sun)
Victor Stinner73ea29c2011-01-08 01:56:31 +0000467 if (buf.tm_year + 1900 < 1 || 9999 < buf.tm_year + 1900) {
Victor Stinner6f0e4f92011-03-21 02:14:53 +0100468 PyErr_SetString(PyExc_ValueError,
469 "strftime() requires year in [1; 9999]");
Alexander Belopolsky0dd06f42011-01-08 01:23:02 +0000470 return NULL;
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000471 }
Victor Stinner73ea29c2011-01-08 01:56:31 +0000472#endif
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000473
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000474 /* Normalize tm_isdst just in case someone foolishly implements %Z
475 based on the assumption that tm_isdst falls within the range of
476 [-1, 1] */
477 if (buf.tm_isdst < -1)
478 buf.tm_isdst = -1;
479 else if (buf.tm_isdst > 1)
480 buf.tm_isdst = 1;
Brett Cannond1080a32004-03-02 04:38:10 +0000481
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000482#ifdef HAVE_WCSFTIME
Victor Stinnerbeb4135b2010-10-07 01:02:42 +0000483 format = PyUnicode_AsWideCharString(format_arg, NULL);
Victor Stinnerb2904782010-09-29 10:34:19 +0000484 if (format == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000485 return NULL;
Victor Stinnerb2904782010-09-29 10:34:19 +0000486 fmt = format;
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000487#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000488 /* Convert the unicode string to an ascii one */
Victor Stinner1b579672011-12-17 05:47:23 +0100489 format = PyUnicode_EncodeLocale(format_arg, "surrogateescape");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000490 if (format == NULL)
491 return NULL;
492 fmt = PyBytes_AS_STRING(format);
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000493#endif
Amaury Forgeot d'Arcb5be6d42009-03-02 23:52:57 +0000494
Victor Stinner5a3ff792011-10-16 19:08:23 +0200495#if defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000496 /* check that the format string contains only valid directives */
Victor Stinner5a3ff792011-10-16 19:08:23 +0200497 for(outbuf = strchr(fmt, '%');
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000498 outbuf != NULL;
Victor Stinner5a3ff792011-10-16 19:08:23 +0200499 outbuf = strchr(outbuf+2, '%'))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000500 {
501 if (outbuf[1]=='#')
502 ++outbuf; /* not documented by python, */
503 if (outbuf[1]=='\0' ||
Victor Stinner5a3ff792011-10-16 19:08:23 +0200504 !strchr("aAbBcdHIjmMpSUwWxXyYzZ%", outbuf[1]))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000505 {
506 PyErr_SetString(PyExc_ValueError, "Invalid format string");
507 return 0;
508 }
509 }
Amaury Forgeot d'Arcb5be6d42009-03-02 23:52:57 +0000510#endif
511
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000512 fmtlen = time_strlen(fmt);
Guido van Rossumc222ec21999-02-23 00:00:10 +0000513
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000514 /* I hate these functions that presume you know how big the output
515 * will be ahead of time...
516 */
517 for (i = 1024; ; i += i) {
Victor Stinner136ea492011-12-17 22:37:18 +0100518#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100519 int err;
Victor Stinner136ea492011-12-17 22:37:18 +0100520#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000521 outbuf = (time_char *)PyMem_Malloc(i*sizeof(time_char));
522 if (outbuf == NULL) {
Victor Stinnerb2904782010-09-29 10:34:19 +0000523 PyErr_NoMemory();
524 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000525 }
526 buflen = format_time(outbuf, i, fmt, &buf);
Victor Stinner136ea492011-12-17 22:37:18 +0100527#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100528 err = errno;
Victor Stinner136ea492011-12-17 22:37:18 +0100529#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000530 if (buflen > 0 || i >= 256 * fmtlen) {
531 /* If the buffer is 256 times as long as the format,
532 it's probably not failing for lack of room!
533 More likely, the format yields an empty result,
534 e.g. an empty format, or %Z when the timezone
535 is unknown. */
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000536#ifdef HAVE_WCSFTIME
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000537 ret = PyUnicode_FromWideChar(outbuf, buflen);
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000538#else
Victor Stinner1b579672011-12-17 05:47:23 +0100539 ret = PyUnicode_DecodeLocaleAndSize(outbuf, buflen,
540 "surrogateescape");
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000541#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000542 PyMem_Free(outbuf);
Victor Stinnerb2904782010-09-29 10:34:19 +0000543 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000544 }
545 PyMem_Free(outbuf);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000546#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000547 /* VisualStudio .NET 2005 does this properly */
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100548 if (buflen == 0 && err == EINVAL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000549 PyErr_SetString(PyExc_ValueError, "Invalid format string");
Victor Stinnerb2904782010-09-29 10:34:19 +0000550 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000551 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000552#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000553 }
Victor Stinnerb2904782010-09-29 10:34:19 +0000554#ifdef HAVE_WCSFTIME
555 PyMem_Free(format);
556#else
557 Py_DECREF(format);
558#endif
559 return ret;
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000560}
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000561
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000562#undef time_char
563#undef format_time
564
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000565PyDoc_STRVAR(strftime_doc,
Thomas Woutersfe385252001-01-19 23:16:56 +0000566"strftime(format[, tuple]) -> string\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000567\n\
568Convert a time tuple to a string according to a format specification.\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000569See the library reference manual for formatting codes. When the time tuple\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000570is not present, current time as returned by localtime() is used.");
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000571#endif /* HAVE_STRFTIME */
572
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000573static PyObject *
574time_strptime(PyObject *self, PyObject *args)
575{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000576 PyObject *strptime_module = PyImport_ImportModuleNoBlock("_strptime");
577 PyObject *strptime_result;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200578 _Py_IDENTIFIER(_strptime_time);
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000579
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000580 if (!strptime_module)
581 return NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200582 strptime_result = _PyObject_CallMethodId(strptime_module,
583 &PyId__strptime_time, "O", args);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000584 Py_DECREF(strptime_module);
585 return strptime_result;
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000586}
587
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000588
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000589PyDoc_STRVAR(strptime_doc,
Brett Cannon20def8b2003-07-01 05:16:08 +0000590"strptime(string, format) -> struct_time\n\
Martin v. Löwisb3cfc1d2001-12-02 12:27:43 +0000591\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000592Parse a string to a time tuple according to a format specification.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000593See the library reference manual for formatting codes (same as strftime()).");
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000594
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000595static PyObject *
596_asctime(struct tm *timeptr)
597{
598 /* Inspired by Open Group reference implementation available at
599 * http://pubs.opengroup.org/onlinepubs/009695399/functions/asctime.html */
Victor Stinner499dfcf2011-03-21 13:26:24 +0100600 static char wday_name[7][4] = {
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000601 "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
602 };
Victor Stinner499dfcf2011-03-21 13:26:24 +0100603 static char mon_name[12][4] = {
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000604 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
605 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
606 };
Victor Stinner499dfcf2011-03-21 13:26:24 +0100607 return PyUnicode_FromFormat(
608 "%s %s%3d %.2d:%.2d:%.2d %d",
609 wday_name[timeptr->tm_wday],
610 mon_name[timeptr->tm_mon],
611 timeptr->tm_mday, timeptr->tm_hour,
612 timeptr->tm_min, timeptr->tm_sec,
613 1900 + timeptr->tm_year);
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000614}
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000615
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000616static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000617time_asctime(PyObject *self, PyObject *args)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000618{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000619 PyObject *tup = NULL;
620 struct tm buf;
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000622 if (!PyArg_UnpackTuple(args, "asctime", 0, 1, &tup))
623 return NULL;
624 if (tup == NULL) {
625 time_t tt = time(NULL);
626 buf = *localtime(&tt);
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000627 } else if (!gettmarg(tup, &buf) || !checktm(&buf))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000628 return NULL;
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000629 return _asctime(&buf);
Guido van Rossum9e90a671993-06-24 11:10:19 +0000630}
631
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000632PyDoc_STRVAR(asctime_doc,
Thomas Woutersfe385252001-01-19 23:16:56 +0000633"asctime([tuple]) -> string\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000634\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000635Convert a time tuple to a string, e.g. 'Sat Jun 06 16:26:11 1998'.\n\
636When the time tuple is not present, current time as returned by localtime()\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000637is used.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000638
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000639static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000640time_ctime(PyObject *self, PyObject *args)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000641{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000642 PyObject *ot = NULL;
643 time_t tt;
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000644 struct tm *timeptr;
Guido van Rossum10b164a2001-09-25 13:59:01 +0000645
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000646 if (!PyArg_UnpackTuple(args, "ctime", 0, 1, &ot))
647 return NULL;
648 if (ot == NULL || ot == Py_None)
649 tt = time(NULL);
650 else {
651 double dt = PyFloat_AsDouble(ot);
652 if (PyErr_Occurred())
653 return NULL;
654 tt = _PyTime_DoubleToTimet(dt);
655 if (tt == (time_t)-1 && PyErr_Occurred())
656 return NULL;
657 }
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000658 timeptr = localtime(&tt);
659 if (timeptr == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000660 PyErr_SetString(PyExc_ValueError, "unconvertible time");
Alexander Belopolsky5da468f2011-01-04 17:15:52 +0000661 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000662 }
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000663 return _asctime(timeptr);
Guido van Rossum9e90a671993-06-24 11:10:19 +0000664}
665
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000666PyDoc_STRVAR(ctime_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000667"ctime(seconds) -> string\n\
668\n\
669Convert a time in seconds since the Epoch to a string in local time.\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000670This is equivalent to asctime(localtime(seconds)). When the time tuple is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000671not present, current time as returned by localtime() is used.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000672
Guido van Rossum60cd8131998-03-06 17:16:21 +0000673#ifdef HAVE_MKTIME
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000674static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000675time_mktime(PyObject *self, PyObject *tup)
Guido van Rossum234f9421993-06-17 12:35:49 +0000676{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000677 struct tm buf;
678 time_t tt;
679 if (!gettmarg(tup, &buf))
680 return NULL;
Alexander Belopolskyb7d40d12011-01-11 01:21:25 +0000681 buf.tm_wday = -1; /* sentinel; original value ignored */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000682 tt = mktime(&buf);
Alexander Belopolskyb7d40d12011-01-11 01:21:25 +0000683 /* Return value of -1 does not necessarily mean an error, but tm_wday
Ezio Melotti13925002011-03-16 11:05:33 +0200684 * cannot remain set to -1 if mktime succeeded. */
Alexander Belopolskyb7d40d12011-01-11 01:21:25 +0000685 if (tt == (time_t)(-1) && buf.tm_wday == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000686 PyErr_SetString(PyExc_OverflowError,
687 "mktime argument out of range");
688 return NULL;
689 }
690 return PyFloat_FromDouble((double)tt);
Guido van Rossum234f9421993-06-17 12:35:49 +0000691}
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000692
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000693PyDoc_STRVAR(mktime_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000694"mktime(tuple) -> floating point number\n\
695\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000696Convert a time tuple in local time to seconds since the Epoch.");
Guido van Rossum60cd8131998-03-06 17:16:21 +0000697#endif /* HAVE_MKTIME */
Guido van Rossum234f9421993-06-17 12:35:49 +0000698
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000699#ifdef HAVE_WORKING_TZSET
Martin v. Löwis1a214512008-06-11 05:26:20 +0000700static void PyInit_timezone(PyObject *module);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000701
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000702static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000703time_tzset(PyObject *self, PyObject *unused)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000704{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000705 PyObject* m;
Fred Drake9bb74322002-04-01 14:49:59 +0000706
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000707 m = PyImport_ImportModuleNoBlock("time");
708 if (m == NULL) {
709 return NULL;
710 }
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000711
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000712 tzset();
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000713
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000714 /* Reset timezone, altzone, daylight and tzname */
715 PyInit_timezone(m);
716 Py_DECREF(m);
Tim Peters1b6f7a92004-06-20 02:50:16 +0000717
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000718 Py_INCREF(Py_None);
719 return Py_None;
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000720}
721
722PyDoc_STRVAR(tzset_doc,
R. David Murray4d55bf92010-12-14 00:55:46 +0000723"tzset()\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000724\n\
725Initialize, or reinitialize, the local timezone to the value stored in\n\
726os.environ['TZ']. The TZ environment variable should be specified in\n\
Neal Norwitzdc8e1942004-07-20 22:34:37 +0000727standard Unix timezone format as documented in the tzset man page\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000728(eg. 'US/Eastern', 'Europe/Amsterdam'). Unknown timezones will silently\n\
729fall back to UTC. If the TZ environment variable is not set, the local\n\
730timezone is set to the systems best guess of wallclock time.\n\
731Changing the TZ environment variable without calling tzset *may* change\n\
732the local timezone used by methods such as localtime, but this behaviour\n\
733should not be relied on.");
734#endif /* HAVE_WORKING_TZSET */
735
Victor Stinnerb94b2662012-01-18 01:50:21 +0100736static PyObject *
737time_wallclock(PyObject *self, PyObject *unused)
738{
739#if defined(MS_WINDOWS) && !defined(__BORLANDC__)
740 return time_clock(self, NULL);
741#elif defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_MONOTONIC)
742 static int clk_index = 0;
743 clockid_t clk_ids[] = {
744#ifdef CLOCK_MONOTONIC_RAW
745 CLOCK_MONOTONIC_RAW,
746#endif
747 CLOCK_MONOTONIC
748#ifdef CLOCK_REALTIME
749 /* On Linux, CLOCK_REALTIME uses the same clock than gettimeofday(),
750 but clock_gettime() has a nanosecond resolution. */
751 , CLOCK_REALTIME
752#endif
753 };
754 int ret;
755 struct timespec tp;
756
757 while (0 <= clk_index) {
758 clockid_t clk_id = clk_ids[clk_index];
759 ret = clock_gettime(clk_id, &tp);
760 if (ret == 0)
761 return PyFloat_FromDouble(tp.tv_sec + tp.tv_nsec * 1e-9);
762
763 clk_index++;
764 if (Py_ARRAY_LENGTH(clk_ids) <= clk_index)
765 clk_index = -1;
766 }
767 return time_time(self, NULL);
768#else
769 return time_time(self, NULL);
770#endif
771}
772
773PyDoc_STRVAR(wallclock_doc,
774"wallclock() -> float\n\
775\n\
776Return the current time in fractions of a second to the system's best\n\
777ability. Use this when the most accurate representation of wall-clock is\n\
778required, i.e. when "processor time" is inappropriate. The reference point\n\
779of the returned value is undefined so only the difference of consecutive\n\
780calls is valid.");
781
Martin v. Löwisd218dc12008-04-07 03:17:54 +0000782static void
Martin v. Löwis1a214512008-06-11 05:26:20 +0000783PyInit_timezone(PyObject *m) {
784 /* This code moved from PyInit_time wholesale to allow calling it from
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000785 time_tzset. In the future, some parts of it can be moved back
786 (for platforms that don't HAVE_WORKING_TZSET, when we know what they
787 are), and the extraneous calls to tzset(3) should be removed.
788 I haven't done this yet, as I don't want to change this code as
789 little as possible when introducing the time.tzset and time.tzsetwall
790 methods. This should simply be a method of doing the following once,
791 at the top of this function and removing the call to tzset() from
792 time_tzset():
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000793
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000794 #ifdef HAVE_TZSET
795 tzset()
796 #endif
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000797
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000798 And I'm lazy and hate C so nyer.
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000799 */
Guido van Rossum10b164a2001-09-25 13:59:01 +0000800#if defined(HAVE_TZNAME) && !defined(__GLIBC__) && !defined(__CYGWIN__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000801 PyObject *otz0, *otz1;
802 tzset();
Guido van Rossum26452411998-09-28 22:07:11 +0000803#ifdef PYOS_OS2
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000804 PyModule_AddIntConstant(m, "timezone", _timezone);
Guido van Rossum26452411998-09-28 22:07:11 +0000805#else /* !PYOS_OS2 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000806 PyModule_AddIntConstant(m, "timezone", timezone);
Guido van Rossum26452411998-09-28 22:07:11 +0000807#endif /* PYOS_OS2 */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000808#ifdef HAVE_ALTZONE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000809 PyModule_AddIntConstant(m, "altzone", altzone);
Guido van Rossumb6775db1994-08-01 11:34:53 +0000810#else
Guido van Rossum26452411998-09-28 22:07:11 +0000811#ifdef PYOS_OS2
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000812 PyModule_AddIntConstant(m, "altzone", _timezone-3600);
Guido van Rossum26452411998-09-28 22:07:11 +0000813#else /* !PYOS_OS2 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000814 PyModule_AddIntConstant(m, "altzone", timezone-3600);
Guido van Rossum26452411998-09-28 22:07:11 +0000815#endif /* PYOS_OS2 */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000816#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000817 PyModule_AddIntConstant(m, "daylight", daylight);
Victor Stinner1b579672011-12-17 05:47:23 +0100818 otz0 = PyUnicode_DecodeLocale(tzname[0], "surrogateescape");
819 otz1 = PyUnicode_DecodeLocale(tzname[1], "surrogateescape");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000820 PyModule_AddObject(m, "tzname", Py_BuildValue("(NN)", otz0, otz1));
Guido van Rossum10b164a2001-09-25 13:59:01 +0000821#else /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/
Martin v. Löwis60a5d722002-10-16 20:28:25 +0000822#ifdef HAVE_STRUCT_TM_TM_ZONE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000823 {
Guido van Rossum234f9421993-06-17 12:35:49 +0000824#define YEAR ((time_t)((365 * 24 + 6) * 3600))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000825 time_t t;
826 struct tm *p;
827 long janzone, julyzone;
828 char janname[10], julyname[10];
829 t = (time((time_t *)0) / YEAR) * YEAR;
830 p = localtime(&t);
831 janzone = -p->tm_gmtoff;
832 strncpy(janname, p->tm_zone ? p->tm_zone : " ", 9);
833 janname[9] = '\0';
834 t += YEAR/2;
835 p = localtime(&t);
836 julyzone = -p->tm_gmtoff;
837 strncpy(julyname, p->tm_zone ? p->tm_zone : " ", 9);
838 julyname[9] = '\0';
Guido van Rossum10b164a2001-09-25 13:59:01 +0000839
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000840 if( janzone < julyzone ) {
841 /* DST is reversed in the southern hemisphere */
842 PyModule_AddIntConstant(m, "timezone", julyzone);
843 PyModule_AddIntConstant(m, "altzone", janzone);
844 PyModule_AddIntConstant(m, "daylight",
845 janzone != julyzone);
846 PyModule_AddObject(m, "tzname",
847 Py_BuildValue("(zz)",
848 julyname, janname));
849 } else {
850 PyModule_AddIntConstant(m, "timezone", janzone);
851 PyModule_AddIntConstant(m, "altzone", julyzone);
852 PyModule_AddIntConstant(m, "daylight",
853 janzone != julyzone);
854 PyModule_AddObject(m, "tzname",
855 Py_BuildValue("(zz)",
856 janname, julyname));
857 }
858 }
Guido van Rossume6a4b7b1997-10-08 15:27:56 +0000859#else
Martin v. Löwis60a5d722002-10-16 20:28:25 +0000860#endif /* HAVE_STRUCT_TM_TM_ZONE */
Tim Peters26ae7cd2001-03-20 03:26:49 +0000861#ifdef __CYGWIN__
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000862 tzset();
863 PyModule_AddIntConstant(m, "timezone", _timezone);
864 PyModule_AddIntConstant(m, "altzone", _timezone-3600);
865 PyModule_AddIntConstant(m, "daylight", _daylight);
866 PyModule_AddObject(m, "tzname",
867 Py_BuildValue("(zz)", _tzname[0], _tzname[1]));
Tim Peters26ae7cd2001-03-20 03:26:49 +0000868#endif /* __CYGWIN__ */
Guido van Rossum10b164a2001-09-25 13:59:01 +0000869#endif /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/
Victor Stinnere0be4232011-10-25 13:06:09 +0200870
871#if defined(HAVE_CLOCK_GETTIME) || defined(HAVE_CLOCK_GETRES)
872#ifdef CLOCK_REALTIME
873 PyModule_AddIntMacro(m, CLOCK_REALTIME);
874#endif
875#ifdef CLOCK_MONOTONIC
876 PyModule_AddIntMacro(m, CLOCK_MONOTONIC);
877#endif
878#ifdef CLOCK_MONOTONIC_RAW
879 PyModule_AddIntMacro(m, CLOCK_MONOTONIC_RAW);
880#endif
881#ifdef CLOCK_PROCESS_CPUTIME_ID
882 PyModule_AddIntMacro(m, CLOCK_PROCESS_CPUTIME_ID);
883#endif
884#ifdef CLOCK_THREAD_CPUTIME_ID
885 PyModule_AddIntMacro(m, CLOCK_THREAD_CPUTIME_ID);
886#endif
887#endif /* HAVE_CLOCK_GETTIME */
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000888}
889
890
891static PyMethodDef time_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000892 {"time", time_time, METH_NOARGS, time_doc},
Victor Stinner9122fdd2011-07-04 13:55:40 +0200893#if (defined(MS_WINDOWS) && !defined(__BORLANDC__)) || defined(HAVE_CLOCK)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000894 {"clock", time_clock, METH_NOARGS, clock_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000895#endif
Victor Stinnere0be4232011-10-25 13:06:09 +0200896#ifdef HAVE_CLOCK_GETTIME
897 {"clock_gettime", time_clock_gettime, METH_VARARGS, clock_gettime_doc},
898#endif
899#ifdef HAVE_CLOCK_GETRES
900 {"clock_getres", time_clock_getres, METH_VARARGS, clock_getres_doc},
901#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000902 {"sleep", time_sleep, METH_VARARGS, sleep_doc},
903 {"gmtime", time_gmtime, METH_VARARGS, gmtime_doc},
904 {"localtime", time_localtime, METH_VARARGS, localtime_doc},
905 {"asctime", time_asctime, METH_VARARGS, asctime_doc},
906 {"ctime", time_ctime, METH_VARARGS, ctime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000907#ifdef HAVE_MKTIME
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000908 {"mktime", time_mktime, METH_O, mktime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000909#endif
910#ifdef HAVE_STRFTIME
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000911 {"strftime", time_strftime, METH_VARARGS, strftime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000912#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000913 {"strptime", time_strptime, METH_VARARGS, strptime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000914#ifdef HAVE_WORKING_TZSET
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000915 {"tzset", time_tzset, METH_NOARGS, tzset_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000916#endif
Victor Stinnerb94b2662012-01-18 01:50:21 +0100917 {"wallclock", time_wallclock, METH_NOARGS, wallclock_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000918 {NULL, NULL} /* sentinel */
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000919};
920
921
922PyDoc_STRVAR(module_doc,
923"This module provides various functions to manipulate time values.\n\
924\n\
925There are two standard representations of time. One is the number\n\
926of seconds since the Epoch, in UTC (a.k.a. GMT). It may be an integer\n\
927or a floating point number (to represent fractions of seconds).\n\
928The Epoch is system-defined; on Unix, it is generally January 1st, 1970.\n\
929The actual value can be retrieved by calling gmtime(0).\n\
930\n\
931The other representation is a tuple of 9 integers giving local time.\n\
932The tuple items are:\n\
Alexander Belopolsky03163ac2011-05-02 12:20:52 -0400933 year (including century, e.g. 1998)\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000934 month (1-12)\n\
935 day (1-31)\n\
936 hours (0-23)\n\
937 minutes (0-59)\n\
938 seconds (0-59)\n\
939 weekday (0-6, Monday is 0)\n\
940 Julian day (day in the year, 1-366)\n\
941 DST (Daylight Savings Time) flag (-1, 0 or 1)\n\
942If the DST flag is 0, the time is given in the regular time zone;\n\
943if it is 1, the time is given in the DST time zone;\n\
944if it is -1, mktime() should guess based on the date and time.\n\
945\n\
946Variables:\n\
947\n\
948timezone -- difference in seconds between UTC and local standard time\n\
949altzone -- difference in seconds between UTC and local DST time\n\
950daylight -- whether local time should reflect DST\n\
951tzname -- tuple of (standard time zone name, DST time zone name)\n\
952\n\
953Functions:\n\
954\n\
955time() -- return current time in seconds since the Epoch as a float\n\
956clock() -- return CPU time since process start as a float\n\
957sleep() -- delay for a number of seconds given as a float\n\
958gmtime() -- convert seconds since Epoch to UTC tuple\n\
959localtime() -- convert seconds since Epoch to local time tuple\n\
960asctime() -- convert time tuple to string\n\
961ctime() -- convert time in seconds to string\n\
962mktime() -- convert local time tuple to seconds since Epoch\n\
963strftime() -- convert time tuple to string according to format specification\n\
964strptime() -- parse string to time tuple according to format specification\n\
965tzset() -- change the local timezone");
966
967
Martin v. Löwis1a214512008-06-11 05:26:20 +0000968
969static struct PyModuleDef timemodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000970 PyModuleDef_HEAD_INIT,
971 "time",
972 module_doc,
973 -1,
974 time_methods,
975 NULL,
976 NULL,
977 NULL,
978 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +0000979};
980
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000981PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +0000982PyInit_time(void)
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000983{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000984 PyObject *m;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000985 m = PyModule_Create(&timemodule);
986 if (m == NULL)
987 return NULL;
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000988
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000989 /* Set, or reset, module variables like time.timezone */
990 PyInit_timezone(m);
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000991
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000992 if (!initialized) {
993 PyStructSequence_InitType(&StructTimeType,
994 &struct_time_type_desc);
995 }
996 Py_INCREF(&StructTimeType);
997 PyModule_AddObject(m, "struct_time", (PyObject*) &StructTimeType);
998 initialized = 1;
999 return m;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001000}
1001
Guido van Rossumb6775db1994-08-01 11:34:53 +00001002static double
Thomas Woutersf3f33dc2000-07-21 06:00:07 +00001003floattime(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001004{
Alexander Belopolsky6fc4ade2010-08-05 17:34:27 +00001005 _PyTime_timeval t;
1006 _PyTime_gettimeofday(&t);
1007 return (double)t.tv_sec + t.tv_usec*0.000001;
Guido van Rossum426035c1991-02-19 12:27:35 +00001008}
1009
Guido van Rossumb6775db1994-08-01 11:34:53 +00001010
1011/* Implement floatsleep() for various platforms.
1012 When interrupted (or when another error occurs), return -1 and
1013 set an exception; else return 0. */
1014
1015static int
Guido van Rossuma320fd31995-03-09 12:14:15 +00001016floatsleep(double secs)
Guido van Rossum426035c1991-02-19 12:27:35 +00001017{
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001018/* XXX Should test for MS_WINDOWS first! */
Skip Montanaroeb33e5a2007-08-17 12:57:41 +00001019#if defined(HAVE_SELECT) && !defined(__EMX__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001020 struct timeval t;
1021 double frac;
Victor Stinner48b1ce52011-07-01 13:50:09 +02001022 int err;
1023
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001024 frac = fmod(secs, 1.0);
1025 secs = floor(secs);
1026 t.tv_sec = (long)secs;
1027 t.tv_usec = (long)(frac*1000000.0);
1028 Py_BEGIN_ALLOW_THREADS
Victor Stinner48b1ce52011-07-01 13:50:09 +02001029 err = select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &t);
1030 Py_END_ALLOW_THREADS
1031 if (err != 0) {
Guido van Rossum09cbb011999-11-08 15:32:27 +00001032#ifdef EINTR
Victor Stinner48b1ce52011-07-01 13:50:09 +02001033 if (errno == EINTR) {
1034 if (PyErr_CheckSignals())
1035 return -1;
1036 }
1037 else
Guido van Rossum09cbb011999-11-08 15:32:27 +00001038#endif
Victor Stinner48b1ce52011-07-01 13:50:09 +02001039 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001040 PyErr_SetFromErrno(PyExc_IOError);
1041 return -1;
1042 }
1043 }
Martin v. Löwis02af9642002-01-16 11:04:06 +00001044#elif defined(__WATCOMC__) && !defined(__QNX__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001045 /* XXX Can't interrupt this sleep */
1046 Py_BEGIN_ALLOW_THREADS
1047 delay((int)(secs * 1000 + 0.5)); /* delay() uses milliseconds */
1048 Py_END_ALLOW_THREADS
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001049#elif defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001050 {
1051 double millisecs = secs * 1000.0;
1052 unsigned long ul_millis;
Tim Peters513a1cd2003-01-19 04:54:58 +00001053
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001054 if (millisecs > (double)ULONG_MAX) {
1055 PyErr_SetString(PyExc_OverflowError,
1056 "sleep length is too large");
1057 return -1;
1058 }
1059 Py_BEGIN_ALLOW_THREADS
1060 /* Allow sleep(0) to maintain win32 semantics, and as decreed
1061 * by Guido, only the main thread can be interrupted.
1062 */
1063 ul_millis = (unsigned long)millisecs;
Antoine Pitrou6dd381e2011-11-21 21:26:56 +01001064 if (ul_millis == 0 || !_PyOS_IsMainThread())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001065 Sleep(ul_millis);
1066 else {
1067 DWORD rc;
Antoine Pitrou6dd381e2011-11-21 21:26:56 +01001068 HANDLE hInterruptEvent = _PyOS_SigintEvent();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001069 ResetEvent(hInterruptEvent);
1070 rc = WaitForSingleObject(hInterruptEvent, ul_millis);
1071 if (rc == WAIT_OBJECT_0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001072 Py_BLOCK_THREADS
1073 errno = EINTR;
1074 PyErr_SetFromErrno(PyExc_IOError);
1075 return -1;
1076 }
1077 }
1078 Py_END_ALLOW_THREADS
1079 }
Martin v. Löwis02af9642002-01-16 11:04:06 +00001080#elif defined(PYOS_OS2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001081 /* This Sleep *IS* Interruptable by Exceptions */
1082 Py_BEGIN_ALLOW_THREADS
1083 if (DosSleep(secs * 1000) != NO_ERROR) {
1084 Py_BLOCK_THREADS
1085 PyErr_SetFromErrno(PyExc_IOError);
1086 return -1;
1087 }
1088 Py_END_ALLOW_THREADS
Martin v. Löwis02af9642002-01-16 11:04:06 +00001089#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001090 /* XXX Can't interrupt this sleep */
1091 Py_BEGIN_ALLOW_THREADS
1092 sleep((int)secs);
1093 Py_END_ALLOW_THREADS
Martin v. Löwis02af9642002-01-16 11:04:06 +00001094#endif
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001095
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001096 return 0;
Guido van Rossum80c9d881991-04-16 08:47:51 +00001097}