blob: f7dac5b1918499f354138718c5455f9cad120e14 [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);
Antoine Pitrou2c085602012-01-18 01:41:44 +0100131 if (ret != 0) {
Victor Stinnere0be4232011-10-25 13:06:09 +0200132 PyErr_SetFromErrno(PyExc_IOError);
Antoine Pitrou2c085602012-01-18 01:41:44 +0100133 return NULL;
134 }
Victor Stinnere0be4232011-10-25 13:06:09 +0200135
136 return PyFloat_FromDouble(tp.tv_sec + tp.tv_nsec * 1e-9);
137}
138
139PyDoc_STRVAR(clock_gettime_doc,
140"clock_gettime(clk_id) -> floating point number\n\
141\n\
142Return the time of the specified clock clk_id.");
143#endif
144
145#ifdef HAVE_CLOCK_GETRES
146static PyObject *
147time_clock_getres(PyObject *self, PyObject *args)
148{
149 int ret;
150 clockid_t clk_id;
151 struct timespec tp;
152
153 if (!PyArg_ParseTuple(args, "i:clock_getres", &clk_id))
154 return NULL;
155
156 ret = clock_getres((clockid_t)clk_id, &tp);
Antoine Pitrou2c085602012-01-18 01:41:44 +0100157 if (ret != 0) {
Victor Stinnere0be4232011-10-25 13:06:09 +0200158 PyErr_SetFromErrno(PyExc_IOError);
Antoine Pitrou2c085602012-01-18 01:41:44 +0100159 return NULL;
160 }
Victor Stinnere0be4232011-10-25 13:06:09 +0200161
162 return PyFloat_FromDouble(tp.tv_sec + tp.tv_nsec * 1e-9);
163}
164
165PyDoc_STRVAR(clock_getres_doc,
166"clock_getres(clk_id) -> floating point number\n\
167\n\
168Return the resolution (precision) of the specified clock clk_id.");
169#endif
170
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000171static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000172time_sleep(PyObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000173{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000174 double secs;
175 if (!PyArg_ParseTuple(args, "d:sleep", &secs))
176 return NULL;
Victor Stinner7f53a502011-07-05 22:00:25 +0200177 if (secs < 0) {
178 PyErr_SetString(PyExc_ValueError,
179 "sleep length must be non-negative");
180 return NULL;
181 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000182 if (floatsleep(secs) != 0)
183 return NULL;
184 Py_INCREF(Py_None);
185 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000186}
187
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000188PyDoc_STRVAR(sleep_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000189"sleep(seconds)\n\
190\n\
191Delay execution for a given number of seconds. The argument may be\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000192a floating point number for subsecond precision.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000193
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000194static PyStructSequence_Field struct_time_type_fields[] = {
Alexander Belopolsky69f3fd02010-06-05 15:04:51 +0000195 {"tm_year", "year, for example, 1993"},
196 {"tm_mon", "month of year, range [1, 12]"},
197 {"tm_mday", "day of month, range [1, 31]"},
198 {"tm_hour", "hours, range [0, 23]"},
199 {"tm_min", "minutes, range [0, 59]"},
200 {"tm_sec", "seconds, range [0, 61])"},
201 {"tm_wday", "day of week, range [0, 6], Monday is 0"},
202 {"tm_yday", "day of year, range [1, 366]"},
203 {"tm_isdst", "1 if summer time is in effect, 0 if not, and -1 if unknown"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000204 {0}
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000205};
206
207static PyStructSequence_Desc struct_time_type_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000208 "time.struct_time",
Alexander Belopolsky69f3fd02010-06-05 15:04:51 +0000209 "The time value as returned by gmtime(), localtime(), and strptime(), and\n"
210 " accepted by asctime(), mktime() and strftime(). May be considered as a\n"
211 " sequence of 9 integers.\n\n"
212 " Note that several fields' values are not the same as those defined by\n"
213 " the C language standard for struct tm. For example, the value of the\n"
214 " field tm_year is the actual year, not year - 1900. See individual\n"
215 " fields' descriptions for details.",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000216 struct_time_type_fields,
217 9,
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000218};
Tim Peters9ad4b682002-02-13 05:14:18 +0000219
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000220static int initialized;
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000221static PyTypeObject StructTimeType;
222
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000223static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000224tmtotuple(struct tm *p)
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000225{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000226 PyObject *v = PyStructSequence_New(&StructTimeType);
227 if (v == NULL)
228 return NULL;
Tim Peters9ad4b682002-02-13 05:14:18 +0000229
Christian Heimes217cfd12007-12-02 14:31:20 +0000230#define SET(i,val) PyStructSequence_SET_ITEM(v, i, PyLong_FromLong((long) val))
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000231
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000232 SET(0, p->tm_year + 1900);
233 SET(1, p->tm_mon + 1); /* Want January == 1 */
234 SET(2, p->tm_mday);
235 SET(3, p->tm_hour);
236 SET(4, p->tm_min);
237 SET(5, p->tm_sec);
238 SET(6, (p->tm_wday + 6) % 7); /* Want Monday == 0 */
239 SET(7, p->tm_yday + 1); /* Want January, 1 == 1 */
240 SET(8, p->tm_isdst);
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000241#undef SET
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000242 if (PyErr_Occurred()) {
243 Py_XDECREF(v);
244 return NULL;
245 }
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000246
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000247 return v;
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000248}
249
250static PyObject *
Brett Cannon298c3802004-06-19 20:48:43 +0000251time_convert(double when, struct tm * (*function)(const time_t *))
Guido van Rossum234f9421993-06-17 12:35:49 +0000252{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000253 struct tm *p;
254 time_t whent = _PyTime_DoubleToTimet(when);
Brett Cannon298c3802004-06-19 20:48:43 +0000255
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000256 if (whent == (time_t)-1 && PyErr_Occurred())
257 return NULL;
258 errno = 0;
259 p = function(&whent);
260 if (p == NULL) {
Guido van Rossum6e8583d1996-10-08 14:19:52 +0000261#ifdef EINVAL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000262 if (errno == 0)
263 errno = EINVAL;
Guido van Rossum6e8583d1996-10-08 14:19:52 +0000264#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000265 return PyErr_SetFromErrno(PyExc_ValueError);
266 }
267 return tmtotuple(p);
Guido van Rossum234f9421993-06-17 12:35:49 +0000268}
269
Fred Drakef901abd2004-08-03 17:58:55 +0000270/* Parse arg tuple that can contain an optional float-or-None value;
271 format needs to be "|O:name".
272 Returns non-zero on success (parallels PyArg_ParseTuple).
273*/
274static int
275parse_time_double_args(PyObject *args, char *format, double *pwhen)
276{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000277 PyObject *ot = NULL;
Fred Drakef901abd2004-08-03 17:58:55 +0000278
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000279 if (!PyArg_ParseTuple(args, format, &ot))
280 return 0;
281 if (ot == NULL || ot == Py_None)
282 *pwhen = floattime();
283 else {
284 double when = PyFloat_AsDouble(ot);
285 if (PyErr_Occurred())
286 return 0;
287 *pwhen = when;
288 }
289 return 1;
Fred Drakef901abd2004-08-03 17:58:55 +0000290}
291
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000292static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000293time_gmtime(PyObject *self, PyObject *args)
Guido van Rossum234f9421993-06-17 12:35:49 +0000294{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000295 double when;
296 if (!parse_time_double_args(args, "|O:gmtime", &when))
297 return NULL;
298 return time_convert(when, gmtime);
Guido van Rossum234f9421993-06-17 12:35:49 +0000299}
300
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000301PyDoc_STRVAR(gmtime_doc,
Christian Heimes9a371592007-12-28 14:08:13 +0000302"gmtime([seconds]) -> (tm_year, tm_mon, tm_mday, tm_hour, tm_min,\n\
Fred Drake193a3f62002-03-12 21:38:49 +0000303 tm_sec, tm_wday, tm_yday, tm_isdst)\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000304\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000305Convert seconds since the Epoch to a time tuple expressing UTC (a.k.a.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000306GMT). When 'seconds' is not passed in, convert the current time instead.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000307
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000308static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000309time_localtime(PyObject *self, PyObject *args)
Guido van Rossum234f9421993-06-17 12:35:49 +0000310{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000311 double when;
312 if (!parse_time_double_args(args, "|O:localtime", &when))
313 return NULL;
314 return time_convert(when, localtime);
Guido van Rossum234f9421993-06-17 12:35:49 +0000315}
316
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000317PyDoc_STRVAR(localtime_doc,
Christian Heimes9a371592007-12-28 14:08:13 +0000318"localtime([seconds]) -> (tm_year,tm_mon,tm_mday,tm_hour,tm_min,\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000319 tm_sec,tm_wday,tm_yday,tm_isdst)\n\
Martin v. Löwisb3cfc1d2001-12-02 12:27:43 +0000320\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000321Convert seconds since the Epoch to a time tuple expressing local time.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000322When 'seconds' is not passed in, convert the current time instead.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000323
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000324/* Convert 9-item tuple to tm structure. Return 1 on success, set
325 * an exception and return 0 on error.
326 */
Guido van Rossum9e90a671993-06-24 11:10:19 +0000327static int
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000328gettmarg(PyObject *args, struct tm *p)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000329{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000330 int y;
Guido van Rossumcfbaecc1998-08-25 14:51:12 +0000331
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000332 memset((void *) p, '\0', sizeof(struct tm));
Guido van Rossumb9081262007-08-25 03:14:09 +0000333
Alexander Belopolsky610e5442011-01-06 21:57:06 +0000334 if (!PyTuple_Check(args)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000335 PyErr_SetString(PyExc_TypeError,
336 "Tuple or struct_time argument required");
337 return 0;
338 }
Skip Montanaro41cfce92007-08-24 21:11:00 +0000339
Alexander Belopolsky610e5442011-01-06 21:57:06 +0000340 if (!PyArg_ParseTuple(args, "iiiiiiiii",
341 &y, &p->tm_mon, &p->tm_mday,
342 &p->tm_hour, &p->tm_min, &p->tm_sec,
343 &p->tm_wday, &p->tm_yday, &p->tm_isdst))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000344 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000345 p->tm_year = y - 1900;
346 p->tm_mon--;
347 p->tm_wday = (p->tm_wday + 1) % 7;
348 p->tm_yday--;
349 return 1;
Guido van Rossum9e90a671993-06-24 11:10:19 +0000350}
351
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000352/* Check values of the struct tm fields before it is passed to strftime() and
353 * asctime(). Return 1 if all values are valid, otherwise set an exception
354 * and returns 0.
355 */
Victor Stinneref128102010-10-07 01:00:52 +0000356static int
357checktm(struct tm* buf)
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000358{
Victor Stinneref128102010-10-07 01:00:52 +0000359 /* Checks added to make sure strftime() and asctime() does not crash Python by
360 indexing blindly into some array for a textual representation
361 by some bad index (fixes bug #897625 and #6608).
362
363 Also support values of zero from Python code for arguments in which
364 that is out of range by forcing that value to the lowest value that
365 is valid (fixed bug #1520914).
366
367 Valid ranges based on what is allowed in struct tm:
368
369 - tm_year: [0, max(int)] (1)
370 - tm_mon: [0, 11] (2)
371 - tm_mday: [1, 31]
372 - tm_hour: [0, 23]
373 - tm_min: [0, 59]
374 - tm_sec: [0, 60]
375 - tm_wday: [0, 6] (1)
376 - tm_yday: [0, 365] (2)
377 - tm_isdst: [-max(int), max(int)]
378
379 (1) gettmarg() handles bounds-checking.
380 (2) Python's acceptable range is one greater than the range in C,
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000381 thus need to check against automatic decrement by gettmarg().
382 */
383 if (buf->tm_mon == -1)
384 buf->tm_mon = 0;
385 else if (buf->tm_mon < 0 || buf->tm_mon > 11) {
386 PyErr_SetString(PyExc_ValueError, "month out of range");
387 return 0;
388 }
389 if (buf->tm_mday == 0)
390 buf->tm_mday = 1;
391 else if (buf->tm_mday < 0 || buf->tm_mday > 31) {
392 PyErr_SetString(PyExc_ValueError, "day of month out of range");
393 return 0;
394 }
395 if (buf->tm_hour < 0 || buf->tm_hour > 23) {
396 PyErr_SetString(PyExc_ValueError, "hour out of range");
397 return 0;
398 }
399 if (buf->tm_min < 0 || buf->tm_min > 59) {
400 PyErr_SetString(PyExc_ValueError, "minute out of range");
401 return 0;
402 }
403 if (buf->tm_sec < 0 || buf->tm_sec > 61) {
404 PyErr_SetString(PyExc_ValueError, "seconds out of range");
405 return 0;
406 }
407 /* tm_wday does not need checking of its upper-bound since taking
408 ``% 7`` in gettmarg() automatically restricts the range. */
409 if (buf->tm_wday < 0) {
410 PyErr_SetString(PyExc_ValueError, "day of week out of range");
411 return 0;
412 }
413 if (buf->tm_yday == -1)
414 buf->tm_yday = 0;
415 else if (buf->tm_yday < 0 || buf->tm_yday > 365) {
416 PyErr_SetString(PyExc_ValueError, "day of year out of range");
417 return 0;
418 }
419 return 1;
420}
421
Victor Stinnerc1f32ca2011-10-14 02:36:13 +0200422#ifdef MS_WINDOWS
423 /* wcsftime() doesn't format correctly time zones, see issue #10653 */
424# undef HAVE_WCSFTIME
425#endif
426
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000427#ifdef HAVE_STRFTIME
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000428#ifdef HAVE_WCSFTIME
429#define time_char wchar_t
430#define format_time wcsftime
431#define time_strlen wcslen
432#else
433#define time_char char
434#define format_time strftime
435#define time_strlen strlen
436#endif
437
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000438static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000439time_strftime(PyObject *self, PyObject *args)
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000440{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000441 PyObject *tup = NULL;
442 struct tm buf;
443 const time_char *fmt;
Victor Stinnerb2904782010-09-29 10:34:19 +0000444#ifdef HAVE_WCSFTIME
445 wchar_t *format;
446#else
447 PyObject *format;
448#endif
Victor Stinneref128102010-10-07 01:00:52 +0000449 PyObject *format_arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000450 size_t fmtlen, buflen;
Victor Stinnerb2904782010-09-29 10:34:19 +0000451 time_char *outbuf = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000452 size_t i;
Victor Stinnerb2904782010-09-29 10:34:19 +0000453 PyObject *ret = NULL;
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000454
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000455 memset((void *) &buf, '\0', sizeof(buf));
Guido van Rossum1f41f841998-04-27 19:04:26 +0000456
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000457 /* Will always expect a unicode string to be passed as format.
458 Given that there's no str type anymore in py3k this seems safe.
459 */
Victor Stinneref128102010-10-07 01:00:52 +0000460 if (!PyArg_ParseTuple(args, "U|O:strftime", &format_arg, &tup))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000461 return NULL;
Thomas Woutersfe385252001-01-19 23:16:56 +0000462
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000463 if (tup == NULL) {
464 time_t tt = time(NULL);
465 buf = *localtime(&tt);
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000466 }
467 else if (!gettmarg(tup, &buf) || !checktm(&buf))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000468 return NULL;
Guido van Rossum10b164a2001-09-25 13:59:01 +0000469
Victor Stinner06ec45e2011-01-08 03:35:36 +0000470#if defined(_MSC_VER) || defined(sun)
Victor Stinner73ea29c2011-01-08 01:56:31 +0000471 if (buf.tm_year + 1900 < 1 || 9999 < buf.tm_year + 1900) {
Victor Stinner6f0e4f92011-03-21 02:14:53 +0100472 PyErr_SetString(PyExc_ValueError,
473 "strftime() requires year in [1; 9999]");
Alexander Belopolsky0dd06f42011-01-08 01:23:02 +0000474 return NULL;
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000475 }
Victor Stinner73ea29c2011-01-08 01:56:31 +0000476#endif
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000477
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000478 /* Normalize tm_isdst just in case someone foolishly implements %Z
479 based on the assumption that tm_isdst falls within the range of
480 [-1, 1] */
481 if (buf.tm_isdst < -1)
482 buf.tm_isdst = -1;
483 else if (buf.tm_isdst > 1)
484 buf.tm_isdst = 1;
Brett Cannond1080a32004-03-02 04:38:10 +0000485
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000486#ifdef HAVE_WCSFTIME
Victor Stinnerbeb4135b2010-10-07 01:02:42 +0000487 format = PyUnicode_AsWideCharString(format_arg, NULL);
Victor Stinnerb2904782010-09-29 10:34:19 +0000488 if (format == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000489 return NULL;
Victor Stinnerb2904782010-09-29 10:34:19 +0000490 fmt = format;
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000491#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000492 /* Convert the unicode string to an ascii one */
Victor Stinner1b579672011-12-17 05:47:23 +0100493 format = PyUnicode_EncodeLocale(format_arg, "surrogateescape");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000494 if (format == NULL)
495 return NULL;
496 fmt = PyBytes_AS_STRING(format);
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000497#endif
Amaury Forgeot d'Arcb5be6d42009-03-02 23:52:57 +0000498
Victor Stinner5a3ff792011-10-16 19:08:23 +0200499#if defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000500 /* check that the format string contains only valid directives */
Victor Stinner5a3ff792011-10-16 19:08:23 +0200501 for(outbuf = strchr(fmt, '%');
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000502 outbuf != NULL;
Victor Stinner5a3ff792011-10-16 19:08:23 +0200503 outbuf = strchr(outbuf+2, '%'))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000504 {
505 if (outbuf[1]=='#')
506 ++outbuf; /* not documented by python, */
507 if (outbuf[1]=='\0' ||
Victor Stinner5a3ff792011-10-16 19:08:23 +0200508 !strchr("aAbBcdHIjmMpSUwWxXyYzZ%", outbuf[1]))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000509 {
510 PyErr_SetString(PyExc_ValueError, "Invalid format string");
511 return 0;
512 }
513 }
Amaury Forgeot d'Arcb5be6d42009-03-02 23:52:57 +0000514#endif
515
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000516 fmtlen = time_strlen(fmt);
Guido van Rossumc222ec21999-02-23 00:00:10 +0000517
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000518 /* I hate these functions that presume you know how big the output
519 * will be ahead of time...
520 */
521 for (i = 1024; ; i += i) {
Victor Stinner136ea492011-12-17 22:37:18 +0100522#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100523 int err;
Victor Stinner136ea492011-12-17 22:37:18 +0100524#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000525 outbuf = (time_char *)PyMem_Malloc(i*sizeof(time_char));
526 if (outbuf == NULL) {
Victor Stinnerb2904782010-09-29 10:34:19 +0000527 PyErr_NoMemory();
528 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000529 }
530 buflen = format_time(outbuf, i, fmt, &buf);
Victor Stinner136ea492011-12-17 22:37:18 +0100531#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100532 err = errno;
Victor Stinner136ea492011-12-17 22:37:18 +0100533#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000534 if (buflen > 0 || i >= 256 * fmtlen) {
535 /* If the buffer is 256 times as long as the format,
536 it's probably not failing for lack of room!
537 More likely, the format yields an empty result,
538 e.g. an empty format, or %Z when the timezone
539 is unknown. */
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000540#ifdef HAVE_WCSFTIME
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000541 ret = PyUnicode_FromWideChar(outbuf, buflen);
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000542#else
Victor Stinner1b579672011-12-17 05:47:23 +0100543 ret = PyUnicode_DecodeLocaleAndSize(outbuf, buflen,
544 "surrogateescape");
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000545#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000546 PyMem_Free(outbuf);
Victor Stinnerb2904782010-09-29 10:34:19 +0000547 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000548 }
549 PyMem_Free(outbuf);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000550#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000551 /* VisualStudio .NET 2005 does this properly */
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100552 if (buflen == 0 && err == EINVAL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000553 PyErr_SetString(PyExc_ValueError, "Invalid format string");
Victor Stinnerb2904782010-09-29 10:34:19 +0000554 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000555 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000556#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000557 }
Victor Stinnerb2904782010-09-29 10:34:19 +0000558#ifdef HAVE_WCSFTIME
559 PyMem_Free(format);
560#else
561 Py_DECREF(format);
562#endif
563 return ret;
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000564}
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000565
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000566#undef time_char
567#undef format_time
568
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000569PyDoc_STRVAR(strftime_doc,
Thomas Woutersfe385252001-01-19 23:16:56 +0000570"strftime(format[, tuple]) -> string\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000571\n\
572Convert a time tuple to a string according to a format specification.\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000573See the library reference manual for formatting codes. When the time tuple\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000574is not present, current time as returned by localtime() is used.");
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000575#endif /* HAVE_STRFTIME */
576
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000577static PyObject *
578time_strptime(PyObject *self, PyObject *args)
579{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000580 PyObject *strptime_module = PyImport_ImportModuleNoBlock("_strptime");
581 PyObject *strptime_result;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200582 _Py_IDENTIFIER(_strptime_time);
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000583
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000584 if (!strptime_module)
585 return NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200586 strptime_result = _PyObject_CallMethodId(strptime_module,
587 &PyId__strptime_time, "O", args);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000588 Py_DECREF(strptime_module);
589 return strptime_result;
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000590}
591
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000592
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000593PyDoc_STRVAR(strptime_doc,
Brett Cannon20def8b2003-07-01 05:16:08 +0000594"strptime(string, format) -> struct_time\n\
Martin v. Löwisb3cfc1d2001-12-02 12:27:43 +0000595\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000596Parse a string to a time tuple according to a format specification.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000597See the library reference manual for formatting codes (same as strftime()).");
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000598
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000599static PyObject *
600_asctime(struct tm *timeptr)
601{
602 /* Inspired by Open Group reference implementation available at
603 * http://pubs.opengroup.org/onlinepubs/009695399/functions/asctime.html */
Victor Stinner499dfcf2011-03-21 13:26:24 +0100604 static char wday_name[7][4] = {
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000605 "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
606 };
Victor Stinner499dfcf2011-03-21 13:26:24 +0100607 static char mon_name[12][4] = {
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000608 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
609 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
610 };
Victor Stinner499dfcf2011-03-21 13:26:24 +0100611 return PyUnicode_FromFormat(
612 "%s %s%3d %.2d:%.2d:%.2d %d",
613 wday_name[timeptr->tm_wday],
614 mon_name[timeptr->tm_mon],
615 timeptr->tm_mday, timeptr->tm_hour,
616 timeptr->tm_min, timeptr->tm_sec,
617 1900 + timeptr->tm_year);
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000618}
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000619
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000620static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000621time_asctime(PyObject *self, PyObject *args)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000622{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000623 PyObject *tup = NULL;
624 struct tm buf;
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000625
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000626 if (!PyArg_UnpackTuple(args, "asctime", 0, 1, &tup))
627 return NULL;
628 if (tup == NULL) {
629 time_t tt = time(NULL);
630 buf = *localtime(&tt);
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000631 } else if (!gettmarg(tup, &buf) || !checktm(&buf))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000632 return NULL;
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000633 return _asctime(&buf);
Guido van Rossum9e90a671993-06-24 11:10:19 +0000634}
635
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000636PyDoc_STRVAR(asctime_doc,
Thomas Woutersfe385252001-01-19 23:16:56 +0000637"asctime([tuple]) -> string\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000638\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000639Convert a time tuple to a string, e.g. 'Sat Jun 06 16:26:11 1998'.\n\
640When the time tuple is not present, current time as returned by localtime()\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000641is used.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000642
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000643static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000644time_ctime(PyObject *self, PyObject *args)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000645{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000646 PyObject *ot = NULL;
647 time_t tt;
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000648 struct tm *timeptr;
Guido van Rossum10b164a2001-09-25 13:59:01 +0000649
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000650 if (!PyArg_UnpackTuple(args, "ctime", 0, 1, &ot))
651 return NULL;
652 if (ot == NULL || ot == Py_None)
653 tt = time(NULL);
654 else {
655 double dt = PyFloat_AsDouble(ot);
656 if (PyErr_Occurred())
657 return NULL;
658 tt = _PyTime_DoubleToTimet(dt);
659 if (tt == (time_t)-1 && PyErr_Occurred())
660 return NULL;
661 }
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000662 timeptr = localtime(&tt);
663 if (timeptr == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000664 PyErr_SetString(PyExc_ValueError, "unconvertible time");
Alexander Belopolsky5da468f2011-01-04 17:15:52 +0000665 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000666 }
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000667 return _asctime(timeptr);
Guido van Rossum9e90a671993-06-24 11:10:19 +0000668}
669
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000670PyDoc_STRVAR(ctime_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000671"ctime(seconds) -> string\n\
672\n\
673Convert a time in seconds since the Epoch to a string in local time.\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000674This is equivalent to asctime(localtime(seconds)). When the time tuple is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000675not present, current time as returned by localtime() is used.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000676
Guido van Rossum60cd8131998-03-06 17:16:21 +0000677#ifdef HAVE_MKTIME
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000678static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000679time_mktime(PyObject *self, PyObject *tup)
Guido van Rossum234f9421993-06-17 12:35:49 +0000680{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000681 struct tm buf;
682 time_t tt;
683 if (!gettmarg(tup, &buf))
684 return NULL;
Alexander Belopolskyb7d40d12011-01-11 01:21:25 +0000685 buf.tm_wday = -1; /* sentinel; original value ignored */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000686 tt = mktime(&buf);
Alexander Belopolskyb7d40d12011-01-11 01:21:25 +0000687 /* Return value of -1 does not necessarily mean an error, but tm_wday
Ezio Melotti13925002011-03-16 11:05:33 +0200688 * cannot remain set to -1 if mktime succeeded. */
Alexander Belopolskyb7d40d12011-01-11 01:21:25 +0000689 if (tt == (time_t)(-1) && buf.tm_wday == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000690 PyErr_SetString(PyExc_OverflowError,
691 "mktime argument out of range");
692 return NULL;
693 }
694 return PyFloat_FromDouble((double)tt);
Guido van Rossum234f9421993-06-17 12:35:49 +0000695}
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000696
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000697PyDoc_STRVAR(mktime_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000698"mktime(tuple) -> floating point number\n\
699\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000700Convert a time tuple in local time to seconds since the Epoch.");
Guido van Rossum60cd8131998-03-06 17:16:21 +0000701#endif /* HAVE_MKTIME */
Guido van Rossum234f9421993-06-17 12:35:49 +0000702
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000703#ifdef HAVE_WORKING_TZSET
Martin v. Löwis1a214512008-06-11 05:26:20 +0000704static void PyInit_timezone(PyObject *module);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000705
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000706static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000707time_tzset(PyObject *self, PyObject *unused)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000708{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000709 PyObject* m;
Fred Drake9bb74322002-04-01 14:49:59 +0000710
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000711 m = PyImport_ImportModuleNoBlock("time");
712 if (m == NULL) {
713 return NULL;
714 }
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000715
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000716 tzset();
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000717
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000718 /* Reset timezone, altzone, daylight and tzname */
719 PyInit_timezone(m);
720 Py_DECREF(m);
Tim Peters1b6f7a92004-06-20 02:50:16 +0000721
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000722 Py_INCREF(Py_None);
723 return Py_None;
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000724}
725
726PyDoc_STRVAR(tzset_doc,
R. David Murray4d55bf92010-12-14 00:55:46 +0000727"tzset()\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000728\n\
729Initialize, or reinitialize, the local timezone to the value stored in\n\
730os.environ['TZ']. The TZ environment variable should be specified in\n\
Neal Norwitzdc8e1942004-07-20 22:34:37 +0000731standard Unix timezone format as documented in the tzset man page\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000732(eg. 'US/Eastern', 'Europe/Amsterdam'). Unknown timezones will silently\n\
733fall back to UTC. If the TZ environment variable is not set, the local\n\
734timezone is set to the systems best guess of wallclock time.\n\
735Changing the TZ environment variable without calling tzset *may* change\n\
736the local timezone used by methods such as localtime, but this behaviour\n\
737should not be relied on.");
738#endif /* HAVE_WORKING_TZSET */
739
Victor Stinnerb94b2662012-01-18 01:50:21 +0100740static PyObject *
741time_wallclock(PyObject *self, PyObject *unused)
742{
743#if defined(MS_WINDOWS) && !defined(__BORLANDC__)
744 return time_clock(self, NULL);
745#elif defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_MONOTONIC)
746 static int clk_index = 0;
747 clockid_t clk_ids[] = {
748#ifdef CLOCK_MONOTONIC_RAW
749 CLOCK_MONOTONIC_RAW,
750#endif
751 CLOCK_MONOTONIC
752#ifdef CLOCK_REALTIME
753 /* On Linux, CLOCK_REALTIME uses the same clock than gettimeofday(),
754 but clock_gettime() has a nanosecond resolution. */
755 , CLOCK_REALTIME
756#endif
757 };
758 int ret;
759 struct timespec tp;
760
761 while (0 <= clk_index) {
762 clockid_t clk_id = clk_ids[clk_index];
763 ret = clock_gettime(clk_id, &tp);
764 if (ret == 0)
765 return PyFloat_FromDouble(tp.tv_sec + tp.tv_nsec * 1e-9);
766
767 clk_index++;
768 if (Py_ARRAY_LENGTH(clk_ids) <= clk_index)
769 clk_index = -1;
770 }
771 return time_time(self, NULL);
772#else
773 return time_time(self, NULL);
774#endif
775}
776
777PyDoc_STRVAR(wallclock_doc,
778"wallclock() -> float\n\
779\n\
780Return the current time in fractions of a second to the system's best\n\
781ability. Use this when the most accurate representation of wall-clock is\n\
Victor Stinner855889b2012-01-18 01:57:19 +0100782required, i.e. when \"processor time\" is inappropriate. The reference point\n\
Victor Stinnerb94b2662012-01-18 01:50:21 +0100783of the returned value is undefined so only the difference of consecutive\n\
784calls is valid.");
785
Martin v. Löwisd218dc12008-04-07 03:17:54 +0000786static void
Martin v. Löwis1a214512008-06-11 05:26:20 +0000787PyInit_timezone(PyObject *m) {
788 /* This code moved from PyInit_time wholesale to allow calling it from
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000789 time_tzset. In the future, some parts of it can be moved back
790 (for platforms that don't HAVE_WORKING_TZSET, when we know what they
791 are), and the extraneous calls to tzset(3) should be removed.
792 I haven't done this yet, as I don't want to change this code as
793 little as possible when introducing the time.tzset and time.tzsetwall
794 methods. This should simply be a method of doing the following once,
795 at the top of this function and removing the call to tzset() from
796 time_tzset():
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000797
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000798 #ifdef HAVE_TZSET
799 tzset()
800 #endif
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000801
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000802 And I'm lazy and hate C so nyer.
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000803 */
Guido van Rossum10b164a2001-09-25 13:59:01 +0000804#if defined(HAVE_TZNAME) && !defined(__GLIBC__) && !defined(__CYGWIN__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000805 PyObject *otz0, *otz1;
806 tzset();
Guido van Rossum26452411998-09-28 22:07:11 +0000807#ifdef PYOS_OS2
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000808 PyModule_AddIntConstant(m, "timezone", _timezone);
Guido van Rossum26452411998-09-28 22:07:11 +0000809#else /* !PYOS_OS2 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000810 PyModule_AddIntConstant(m, "timezone", timezone);
Guido van Rossum26452411998-09-28 22:07:11 +0000811#endif /* PYOS_OS2 */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000812#ifdef HAVE_ALTZONE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000813 PyModule_AddIntConstant(m, "altzone", altzone);
Guido van Rossumb6775db1994-08-01 11:34:53 +0000814#else
Guido van Rossum26452411998-09-28 22:07:11 +0000815#ifdef PYOS_OS2
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000816 PyModule_AddIntConstant(m, "altzone", _timezone-3600);
Guido van Rossum26452411998-09-28 22:07:11 +0000817#else /* !PYOS_OS2 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000818 PyModule_AddIntConstant(m, "altzone", timezone-3600);
Guido van Rossum26452411998-09-28 22:07:11 +0000819#endif /* PYOS_OS2 */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000820#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000821 PyModule_AddIntConstant(m, "daylight", daylight);
Victor Stinner1b579672011-12-17 05:47:23 +0100822 otz0 = PyUnicode_DecodeLocale(tzname[0], "surrogateescape");
823 otz1 = PyUnicode_DecodeLocale(tzname[1], "surrogateescape");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000824 PyModule_AddObject(m, "tzname", Py_BuildValue("(NN)", otz0, otz1));
Guido van Rossum10b164a2001-09-25 13:59:01 +0000825#else /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/
Martin v. Löwis60a5d722002-10-16 20:28:25 +0000826#ifdef HAVE_STRUCT_TM_TM_ZONE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000827 {
Guido van Rossum234f9421993-06-17 12:35:49 +0000828#define YEAR ((time_t)((365 * 24 + 6) * 3600))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000829 time_t t;
830 struct tm *p;
831 long janzone, julyzone;
832 char janname[10], julyname[10];
833 t = (time((time_t *)0) / YEAR) * YEAR;
834 p = localtime(&t);
835 janzone = -p->tm_gmtoff;
836 strncpy(janname, p->tm_zone ? p->tm_zone : " ", 9);
837 janname[9] = '\0';
838 t += YEAR/2;
839 p = localtime(&t);
840 julyzone = -p->tm_gmtoff;
841 strncpy(julyname, p->tm_zone ? p->tm_zone : " ", 9);
842 julyname[9] = '\0';
Guido van Rossum10b164a2001-09-25 13:59:01 +0000843
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000844 if( janzone < julyzone ) {
845 /* DST is reversed in the southern hemisphere */
846 PyModule_AddIntConstant(m, "timezone", julyzone);
847 PyModule_AddIntConstant(m, "altzone", janzone);
848 PyModule_AddIntConstant(m, "daylight",
849 janzone != julyzone);
850 PyModule_AddObject(m, "tzname",
851 Py_BuildValue("(zz)",
852 julyname, janname));
853 } else {
854 PyModule_AddIntConstant(m, "timezone", janzone);
855 PyModule_AddIntConstant(m, "altzone", julyzone);
856 PyModule_AddIntConstant(m, "daylight",
857 janzone != julyzone);
858 PyModule_AddObject(m, "tzname",
859 Py_BuildValue("(zz)",
860 janname, julyname));
861 }
862 }
Guido van Rossume6a4b7b1997-10-08 15:27:56 +0000863#else
Martin v. Löwis60a5d722002-10-16 20:28:25 +0000864#endif /* HAVE_STRUCT_TM_TM_ZONE */
Tim Peters26ae7cd2001-03-20 03:26:49 +0000865#ifdef __CYGWIN__
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000866 tzset();
867 PyModule_AddIntConstant(m, "timezone", _timezone);
868 PyModule_AddIntConstant(m, "altzone", _timezone-3600);
869 PyModule_AddIntConstant(m, "daylight", _daylight);
870 PyModule_AddObject(m, "tzname",
871 Py_BuildValue("(zz)", _tzname[0], _tzname[1]));
Tim Peters26ae7cd2001-03-20 03:26:49 +0000872#endif /* __CYGWIN__ */
Guido van Rossum10b164a2001-09-25 13:59:01 +0000873#endif /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/
Victor Stinnere0be4232011-10-25 13:06:09 +0200874
875#if defined(HAVE_CLOCK_GETTIME) || defined(HAVE_CLOCK_GETRES)
876#ifdef CLOCK_REALTIME
877 PyModule_AddIntMacro(m, CLOCK_REALTIME);
878#endif
879#ifdef CLOCK_MONOTONIC
880 PyModule_AddIntMacro(m, CLOCK_MONOTONIC);
881#endif
882#ifdef CLOCK_MONOTONIC_RAW
883 PyModule_AddIntMacro(m, CLOCK_MONOTONIC_RAW);
884#endif
885#ifdef CLOCK_PROCESS_CPUTIME_ID
886 PyModule_AddIntMacro(m, CLOCK_PROCESS_CPUTIME_ID);
887#endif
888#ifdef CLOCK_THREAD_CPUTIME_ID
889 PyModule_AddIntMacro(m, CLOCK_THREAD_CPUTIME_ID);
890#endif
891#endif /* HAVE_CLOCK_GETTIME */
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000892}
893
894
895static PyMethodDef time_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000896 {"time", time_time, METH_NOARGS, time_doc},
Victor Stinner9122fdd2011-07-04 13:55:40 +0200897#if (defined(MS_WINDOWS) && !defined(__BORLANDC__)) || defined(HAVE_CLOCK)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000898 {"clock", time_clock, METH_NOARGS, clock_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000899#endif
Victor Stinnere0be4232011-10-25 13:06:09 +0200900#ifdef HAVE_CLOCK_GETTIME
901 {"clock_gettime", time_clock_gettime, METH_VARARGS, clock_gettime_doc},
902#endif
903#ifdef HAVE_CLOCK_GETRES
904 {"clock_getres", time_clock_getres, METH_VARARGS, clock_getres_doc},
905#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000906 {"sleep", time_sleep, METH_VARARGS, sleep_doc},
907 {"gmtime", time_gmtime, METH_VARARGS, gmtime_doc},
908 {"localtime", time_localtime, METH_VARARGS, localtime_doc},
909 {"asctime", time_asctime, METH_VARARGS, asctime_doc},
910 {"ctime", time_ctime, METH_VARARGS, ctime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000911#ifdef HAVE_MKTIME
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000912 {"mktime", time_mktime, METH_O, mktime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000913#endif
914#ifdef HAVE_STRFTIME
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000915 {"strftime", time_strftime, METH_VARARGS, strftime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000916#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000917 {"strptime", time_strptime, METH_VARARGS, strptime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000918#ifdef HAVE_WORKING_TZSET
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000919 {"tzset", time_tzset, METH_NOARGS, tzset_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000920#endif
Victor Stinnerb94b2662012-01-18 01:50:21 +0100921 {"wallclock", time_wallclock, METH_NOARGS, wallclock_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000922 {NULL, NULL} /* sentinel */
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000923};
924
925
926PyDoc_STRVAR(module_doc,
927"This module provides various functions to manipulate time values.\n\
928\n\
929There are two standard representations of time. One is the number\n\
930of seconds since the Epoch, in UTC (a.k.a. GMT). It may be an integer\n\
931or a floating point number (to represent fractions of seconds).\n\
932The Epoch is system-defined; on Unix, it is generally January 1st, 1970.\n\
933The actual value can be retrieved by calling gmtime(0).\n\
934\n\
935The other representation is a tuple of 9 integers giving local time.\n\
936The tuple items are:\n\
Alexander Belopolsky03163ac2011-05-02 12:20:52 -0400937 year (including century, e.g. 1998)\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000938 month (1-12)\n\
939 day (1-31)\n\
940 hours (0-23)\n\
941 minutes (0-59)\n\
942 seconds (0-59)\n\
943 weekday (0-6, Monday is 0)\n\
944 Julian day (day in the year, 1-366)\n\
945 DST (Daylight Savings Time) flag (-1, 0 or 1)\n\
946If the DST flag is 0, the time is given in the regular time zone;\n\
947if it is 1, the time is given in the DST time zone;\n\
948if it is -1, mktime() should guess based on the date and time.\n\
949\n\
950Variables:\n\
951\n\
952timezone -- difference in seconds between UTC and local standard time\n\
953altzone -- difference in seconds between UTC and local DST time\n\
954daylight -- whether local time should reflect DST\n\
955tzname -- tuple of (standard time zone name, DST time zone name)\n\
956\n\
957Functions:\n\
958\n\
959time() -- return current time in seconds since the Epoch as a float\n\
960clock() -- return CPU time since process start as a float\n\
961sleep() -- delay for a number of seconds given as a float\n\
962gmtime() -- convert seconds since Epoch to UTC tuple\n\
963localtime() -- convert seconds since Epoch to local time tuple\n\
964asctime() -- convert time tuple to string\n\
965ctime() -- convert time in seconds to string\n\
966mktime() -- convert local time tuple to seconds since Epoch\n\
967strftime() -- convert time tuple to string according to format specification\n\
968strptime() -- parse string to time tuple according to format specification\n\
969tzset() -- change the local timezone");
970
971
Martin v. Löwis1a214512008-06-11 05:26:20 +0000972
973static struct PyModuleDef timemodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000974 PyModuleDef_HEAD_INIT,
975 "time",
976 module_doc,
977 -1,
978 time_methods,
979 NULL,
980 NULL,
981 NULL,
982 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +0000983};
984
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000985PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +0000986PyInit_time(void)
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000987{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000988 PyObject *m;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000989 m = PyModule_Create(&timemodule);
990 if (m == NULL)
991 return NULL;
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000992
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000993 /* Set, or reset, module variables like time.timezone */
994 PyInit_timezone(m);
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000995
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000996 if (!initialized) {
997 PyStructSequence_InitType(&StructTimeType,
998 &struct_time_type_desc);
999 }
1000 Py_INCREF(&StructTimeType);
1001 PyModule_AddObject(m, "struct_time", (PyObject*) &StructTimeType);
1002 initialized = 1;
1003 return m;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001004}
1005
Guido van Rossumb6775db1994-08-01 11:34:53 +00001006static double
Thomas Woutersf3f33dc2000-07-21 06:00:07 +00001007floattime(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001008{
Alexander Belopolsky6fc4ade2010-08-05 17:34:27 +00001009 _PyTime_timeval t;
1010 _PyTime_gettimeofday(&t);
1011 return (double)t.tv_sec + t.tv_usec*0.000001;
Guido van Rossum426035c1991-02-19 12:27:35 +00001012}
1013
Guido van Rossumb6775db1994-08-01 11:34:53 +00001014
1015/* Implement floatsleep() for various platforms.
1016 When interrupted (or when another error occurs), return -1 and
1017 set an exception; else return 0. */
1018
1019static int
Guido van Rossuma320fd31995-03-09 12:14:15 +00001020floatsleep(double secs)
Guido van Rossum426035c1991-02-19 12:27:35 +00001021{
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001022/* XXX Should test for MS_WINDOWS first! */
Skip Montanaroeb33e5a2007-08-17 12:57:41 +00001023#if defined(HAVE_SELECT) && !defined(__EMX__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001024 struct timeval t;
1025 double frac;
Victor Stinner48b1ce52011-07-01 13:50:09 +02001026 int err;
1027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 frac = fmod(secs, 1.0);
1029 secs = floor(secs);
1030 t.tv_sec = (long)secs;
1031 t.tv_usec = (long)(frac*1000000.0);
1032 Py_BEGIN_ALLOW_THREADS
Victor Stinner48b1ce52011-07-01 13:50:09 +02001033 err = select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &t);
1034 Py_END_ALLOW_THREADS
1035 if (err != 0) {
Guido van Rossum09cbb011999-11-08 15:32:27 +00001036#ifdef EINTR
Victor Stinner48b1ce52011-07-01 13:50:09 +02001037 if (errno == EINTR) {
1038 if (PyErr_CheckSignals())
1039 return -1;
1040 }
1041 else
Guido van Rossum09cbb011999-11-08 15:32:27 +00001042#endif
Victor Stinner48b1ce52011-07-01 13:50:09 +02001043 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001044 PyErr_SetFromErrno(PyExc_IOError);
1045 return -1;
1046 }
1047 }
Martin v. Löwis02af9642002-01-16 11:04:06 +00001048#elif defined(__WATCOMC__) && !defined(__QNX__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001049 /* XXX Can't interrupt this sleep */
1050 Py_BEGIN_ALLOW_THREADS
1051 delay((int)(secs * 1000 + 0.5)); /* delay() uses milliseconds */
1052 Py_END_ALLOW_THREADS
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001053#elif defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001054 {
1055 double millisecs = secs * 1000.0;
1056 unsigned long ul_millis;
Tim Peters513a1cd2003-01-19 04:54:58 +00001057
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001058 if (millisecs > (double)ULONG_MAX) {
1059 PyErr_SetString(PyExc_OverflowError,
1060 "sleep length is too large");
1061 return -1;
1062 }
1063 Py_BEGIN_ALLOW_THREADS
1064 /* Allow sleep(0) to maintain win32 semantics, and as decreed
1065 * by Guido, only the main thread can be interrupted.
1066 */
1067 ul_millis = (unsigned long)millisecs;
Antoine Pitrou6dd381e2011-11-21 21:26:56 +01001068 if (ul_millis == 0 || !_PyOS_IsMainThread())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001069 Sleep(ul_millis);
1070 else {
1071 DWORD rc;
Antoine Pitrou6dd381e2011-11-21 21:26:56 +01001072 HANDLE hInterruptEvent = _PyOS_SigintEvent();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001073 ResetEvent(hInterruptEvent);
1074 rc = WaitForSingleObject(hInterruptEvent, ul_millis);
1075 if (rc == WAIT_OBJECT_0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001076 Py_BLOCK_THREADS
1077 errno = EINTR;
1078 PyErr_SetFromErrno(PyExc_IOError);
1079 return -1;
1080 }
1081 }
1082 Py_END_ALLOW_THREADS
1083 }
Martin v. Löwis02af9642002-01-16 11:04:06 +00001084#elif defined(PYOS_OS2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001085 /* This Sleep *IS* Interruptable by Exceptions */
1086 Py_BEGIN_ALLOW_THREADS
1087 if (DosSleep(secs * 1000) != NO_ERROR) {
1088 Py_BLOCK_THREADS
1089 PyErr_SetFromErrno(PyExc_IOError);
1090 return -1;
1091 }
1092 Py_END_ALLOW_THREADS
Martin v. Löwis02af9642002-01-16 11:04:06 +00001093#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001094 /* XXX Can't interrupt this sleep */
1095 Py_BEGIN_ALLOW_THREADS
1096 sleep((int)secs);
1097 Py_END_ALLOW_THREADS
Martin v. Löwis02af9642002-01-16 11:04:06 +00001098#endif
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001099
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001100 return 0;
Guido van Rossum80c9d881991-04-16 08:47:51 +00001101}