blob: 8e29e0c7b580a0303677406ef320e249b0526f46 [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
24/* helper to allow us to interrupt sleep() on Windows*/
25static HANDLE hInterruptEvent = NULL;
26static BOOL WINAPI PyCtrlHandler(DWORD dwCtrlType)
27{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000028 SetEvent(hInterruptEvent);
29 /* allow other default handlers to be called.
30 Default Python handler will setup the
31 KeyboardInterrupt exception.
32 */
33 return FALSE;
Mark Hammond975e3922002-07-16 01:29:19 +000034}
35static long main_thread;
36
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000037#if defined(__BORLANDC__)
Guido van Rossumb2fb3641996-09-07 00:47:35 +000038/* These overrides not needed for Win32 */
Guido van Rossumb6775db1994-08-01 11:34:53 +000039#define timezone _timezone
Guido van Rossumcc081121995-03-14 15:05:41 +000040#define tzname _tzname
41#define daylight _daylight
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000042#endif /* __BORLANDC__ */
Guido van Rossumcac6c721996-09-06 13:34:02 +000043#endif /* MS_WINDOWS */
Guido van Rossum7bf22de1997-12-02 20:34:19 +000044#endif /* !__WATCOMC__ || __QNX__ */
Guido van Rossum234f9421993-06-17 12:35:49 +000045
Victor Stinner9122fdd2011-07-04 13:55:40 +020046#if defined(MS_WINDOWS)
47# define TZNAME_ENCODING "mbcs"
48#else
49# define TZNAME_ENCODING "utf-8"
50#endif
Guido van Rossum3917c221997-04-02 05:35:28 +000051
Andrew MacIntyre7bf68332002-03-03 02:59:16 +000052#if defined(PYOS_OS2)
53#define INCL_DOS
54#define INCL_ERRORS
55#include <os2.h>
56#endif
57
Guido van Rossum8e9ebfd1997-11-22 21:53:48 +000058#if defined(PYCC_VACPP)
Guido van Rossum26452411998-09-28 22:07:11 +000059#include <sys/time.h>
Guido van Rossum8e9ebfd1997-11-22 21:53:48 +000060#endif
61
Guido van Rossum234f9421993-06-17 12:35:49 +000062/* Forward declarations */
Tim Petersdbd9ba62000-07-09 03:09:57 +000063static int floatsleep(double);
Thomas Woutersed77bac2000-07-24 15:26:39 +000064static double floattime(void);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000065
Barry Warsaw9a2a8a81996-12-06 23:32:14 +000066static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000067time_time(PyObject *self, PyObject *unused)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000068{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000069 double secs;
70 secs = floattime();
71 if (secs == 0.0) {
72 PyErr_SetFromErrno(PyExc_IOError);
73 return NULL;
74 }
75 return PyFloat_FromDouble(secs);
Guido van Rossumb6775db1994-08-01 11:34:53 +000076}
77
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000078PyDoc_STRVAR(time_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +000079"time() -> floating point number\n\
80\n\
81Return the current time in seconds since the Epoch.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000082Fractions of a second may be present if the system clock provides them.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +000083
Thomas Wouters477c8d52006-05-27 19:21:47 +000084#if defined(MS_WINDOWS) && !defined(__BORLANDC__)
Victor Stinner9122fdd2011-07-04 13:55:40 +020085/* Win32 has better clock replacement; we have our own version, due to Mark
86 Hammond and Tim Peters */
Guido van Rossum3917c221997-04-02 05:35:28 +000087static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000088time_clock(PyObject *self, PyObject *unused)
Guido van Rossum3917c221997-04-02 05:35:28 +000089{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000090 static LARGE_INTEGER ctrStart;
91 static double divisor = 0.0;
92 LARGE_INTEGER now;
93 double diff;
Guido van Rossum3917c221997-04-02 05:35:28 +000094
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000095 if (divisor == 0.0) {
96 LARGE_INTEGER freq;
97 QueryPerformanceCounter(&ctrStart);
98 if (!QueryPerformanceFrequency(&freq) || freq.QuadPart == 0) {
99 /* Unlikely to happen - this works on all intel
100 machines at least! Revert to clock() */
101 return PyFloat_FromDouble(((double)clock()) /
102 CLOCKS_PER_SEC);
103 }
104 divisor = (double)freq.QuadPart;
105 }
106 QueryPerformanceCounter(&now);
107 diff = (double)(now.QuadPart - ctrStart.QuadPart);
108 return PyFloat_FromDouble(diff / divisor);
Guido van Rossum3917c221997-04-02 05:35:28 +0000109}
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000110
Victor Stinner9122fdd2011-07-04 13:55:40 +0200111#elif defined(HAVE_CLOCK)
112
113#ifndef CLOCKS_PER_SEC
114#ifdef CLK_TCK
115#define CLOCKS_PER_SEC CLK_TCK
116#else
117#define CLOCKS_PER_SEC 1000000
118#endif
119#endif
120
121static PyObject *
122time_clock(PyObject *self, PyObject *unused)
123{
124 return PyFloat_FromDouble(((double)clock()) / CLOCKS_PER_SEC);
125}
126#endif /* HAVE_CLOCK */
127
Guido van Rossum3917c221997-04-02 05:35:28 +0000128
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000129#ifdef HAVE_CLOCK
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000130PyDoc_STRVAR(clock_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000131"clock() -> floating point number\n\
132\n\
133Return the CPU time or real time since the start of the process or since\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000134the first call to clock(). This has as much precision as the system\n\
135records.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000136#endif
137
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000138static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000139time_sleep(PyObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000140{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000141 double secs;
142 if (!PyArg_ParseTuple(args, "d:sleep", &secs))
143 return NULL;
144 if (floatsleep(secs) != 0)
145 return NULL;
146 Py_INCREF(Py_None);
147 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000148}
149
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000150PyDoc_STRVAR(sleep_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000151"sleep(seconds)\n\
152\n\
153Delay execution for a given number of seconds. The argument may be\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000154a floating point number for subsecond precision.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000155
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000156static PyStructSequence_Field struct_time_type_fields[] = {
Alexander Belopolsky69f3fd02010-06-05 15:04:51 +0000157 {"tm_year", "year, for example, 1993"},
158 {"tm_mon", "month of year, range [1, 12]"},
159 {"tm_mday", "day of month, range [1, 31]"},
160 {"tm_hour", "hours, range [0, 23]"},
161 {"tm_min", "minutes, range [0, 59]"},
162 {"tm_sec", "seconds, range [0, 61])"},
163 {"tm_wday", "day of week, range [0, 6], Monday is 0"},
164 {"tm_yday", "day of year, range [1, 366]"},
165 {"tm_isdst", "1 if summer time is in effect, 0 if not, and -1 if unknown"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000166 {0}
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000167};
168
169static PyStructSequence_Desc struct_time_type_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000170 "time.struct_time",
Alexander Belopolsky69f3fd02010-06-05 15:04:51 +0000171 "The time value as returned by gmtime(), localtime(), and strptime(), and\n"
172 " accepted by asctime(), mktime() and strftime(). May be considered as a\n"
173 " sequence of 9 integers.\n\n"
174 " Note that several fields' values are not the same as those defined by\n"
175 " the C language standard for struct tm. For example, the value of the\n"
176 " field tm_year is the actual year, not year - 1900. See individual\n"
177 " fields' descriptions for details.",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000178 struct_time_type_fields,
179 9,
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000180};
Tim Peters9ad4b682002-02-13 05:14:18 +0000181
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000182static int initialized;
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000183static PyTypeObject StructTimeType;
184
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000185static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000186tmtotuple(struct tm *p)
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000187{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000188 PyObject *v = PyStructSequence_New(&StructTimeType);
189 if (v == NULL)
190 return NULL;
Tim Peters9ad4b682002-02-13 05:14:18 +0000191
Christian Heimes217cfd12007-12-02 14:31:20 +0000192#define SET(i,val) PyStructSequence_SET_ITEM(v, i, PyLong_FromLong((long) val))
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000193
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000194 SET(0, p->tm_year + 1900);
195 SET(1, p->tm_mon + 1); /* Want January == 1 */
196 SET(2, p->tm_mday);
197 SET(3, p->tm_hour);
198 SET(4, p->tm_min);
199 SET(5, p->tm_sec);
200 SET(6, (p->tm_wday + 6) % 7); /* Want Monday == 0 */
201 SET(7, p->tm_yday + 1); /* Want January, 1 == 1 */
202 SET(8, p->tm_isdst);
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000203#undef SET
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000204 if (PyErr_Occurred()) {
205 Py_XDECREF(v);
206 return NULL;
207 }
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000208
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000209 return v;
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000210}
211
212static PyObject *
Brett Cannon298c3802004-06-19 20:48:43 +0000213time_convert(double when, struct tm * (*function)(const time_t *))
Guido van Rossum234f9421993-06-17 12:35:49 +0000214{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000215 struct tm *p;
216 time_t whent = _PyTime_DoubleToTimet(when);
Brett Cannon298c3802004-06-19 20:48:43 +0000217
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000218 if (whent == (time_t)-1 && PyErr_Occurred())
219 return NULL;
220 errno = 0;
221 p = function(&whent);
222 if (p == NULL) {
Guido van Rossum6e8583d1996-10-08 14:19:52 +0000223#ifdef EINVAL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000224 if (errno == 0)
225 errno = EINVAL;
Guido van Rossum6e8583d1996-10-08 14:19:52 +0000226#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000227 return PyErr_SetFromErrno(PyExc_ValueError);
228 }
229 return tmtotuple(p);
Guido van Rossum234f9421993-06-17 12:35:49 +0000230}
231
Fred Drakef901abd2004-08-03 17:58:55 +0000232/* Parse arg tuple that can contain an optional float-or-None value;
233 format needs to be "|O:name".
234 Returns non-zero on success (parallels PyArg_ParseTuple).
235*/
236static int
237parse_time_double_args(PyObject *args, char *format, double *pwhen)
238{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000239 PyObject *ot = NULL;
Fred Drakef901abd2004-08-03 17:58:55 +0000240
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000241 if (!PyArg_ParseTuple(args, format, &ot))
242 return 0;
243 if (ot == NULL || ot == Py_None)
244 *pwhen = floattime();
245 else {
246 double when = PyFloat_AsDouble(ot);
247 if (PyErr_Occurred())
248 return 0;
249 *pwhen = when;
250 }
251 return 1;
Fred Drakef901abd2004-08-03 17:58:55 +0000252}
253
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000254static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000255time_gmtime(PyObject *self, PyObject *args)
Guido van Rossum234f9421993-06-17 12:35:49 +0000256{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000257 double when;
258 if (!parse_time_double_args(args, "|O:gmtime", &when))
259 return NULL;
260 return time_convert(when, gmtime);
Guido van Rossum234f9421993-06-17 12:35:49 +0000261}
262
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000263PyDoc_STRVAR(gmtime_doc,
Christian Heimes9a371592007-12-28 14:08:13 +0000264"gmtime([seconds]) -> (tm_year, tm_mon, tm_mday, tm_hour, tm_min,\n\
Fred Drake193a3f62002-03-12 21:38:49 +0000265 tm_sec, tm_wday, tm_yday, tm_isdst)\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000266\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000267Convert seconds since the Epoch to a time tuple expressing UTC (a.k.a.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000268GMT). When 'seconds' is not passed in, convert the current time instead.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000269
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000270static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000271time_localtime(PyObject *self, PyObject *args)
Guido van Rossum234f9421993-06-17 12:35:49 +0000272{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000273 double when;
274 if (!parse_time_double_args(args, "|O:localtime", &when))
275 return NULL;
276 return time_convert(when, localtime);
Guido van Rossum234f9421993-06-17 12:35:49 +0000277}
278
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000279PyDoc_STRVAR(localtime_doc,
Christian Heimes9a371592007-12-28 14:08:13 +0000280"localtime([seconds]) -> (tm_year,tm_mon,tm_mday,tm_hour,tm_min,\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000281 tm_sec,tm_wday,tm_yday,tm_isdst)\n\
Martin v. Löwisb3cfc1d2001-12-02 12:27:43 +0000282\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000283Convert seconds since the Epoch to a time tuple expressing local time.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000284When 'seconds' is not passed in, convert the current time instead.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000285
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000286/* Convert 9-item tuple to tm structure. Return 1 on success, set
287 * an exception and return 0 on error.
288 */
Guido van Rossum9e90a671993-06-24 11:10:19 +0000289static int
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000290gettmarg(PyObject *args, struct tm *p)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000291{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000292 int y;
Guido van Rossumcfbaecc1998-08-25 14:51:12 +0000293
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000294 memset((void *) p, '\0', sizeof(struct tm));
Guido van Rossumb9081262007-08-25 03:14:09 +0000295
Alexander Belopolsky610e5442011-01-06 21:57:06 +0000296 if (!PyTuple_Check(args)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000297 PyErr_SetString(PyExc_TypeError,
298 "Tuple or struct_time argument required");
299 return 0;
300 }
Skip Montanaro41cfce92007-08-24 21:11:00 +0000301
Alexander Belopolsky610e5442011-01-06 21:57:06 +0000302 if (!PyArg_ParseTuple(args, "iiiiiiiii",
303 &y, &p->tm_mon, &p->tm_mday,
304 &p->tm_hour, &p->tm_min, &p->tm_sec,
305 &p->tm_wday, &p->tm_yday, &p->tm_isdst))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000306 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000307 p->tm_year = y - 1900;
308 p->tm_mon--;
309 p->tm_wday = (p->tm_wday + 1) % 7;
310 p->tm_yday--;
311 return 1;
Guido van Rossum9e90a671993-06-24 11:10:19 +0000312}
313
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000314/* Check values of the struct tm fields before it is passed to strftime() and
315 * asctime(). Return 1 if all values are valid, otherwise set an exception
316 * and returns 0.
317 */
Victor Stinneref128102010-10-07 01:00:52 +0000318static int
319checktm(struct tm* buf)
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000320{
Victor Stinneref128102010-10-07 01:00:52 +0000321 /* Checks added to make sure strftime() and asctime() does not crash Python by
322 indexing blindly into some array for a textual representation
323 by some bad index (fixes bug #897625 and #6608).
324
325 Also support values of zero from Python code for arguments in which
326 that is out of range by forcing that value to the lowest value that
327 is valid (fixed bug #1520914).
328
329 Valid ranges based on what is allowed in struct tm:
330
331 - tm_year: [0, max(int)] (1)
332 - tm_mon: [0, 11] (2)
333 - tm_mday: [1, 31]
334 - tm_hour: [0, 23]
335 - tm_min: [0, 59]
336 - tm_sec: [0, 60]
337 - tm_wday: [0, 6] (1)
338 - tm_yday: [0, 365] (2)
339 - tm_isdst: [-max(int), max(int)]
340
341 (1) gettmarg() handles bounds-checking.
342 (2) Python's acceptable range is one greater than the range in C,
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000343 thus need to check against automatic decrement by gettmarg().
344 */
345 if (buf->tm_mon == -1)
346 buf->tm_mon = 0;
347 else if (buf->tm_mon < 0 || buf->tm_mon > 11) {
348 PyErr_SetString(PyExc_ValueError, "month out of range");
349 return 0;
350 }
351 if (buf->tm_mday == 0)
352 buf->tm_mday = 1;
353 else if (buf->tm_mday < 0 || buf->tm_mday > 31) {
354 PyErr_SetString(PyExc_ValueError, "day of month out of range");
355 return 0;
356 }
357 if (buf->tm_hour < 0 || buf->tm_hour > 23) {
358 PyErr_SetString(PyExc_ValueError, "hour out of range");
359 return 0;
360 }
361 if (buf->tm_min < 0 || buf->tm_min > 59) {
362 PyErr_SetString(PyExc_ValueError, "minute out of range");
363 return 0;
364 }
365 if (buf->tm_sec < 0 || buf->tm_sec > 61) {
366 PyErr_SetString(PyExc_ValueError, "seconds out of range");
367 return 0;
368 }
369 /* tm_wday does not need checking of its upper-bound since taking
370 ``% 7`` in gettmarg() automatically restricts the range. */
371 if (buf->tm_wday < 0) {
372 PyErr_SetString(PyExc_ValueError, "day of week out of range");
373 return 0;
374 }
375 if (buf->tm_yday == -1)
376 buf->tm_yday = 0;
377 else if (buf->tm_yday < 0 || buf->tm_yday > 365) {
378 PyErr_SetString(PyExc_ValueError, "day of year out of range");
379 return 0;
380 }
381 return 1;
382}
383
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000384#ifdef HAVE_STRFTIME
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000385#ifdef HAVE_WCSFTIME
386#define time_char wchar_t
387#define format_time wcsftime
388#define time_strlen wcslen
389#else
390#define time_char char
391#define format_time strftime
392#define time_strlen strlen
393#endif
394
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000395static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000396time_strftime(PyObject *self, PyObject *args)
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000397{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000398 PyObject *tup = NULL;
399 struct tm buf;
400 const time_char *fmt;
Victor Stinnerb2904782010-09-29 10:34:19 +0000401#ifdef HAVE_WCSFTIME
402 wchar_t *format;
403#else
404 PyObject *format;
405#endif
Victor Stinneref128102010-10-07 01:00:52 +0000406 PyObject *format_arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000407 size_t fmtlen, buflen;
Victor Stinnerb2904782010-09-29 10:34:19 +0000408 time_char *outbuf = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000409 size_t i;
Victor Stinnerb2904782010-09-29 10:34:19 +0000410 PyObject *ret = NULL;
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000411
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000412 memset((void *) &buf, '\0', sizeof(buf));
Guido van Rossum1f41f841998-04-27 19:04:26 +0000413
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000414 /* Will always expect a unicode string to be passed as format.
415 Given that there's no str type anymore in py3k this seems safe.
416 */
Victor Stinneref128102010-10-07 01:00:52 +0000417 if (!PyArg_ParseTuple(args, "U|O:strftime", &format_arg, &tup))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000418 return NULL;
Thomas Woutersfe385252001-01-19 23:16:56 +0000419
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000420 if (tup == NULL) {
421 time_t tt = time(NULL);
422 buf = *localtime(&tt);
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000423 }
424 else if (!gettmarg(tup, &buf) || !checktm(&buf))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000425 return NULL;
Guido van Rossum10b164a2001-09-25 13:59:01 +0000426
Victor Stinner06ec45e2011-01-08 03:35:36 +0000427#if defined(_MSC_VER) || defined(sun)
Victor Stinner73ea29c2011-01-08 01:56:31 +0000428 if (buf.tm_year + 1900 < 1 || 9999 < buf.tm_year + 1900) {
Victor Stinner6f0e4f92011-03-21 02:14:53 +0100429 PyErr_SetString(PyExc_ValueError,
430 "strftime() requires year in [1; 9999]");
Alexander Belopolsky0dd06f42011-01-08 01:23:02 +0000431 return NULL;
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000432 }
Victor Stinner73ea29c2011-01-08 01:56:31 +0000433#endif
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000434
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000435 /* Normalize tm_isdst just in case someone foolishly implements %Z
436 based on the assumption that tm_isdst falls within the range of
437 [-1, 1] */
438 if (buf.tm_isdst < -1)
439 buf.tm_isdst = -1;
440 else if (buf.tm_isdst > 1)
441 buf.tm_isdst = 1;
Brett Cannond1080a32004-03-02 04:38:10 +0000442
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000443#ifdef HAVE_WCSFTIME
Victor Stinnerbeb4135b2010-10-07 01:02:42 +0000444 format = PyUnicode_AsWideCharString(format_arg, NULL);
Victor Stinnerb2904782010-09-29 10:34:19 +0000445 if (format == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000446 return NULL;
Victor Stinnerb2904782010-09-29 10:34:19 +0000447 fmt = format;
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000448#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000449 /* Convert the unicode string to an ascii one */
Victor Stinneref128102010-10-07 01:00:52 +0000450 format = PyUnicode_AsEncodedString(format_arg, TZNAME_ENCODING, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000451 if (format == NULL)
452 return NULL;
453 fmt = PyBytes_AS_STRING(format);
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000454#endif
Amaury Forgeot d'Arcb5be6d42009-03-02 23:52:57 +0000455
Hirokazu Yamamoto6b0e51a2009-06-03 05:19:18 +0000456#if defined(MS_WINDOWS) && defined(HAVE_WCSFTIME)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000457 /* check that the format string contains only valid directives */
458 for(outbuf = wcschr(fmt, L'%');
459 outbuf != NULL;
460 outbuf = wcschr(outbuf+2, L'%'))
461 {
462 if (outbuf[1]=='#')
463 ++outbuf; /* not documented by python, */
464 if (outbuf[1]=='\0' ||
Senthil Kumaran8f377a32011-04-06 12:54:06 +0800465 !wcschr(L"aAbBcdHIjmMpSUwWxXyYzZ%", outbuf[1]))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000466 {
467 PyErr_SetString(PyExc_ValueError, "Invalid format string");
468 return 0;
469 }
470 }
Amaury Forgeot d'Arcb5be6d42009-03-02 23:52:57 +0000471#endif
472
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000473 fmtlen = time_strlen(fmt);
Guido van Rossumc222ec21999-02-23 00:00:10 +0000474
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000475 /* I hate these functions that presume you know how big the output
476 * will be ahead of time...
477 */
478 for (i = 1024; ; i += i) {
479 outbuf = (time_char *)PyMem_Malloc(i*sizeof(time_char));
480 if (outbuf == NULL) {
Victor Stinnerb2904782010-09-29 10:34:19 +0000481 PyErr_NoMemory();
482 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000483 }
484 buflen = format_time(outbuf, i, fmt, &buf);
485 if (buflen > 0 || i >= 256 * fmtlen) {
486 /* If the buffer is 256 times as long as the format,
487 it's probably not failing for lack of room!
488 More likely, the format yields an empty result,
489 e.g. an empty format, or %Z when the timezone
490 is unknown. */
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000491#ifdef HAVE_WCSFTIME
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000492 ret = PyUnicode_FromWideChar(outbuf, buflen);
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000493#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000494 ret = PyUnicode_Decode(outbuf, buflen,
495 TZNAME_ENCODING, NULL);
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000496#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000497 PyMem_Free(outbuf);
Victor Stinnerb2904782010-09-29 10:34:19 +0000498 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000499 }
500 PyMem_Free(outbuf);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000501#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000502 /* VisualStudio .NET 2005 does this properly */
503 if (buflen == 0 && errno == EINVAL) {
504 PyErr_SetString(PyExc_ValueError, "Invalid format string");
Victor Stinnerb2904782010-09-29 10:34:19 +0000505 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000506 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000507#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000508 }
Victor Stinnerb2904782010-09-29 10:34:19 +0000509#ifdef HAVE_WCSFTIME
510 PyMem_Free(format);
511#else
512 Py_DECREF(format);
513#endif
514 return ret;
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000515}
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000516
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000517#undef time_char
518#undef format_time
519
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000520PyDoc_STRVAR(strftime_doc,
Thomas Woutersfe385252001-01-19 23:16:56 +0000521"strftime(format[, tuple]) -> string\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000522\n\
523Convert a time tuple to a string according to a format specification.\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000524See the library reference manual for formatting codes. When the time tuple\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000525is not present, current time as returned by localtime() is used.");
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000526#endif /* HAVE_STRFTIME */
527
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000528static PyObject *
529time_strptime(PyObject *self, PyObject *args)
530{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000531 PyObject *strptime_module = PyImport_ImportModuleNoBlock("_strptime");
532 PyObject *strptime_result;
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000533
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000534 if (!strptime_module)
535 return NULL;
536 strptime_result = PyObject_CallMethod(strptime_module,
537 "_strptime_time", "O", args);
538 Py_DECREF(strptime_module);
539 return strptime_result;
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000540}
541
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000542
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000543PyDoc_STRVAR(strptime_doc,
Brett Cannon20def8b2003-07-01 05:16:08 +0000544"strptime(string, format) -> struct_time\n\
Martin v. Löwisb3cfc1d2001-12-02 12:27:43 +0000545\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000546Parse a string to a time tuple according to a format specification.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000547See the library reference manual for formatting codes (same as strftime()).");
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000548
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000549static PyObject *
550_asctime(struct tm *timeptr)
551{
552 /* Inspired by Open Group reference implementation available at
553 * http://pubs.opengroup.org/onlinepubs/009695399/functions/asctime.html */
Victor Stinner499dfcf2011-03-21 13:26:24 +0100554 static char wday_name[7][4] = {
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000555 "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
556 };
Victor Stinner499dfcf2011-03-21 13:26:24 +0100557 static char mon_name[12][4] = {
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000558 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
559 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
560 };
Victor Stinner499dfcf2011-03-21 13:26:24 +0100561 return PyUnicode_FromFormat(
562 "%s %s%3d %.2d:%.2d:%.2d %d",
563 wday_name[timeptr->tm_wday],
564 mon_name[timeptr->tm_mon],
565 timeptr->tm_mday, timeptr->tm_hour,
566 timeptr->tm_min, timeptr->tm_sec,
567 1900 + timeptr->tm_year);
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000568}
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000569
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000570static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000571time_asctime(PyObject *self, PyObject *args)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000572{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000573 PyObject *tup = NULL;
574 struct tm buf;
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000575
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000576 if (!PyArg_UnpackTuple(args, "asctime", 0, 1, &tup))
577 return NULL;
578 if (tup == NULL) {
579 time_t tt = time(NULL);
580 buf = *localtime(&tt);
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000581 } else if (!gettmarg(tup, &buf) || !checktm(&buf))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000582 return NULL;
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000583 return _asctime(&buf);
Guido van Rossum9e90a671993-06-24 11:10:19 +0000584}
585
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000586PyDoc_STRVAR(asctime_doc,
Thomas Woutersfe385252001-01-19 23:16:56 +0000587"asctime([tuple]) -> string\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000588\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000589Convert a time tuple to a string, e.g. 'Sat Jun 06 16:26:11 1998'.\n\
590When the time tuple is not present, current time as returned by localtime()\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000591is used.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000592
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000593static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000594time_ctime(PyObject *self, PyObject *args)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000595{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000596 PyObject *ot = NULL;
597 time_t tt;
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000598 struct tm *timeptr;
Guido van Rossum10b164a2001-09-25 13:59:01 +0000599
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000600 if (!PyArg_UnpackTuple(args, "ctime", 0, 1, &ot))
601 return NULL;
602 if (ot == NULL || ot == Py_None)
603 tt = time(NULL);
604 else {
605 double dt = PyFloat_AsDouble(ot);
606 if (PyErr_Occurred())
607 return NULL;
608 tt = _PyTime_DoubleToTimet(dt);
609 if (tt == (time_t)-1 && PyErr_Occurred())
610 return NULL;
611 }
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000612 timeptr = localtime(&tt);
613 if (timeptr == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000614 PyErr_SetString(PyExc_ValueError, "unconvertible time");
Alexander Belopolsky5da468f2011-01-04 17:15:52 +0000615 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000616 }
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000617 return _asctime(timeptr);
Guido van Rossum9e90a671993-06-24 11:10:19 +0000618}
619
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000620PyDoc_STRVAR(ctime_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000621"ctime(seconds) -> string\n\
622\n\
623Convert a time in seconds since the Epoch to a string in local time.\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000624This is equivalent to asctime(localtime(seconds)). When the time tuple is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000625not present, current time as returned by localtime() is used.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000626
Guido van Rossum60cd8131998-03-06 17:16:21 +0000627#ifdef HAVE_MKTIME
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000628static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000629time_mktime(PyObject *self, PyObject *tup)
Guido van Rossum234f9421993-06-17 12:35:49 +0000630{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000631 struct tm buf;
632 time_t tt;
633 if (!gettmarg(tup, &buf))
634 return NULL;
Alexander Belopolskyb7d40d12011-01-11 01:21:25 +0000635 buf.tm_wday = -1; /* sentinel; original value ignored */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000636 tt = mktime(&buf);
Alexander Belopolskyb7d40d12011-01-11 01:21:25 +0000637 /* Return value of -1 does not necessarily mean an error, but tm_wday
Ezio Melotti13925002011-03-16 11:05:33 +0200638 * cannot remain set to -1 if mktime succeeded. */
Alexander Belopolskyb7d40d12011-01-11 01:21:25 +0000639 if (tt == (time_t)(-1) && buf.tm_wday == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000640 PyErr_SetString(PyExc_OverflowError,
641 "mktime argument out of range");
642 return NULL;
643 }
644 return PyFloat_FromDouble((double)tt);
Guido van Rossum234f9421993-06-17 12:35:49 +0000645}
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000646
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000647PyDoc_STRVAR(mktime_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000648"mktime(tuple) -> floating point number\n\
649\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000650Convert a time tuple in local time to seconds since the Epoch.");
Guido van Rossum60cd8131998-03-06 17:16:21 +0000651#endif /* HAVE_MKTIME */
Guido van Rossum234f9421993-06-17 12:35:49 +0000652
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000653#ifdef HAVE_WORKING_TZSET
Martin v. Löwis1a214512008-06-11 05:26:20 +0000654static void PyInit_timezone(PyObject *module);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000655
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000656static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000657time_tzset(PyObject *self, PyObject *unused)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000658{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000659 PyObject* m;
Fred Drake9bb74322002-04-01 14:49:59 +0000660
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000661 m = PyImport_ImportModuleNoBlock("time");
662 if (m == NULL) {
663 return NULL;
664 }
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000665
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000666 tzset();
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000667
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000668 /* Reset timezone, altzone, daylight and tzname */
669 PyInit_timezone(m);
670 Py_DECREF(m);
Tim Peters1b6f7a92004-06-20 02:50:16 +0000671
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000672 Py_INCREF(Py_None);
673 return Py_None;
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000674}
675
676PyDoc_STRVAR(tzset_doc,
R. David Murray4d55bf92010-12-14 00:55:46 +0000677"tzset()\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000678\n\
679Initialize, or reinitialize, the local timezone to the value stored in\n\
680os.environ['TZ']. The TZ environment variable should be specified in\n\
Neal Norwitzdc8e1942004-07-20 22:34:37 +0000681standard Unix timezone format as documented in the tzset man page\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000682(eg. 'US/Eastern', 'Europe/Amsterdam'). Unknown timezones will silently\n\
683fall back to UTC. If the TZ environment variable is not set, the local\n\
684timezone is set to the systems best guess of wallclock time.\n\
685Changing the TZ environment variable without calling tzset *may* change\n\
686the local timezone used by methods such as localtime, but this behaviour\n\
687should not be relied on.");
688#endif /* HAVE_WORKING_TZSET */
689
Martin v. Löwisd218dc12008-04-07 03:17:54 +0000690static void
Martin v. Löwis1a214512008-06-11 05:26:20 +0000691PyInit_timezone(PyObject *m) {
692 /* This code moved from PyInit_time wholesale to allow calling it from
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000693 time_tzset. In the future, some parts of it can be moved back
694 (for platforms that don't HAVE_WORKING_TZSET, when we know what they
695 are), and the extraneous calls to tzset(3) should be removed.
696 I haven't done this yet, as I don't want to change this code as
697 little as possible when introducing the time.tzset and time.tzsetwall
698 methods. This should simply be a method of doing the following once,
699 at the top of this function and removing the call to tzset() from
700 time_tzset():
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000701
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000702 #ifdef HAVE_TZSET
703 tzset()
704 #endif
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000705
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000706 And I'm lazy and hate C so nyer.
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000707 */
Guido van Rossum10b164a2001-09-25 13:59:01 +0000708#if defined(HAVE_TZNAME) && !defined(__GLIBC__) && !defined(__CYGWIN__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000709 PyObject *otz0, *otz1;
710 tzset();
Guido van Rossum26452411998-09-28 22:07:11 +0000711#ifdef PYOS_OS2
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000712 PyModule_AddIntConstant(m, "timezone", _timezone);
Guido van Rossum26452411998-09-28 22:07:11 +0000713#else /* !PYOS_OS2 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000714 PyModule_AddIntConstant(m, "timezone", timezone);
Guido van Rossum26452411998-09-28 22:07:11 +0000715#endif /* PYOS_OS2 */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000716#ifdef HAVE_ALTZONE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000717 PyModule_AddIntConstant(m, "altzone", altzone);
Guido van Rossumb6775db1994-08-01 11:34:53 +0000718#else
Guido van Rossum26452411998-09-28 22:07:11 +0000719#ifdef PYOS_OS2
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000720 PyModule_AddIntConstant(m, "altzone", _timezone-3600);
Guido van Rossum26452411998-09-28 22:07:11 +0000721#else /* !PYOS_OS2 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000722 PyModule_AddIntConstant(m, "altzone", timezone-3600);
Guido van Rossum26452411998-09-28 22:07:11 +0000723#endif /* PYOS_OS2 */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000724#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000725 PyModule_AddIntConstant(m, "daylight", daylight);
726 otz0 = PyUnicode_Decode(tzname[0], strlen(tzname[0]), TZNAME_ENCODING, NULL);
727 otz1 = PyUnicode_Decode(tzname[1], strlen(tzname[1]), TZNAME_ENCODING, NULL);
728 PyModule_AddObject(m, "tzname", Py_BuildValue("(NN)", otz0, otz1));
Guido van Rossum10b164a2001-09-25 13:59:01 +0000729#else /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/
Martin v. Löwis60a5d722002-10-16 20:28:25 +0000730#ifdef HAVE_STRUCT_TM_TM_ZONE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000731 {
Guido van Rossum234f9421993-06-17 12:35:49 +0000732#define YEAR ((time_t)((365 * 24 + 6) * 3600))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000733 time_t t;
734 struct tm *p;
735 long janzone, julyzone;
736 char janname[10], julyname[10];
737 t = (time((time_t *)0) / YEAR) * YEAR;
738 p = localtime(&t);
739 janzone = -p->tm_gmtoff;
740 strncpy(janname, p->tm_zone ? p->tm_zone : " ", 9);
741 janname[9] = '\0';
742 t += YEAR/2;
743 p = localtime(&t);
744 julyzone = -p->tm_gmtoff;
745 strncpy(julyname, p->tm_zone ? p->tm_zone : " ", 9);
746 julyname[9] = '\0';
Guido van Rossum10b164a2001-09-25 13:59:01 +0000747
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000748 if( janzone < julyzone ) {
749 /* DST is reversed in the southern hemisphere */
750 PyModule_AddIntConstant(m, "timezone", julyzone);
751 PyModule_AddIntConstant(m, "altzone", janzone);
752 PyModule_AddIntConstant(m, "daylight",
753 janzone != julyzone);
754 PyModule_AddObject(m, "tzname",
755 Py_BuildValue("(zz)",
756 julyname, janname));
757 } else {
758 PyModule_AddIntConstant(m, "timezone", janzone);
759 PyModule_AddIntConstant(m, "altzone", julyzone);
760 PyModule_AddIntConstant(m, "daylight",
761 janzone != julyzone);
762 PyModule_AddObject(m, "tzname",
763 Py_BuildValue("(zz)",
764 janname, julyname));
765 }
766 }
Guido van Rossume6a4b7b1997-10-08 15:27:56 +0000767#else
Martin v. Löwis60a5d722002-10-16 20:28:25 +0000768#endif /* HAVE_STRUCT_TM_TM_ZONE */
Tim Peters26ae7cd2001-03-20 03:26:49 +0000769#ifdef __CYGWIN__
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000770 tzset();
771 PyModule_AddIntConstant(m, "timezone", _timezone);
772 PyModule_AddIntConstant(m, "altzone", _timezone-3600);
773 PyModule_AddIntConstant(m, "daylight", _daylight);
774 PyModule_AddObject(m, "tzname",
775 Py_BuildValue("(zz)", _tzname[0], _tzname[1]));
Tim Peters26ae7cd2001-03-20 03:26:49 +0000776#endif /* __CYGWIN__ */
Guido van Rossum10b164a2001-09-25 13:59:01 +0000777#endif /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000778}
779
780
781static PyMethodDef time_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000782 {"time", time_time, METH_NOARGS, time_doc},
Victor Stinner9122fdd2011-07-04 13:55:40 +0200783#if (defined(MS_WINDOWS) && !defined(__BORLANDC__)) || defined(HAVE_CLOCK)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000784 {"clock", time_clock, METH_NOARGS, clock_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000785#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000786 {"sleep", time_sleep, METH_VARARGS, sleep_doc},
787 {"gmtime", time_gmtime, METH_VARARGS, gmtime_doc},
788 {"localtime", time_localtime, METH_VARARGS, localtime_doc},
789 {"asctime", time_asctime, METH_VARARGS, asctime_doc},
790 {"ctime", time_ctime, METH_VARARGS, ctime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000791#ifdef HAVE_MKTIME
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000792 {"mktime", time_mktime, METH_O, mktime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000793#endif
794#ifdef HAVE_STRFTIME
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000795 {"strftime", time_strftime, METH_VARARGS, strftime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000796#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000797 {"strptime", time_strptime, METH_VARARGS, strptime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000798#ifdef HAVE_WORKING_TZSET
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000799 {"tzset", time_tzset, METH_NOARGS, tzset_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000800#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000801 {NULL, NULL} /* sentinel */
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000802};
803
804
805PyDoc_STRVAR(module_doc,
806"This module provides various functions to manipulate time values.\n\
807\n\
808There are two standard representations of time. One is the number\n\
809of seconds since the Epoch, in UTC (a.k.a. GMT). It may be an integer\n\
810or a floating point number (to represent fractions of seconds).\n\
811The Epoch is system-defined; on Unix, it is generally January 1st, 1970.\n\
812The actual value can be retrieved by calling gmtime(0).\n\
813\n\
814The other representation is a tuple of 9 integers giving local time.\n\
815The tuple items are:\n\
Alexander Belopolsky03163ac2011-05-02 12:20:52 -0400816 year (including century, e.g. 1998)\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000817 month (1-12)\n\
818 day (1-31)\n\
819 hours (0-23)\n\
820 minutes (0-59)\n\
821 seconds (0-59)\n\
822 weekday (0-6, Monday is 0)\n\
823 Julian day (day in the year, 1-366)\n\
824 DST (Daylight Savings Time) flag (-1, 0 or 1)\n\
825If the DST flag is 0, the time is given in the regular time zone;\n\
826if it is 1, the time is given in the DST time zone;\n\
827if it is -1, mktime() should guess based on the date and time.\n\
828\n\
829Variables:\n\
830\n\
831timezone -- difference in seconds between UTC and local standard time\n\
832altzone -- difference in seconds between UTC and local DST time\n\
833daylight -- whether local time should reflect DST\n\
834tzname -- tuple of (standard time zone name, DST time zone name)\n\
835\n\
836Functions:\n\
837\n\
838time() -- return current time in seconds since the Epoch as a float\n\
839clock() -- return CPU time since process start as a float\n\
840sleep() -- delay for a number of seconds given as a float\n\
841gmtime() -- convert seconds since Epoch to UTC tuple\n\
842localtime() -- convert seconds since Epoch to local time tuple\n\
843asctime() -- convert time tuple to string\n\
844ctime() -- convert time in seconds to string\n\
845mktime() -- convert local time tuple to seconds since Epoch\n\
846strftime() -- convert time tuple to string according to format specification\n\
847strptime() -- parse string to time tuple according to format specification\n\
848tzset() -- change the local timezone");
849
850
Martin v. Löwis1a214512008-06-11 05:26:20 +0000851
852static struct PyModuleDef timemodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000853 PyModuleDef_HEAD_INIT,
854 "time",
855 module_doc,
856 -1,
857 time_methods,
858 NULL,
859 NULL,
860 NULL,
861 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +0000862};
863
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000864PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +0000865PyInit_time(void)
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000866{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000867 PyObject *m;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000868 m = PyModule_Create(&timemodule);
869 if (m == NULL)
870 return NULL;
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000871
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000872 /* Set, or reset, module variables like time.timezone */
873 PyInit_timezone(m);
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000874
Mark Hammond975e3922002-07-16 01:29:19 +0000875#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000876 /* Helper to allow interrupts for Windows.
877 If Ctrl+C event delivered while not sleeping
878 it will be ignored.
879 */
880 main_thread = PyThread_get_thread_ident();
881 hInterruptEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
882 SetConsoleCtrlHandler( PyCtrlHandler, TRUE);
Mark Hammond975e3922002-07-16 01:29:19 +0000883#endif /* MS_WINDOWS */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000884 if (!initialized) {
885 PyStructSequence_InitType(&StructTimeType,
886 &struct_time_type_desc);
887 }
888 Py_INCREF(&StructTimeType);
889 PyModule_AddObject(m, "struct_time", (PyObject*) &StructTimeType);
890 initialized = 1;
891 return m;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000892}
893
Guido van Rossumb6775db1994-08-01 11:34:53 +0000894static double
Thomas Woutersf3f33dc2000-07-21 06:00:07 +0000895floattime(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000896{
Alexander Belopolsky6fc4ade2010-08-05 17:34:27 +0000897 _PyTime_timeval t;
898 _PyTime_gettimeofday(&t);
899 return (double)t.tv_sec + t.tv_usec*0.000001;
Guido van Rossum426035c1991-02-19 12:27:35 +0000900}
901
Guido van Rossumb6775db1994-08-01 11:34:53 +0000902
903/* Implement floatsleep() for various platforms.
904 When interrupted (or when another error occurs), return -1 and
905 set an exception; else return 0. */
906
907static int
Guido van Rossuma320fd31995-03-09 12:14:15 +0000908floatsleep(double secs)
Guido van Rossum426035c1991-02-19 12:27:35 +0000909{
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000910/* XXX Should test for MS_WINDOWS first! */
Skip Montanaroeb33e5a2007-08-17 12:57:41 +0000911#if defined(HAVE_SELECT) && !defined(__EMX__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000912 struct timeval t;
913 double frac;
Victor Stinner48b1ce52011-07-01 13:50:09 +0200914 int err;
915
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000916 frac = fmod(secs, 1.0);
917 secs = floor(secs);
918 t.tv_sec = (long)secs;
919 t.tv_usec = (long)(frac*1000000.0);
920 Py_BEGIN_ALLOW_THREADS
Victor Stinner48b1ce52011-07-01 13:50:09 +0200921 err = select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &t);
922 Py_END_ALLOW_THREADS
923 if (err != 0) {
Guido van Rossum09cbb011999-11-08 15:32:27 +0000924#ifdef EINTR
Victor Stinner48b1ce52011-07-01 13:50:09 +0200925 if (errno == EINTR) {
926 if (PyErr_CheckSignals())
927 return -1;
928 }
929 else
Guido van Rossum09cbb011999-11-08 15:32:27 +0000930#endif
Victor Stinner48b1ce52011-07-01 13:50:09 +0200931 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000932 PyErr_SetFromErrno(PyExc_IOError);
933 return -1;
934 }
935 }
Martin v. Löwis02af9642002-01-16 11:04:06 +0000936#elif defined(__WATCOMC__) && !defined(__QNX__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000937 /* XXX Can't interrupt this sleep */
938 Py_BEGIN_ALLOW_THREADS
939 delay((int)(secs * 1000 + 0.5)); /* delay() uses milliseconds */
940 Py_END_ALLOW_THREADS
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000941#elif defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000942 {
943 double millisecs = secs * 1000.0;
944 unsigned long ul_millis;
Tim Peters513a1cd2003-01-19 04:54:58 +0000945
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000946 if (millisecs > (double)ULONG_MAX) {
947 PyErr_SetString(PyExc_OverflowError,
948 "sleep length is too large");
949 return -1;
950 }
951 Py_BEGIN_ALLOW_THREADS
952 /* Allow sleep(0) to maintain win32 semantics, and as decreed
953 * by Guido, only the main thread can be interrupted.
954 */
955 ul_millis = (unsigned long)millisecs;
956 if (ul_millis == 0 ||
957 main_thread != PyThread_get_thread_ident())
958 Sleep(ul_millis);
959 else {
960 DWORD rc;
961 ResetEvent(hInterruptEvent);
962 rc = WaitForSingleObject(hInterruptEvent, ul_millis);
963 if (rc == WAIT_OBJECT_0) {
964 /* Yield to make sure real Python signal
965 * handler called.
966 */
967 Sleep(1);
968 Py_BLOCK_THREADS
969 errno = EINTR;
970 PyErr_SetFromErrno(PyExc_IOError);
971 return -1;
972 }
973 }
974 Py_END_ALLOW_THREADS
975 }
Martin v. Löwis02af9642002-01-16 11:04:06 +0000976#elif defined(PYOS_OS2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000977 /* This Sleep *IS* Interruptable by Exceptions */
978 Py_BEGIN_ALLOW_THREADS
979 if (DosSleep(secs * 1000) != NO_ERROR) {
980 Py_BLOCK_THREADS
981 PyErr_SetFromErrno(PyExc_IOError);
982 return -1;
983 }
984 Py_END_ALLOW_THREADS
Martin v. Löwis02af9642002-01-16 11:04:06 +0000985#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000986 /* XXX Can't interrupt this sleep */
987 Py_BEGIN_ALLOW_THREADS
988 sleep((int)secs);
989 Py_END_ALLOW_THREADS
Martin v. Löwis02af9642002-01-16 11:04:06 +0000990#endif
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000991
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000992 return 0;
Guido van Rossum80c9d881991-04-16 08:47:51 +0000993}