blob: b7604b0c49675007f5e229806ecc4b6e41dd5c59 [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 Stinner99b95382011-07-04 14:23:54 +020046#if defined(HAVE_MBCS)
Victor Stinner9122fdd2011-07-04 13:55:40 +020047# 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;
Victor Stinner7f53a502011-07-05 22:00:25 +0200144 if (secs < 0) {
145 PyErr_SetString(PyExc_ValueError,
146 "sleep length must be non-negative");
147 return NULL;
148 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000149 if (floatsleep(secs) != 0)
150 return NULL;
151 Py_INCREF(Py_None);
152 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000153}
154
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000155PyDoc_STRVAR(sleep_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000156"sleep(seconds)\n\
157\n\
158Delay execution for a given number of seconds. The argument may be\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000159a floating point number for subsecond precision.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000160
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000161static PyStructSequence_Field struct_time_type_fields[] = {
Alexander Belopolsky69f3fd02010-06-05 15:04:51 +0000162 {"tm_year", "year, for example, 1993"},
163 {"tm_mon", "month of year, range [1, 12]"},
164 {"tm_mday", "day of month, range [1, 31]"},
165 {"tm_hour", "hours, range [0, 23]"},
166 {"tm_min", "minutes, range [0, 59]"},
167 {"tm_sec", "seconds, range [0, 61])"},
168 {"tm_wday", "day of week, range [0, 6], Monday is 0"},
169 {"tm_yday", "day of year, range [1, 366]"},
170 {"tm_isdst", "1 if summer time is in effect, 0 if not, and -1 if unknown"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000171 {0}
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000172};
173
174static PyStructSequence_Desc struct_time_type_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000175 "time.struct_time",
Alexander Belopolsky69f3fd02010-06-05 15:04:51 +0000176 "The time value as returned by gmtime(), localtime(), and strptime(), and\n"
177 " accepted by asctime(), mktime() and strftime(). May be considered as a\n"
178 " sequence of 9 integers.\n\n"
179 " Note that several fields' values are not the same as those defined by\n"
180 " the C language standard for struct tm. For example, the value of the\n"
181 " field tm_year is the actual year, not year - 1900. See individual\n"
182 " fields' descriptions for details.",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000183 struct_time_type_fields,
184 9,
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000185};
Tim Peters9ad4b682002-02-13 05:14:18 +0000186
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000187static int initialized;
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000188static PyTypeObject StructTimeType;
189
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000190static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000191tmtotuple(struct tm *p)
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000192{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000193 PyObject *v = PyStructSequence_New(&StructTimeType);
194 if (v == NULL)
195 return NULL;
Tim Peters9ad4b682002-02-13 05:14:18 +0000196
Christian Heimes217cfd12007-12-02 14:31:20 +0000197#define SET(i,val) PyStructSequence_SET_ITEM(v, i, PyLong_FromLong((long) val))
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000198
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000199 SET(0, p->tm_year + 1900);
200 SET(1, p->tm_mon + 1); /* Want January == 1 */
201 SET(2, p->tm_mday);
202 SET(3, p->tm_hour);
203 SET(4, p->tm_min);
204 SET(5, p->tm_sec);
205 SET(6, (p->tm_wday + 6) % 7); /* Want Monday == 0 */
206 SET(7, p->tm_yday + 1); /* Want January, 1 == 1 */
207 SET(8, p->tm_isdst);
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000208#undef SET
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000209 if (PyErr_Occurred()) {
210 Py_XDECREF(v);
211 return NULL;
212 }
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000213
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000214 return v;
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000215}
216
217static PyObject *
Brett Cannon298c3802004-06-19 20:48:43 +0000218time_convert(double when, struct tm * (*function)(const time_t *))
Guido van Rossum234f9421993-06-17 12:35:49 +0000219{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000220 struct tm *p;
221 time_t whent = _PyTime_DoubleToTimet(when);
Brett Cannon298c3802004-06-19 20:48:43 +0000222
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000223 if (whent == (time_t)-1 && PyErr_Occurred())
224 return NULL;
225 errno = 0;
226 p = function(&whent);
227 if (p == NULL) {
Guido van Rossum6e8583d1996-10-08 14:19:52 +0000228#ifdef EINVAL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000229 if (errno == 0)
230 errno = EINVAL;
Guido van Rossum6e8583d1996-10-08 14:19:52 +0000231#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000232 return PyErr_SetFromErrno(PyExc_ValueError);
233 }
234 return tmtotuple(p);
Guido van Rossum234f9421993-06-17 12:35:49 +0000235}
236
Fred Drakef901abd2004-08-03 17:58:55 +0000237/* Parse arg tuple that can contain an optional float-or-None value;
238 format needs to be "|O:name".
239 Returns non-zero on success (parallels PyArg_ParseTuple).
240*/
241static int
242parse_time_double_args(PyObject *args, char *format, double *pwhen)
243{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000244 PyObject *ot = NULL;
Fred Drakef901abd2004-08-03 17:58:55 +0000245
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000246 if (!PyArg_ParseTuple(args, format, &ot))
247 return 0;
248 if (ot == NULL || ot == Py_None)
249 *pwhen = floattime();
250 else {
251 double when = PyFloat_AsDouble(ot);
252 if (PyErr_Occurred())
253 return 0;
254 *pwhen = when;
255 }
256 return 1;
Fred Drakef901abd2004-08-03 17:58:55 +0000257}
258
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000259static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000260time_gmtime(PyObject *self, PyObject *args)
Guido van Rossum234f9421993-06-17 12:35:49 +0000261{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000262 double when;
263 if (!parse_time_double_args(args, "|O:gmtime", &when))
264 return NULL;
265 return time_convert(when, gmtime);
Guido van Rossum234f9421993-06-17 12:35:49 +0000266}
267
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000268PyDoc_STRVAR(gmtime_doc,
Christian Heimes9a371592007-12-28 14:08:13 +0000269"gmtime([seconds]) -> (tm_year, tm_mon, tm_mday, tm_hour, tm_min,\n\
Fred Drake193a3f62002-03-12 21:38:49 +0000270 tm_sec, tm_wday, tm_yday, tm_isdst)\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000271\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000272Convert seconds since the Epoch to a time tuple expressing UTC (a.k.a.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000273GMT). When 'seconds' is not passed in, convert the current time instead.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000274
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000275static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000276time_localtime(PyObject *self, PyObject *args)
Guido van Rossum234f9421993-06-17 12:35:49 +0000277{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000278 double when;
279 if (!parse_time_double_args(args, "|O:localtime", &when))
280 return NULL;
281 return time_convert(when, localtime);
Guido van Rossum234f9421993-06-17 12:35:49 +0000282}
283
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000284PyDoc_STRVAR(localtime_doc,
Christian Heimes9a371592007-12-28 14:08:13 +0000285"localtime([seconds]) -> (tm_year,tm_mon,tm_mday,tm_hour,tm_min,\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000286 tm_sec,tm_wday,tm_yday,tm_isdst)\n\
Martin v. Löwisb3cfc1d2001-12-02 12:27:43 +0000287\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000288Convert seconds since the Epoch to a time tuple expressing local time.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000289When 'seconds' is not passed in, convert the current time instead.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000290
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000291/* Convert 9-item tuple to tm structure. Return 1 on success, set
292 * an exception and return 0 on error.
293 */
Guido van Rossum9e90a671993-06-24 11:10:19 +0000294static int
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000295gettmarg(PyObject *args, struct tm *p)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000296{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000297 int y;
Guido van Rossumcfbaecc1998-08-25 14:51:12 +0000298
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000299 memset((void *) p, '\0', sizeof(struct tm));
Guido van Rossumb9081262007-08-25 03:14:09 +0000300
Alexander Belopolsky610e5442011-01-06 21:57:06 +0000301 if (!PyTuple_Check(args)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000302 PyErr_SetString(PyExc_TypeError,
303 "Tuple or struct_time argument required");
304 return 0;
305 }
Skip Montanaro41cfce92007-08-24 21:11:00 +0000306
Alexander Belopolsky610e5442011-01-06 21:57:06 +0000307 if (!PyArg_ParseTuple(args, "iiiiiiiii",
308 &y, &p->tm_mon, &p->tm_mday,
309 &p->tm_hour, &p->tm_min, &p->tm_sec,
310 &p->tm_wday, &p->tm_yday, &p->tm_isdst))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000311 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000312 p->tm_year = y - 1900;
313 p->tm_mon--;
314 p->tm_wday = (p->tm_wday + 1) % 7;
315 p->tm_yday--;
316 return 1;
Guido van Rossum9e90a671993-06-24 11:10:19 +0000317}
318
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000319/* Check values of the struct tm fields before it is passed to strftime() and
320 * asctime(). Return 1 if all values are valid, otherwise set an exception
321 * and returns 0.
322 */
Victor Stinneref128102010-10-07 01:00:52 +0000323static int
324checktm(struct tm* buf)
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000325{
Victor Stinneref128102010-10-07 01:00:52 +0000326 /* Checks added to make sure strftime() and asctime() does not crash Python by
327 indexing blindly into some array for a textual representation
328 by some bad index (fixes bug #897625 and #6608).
329
330 Also support values of zero from Python code for arguments in which
331 that is out of range by forcing that value to the lowest value that
332 is valid (fixed bug #1520914).
333
334 Valid ranges based on what is allowed in struct tm:
335
336 - tm_year: [0, max(int)] (1)
337 - tm_mon: [0, 11] (2)
338 - tm_mday: [1, 31]
339 - tm_hour: [0, 23]
340 - tm_min: [0, 59]
341 - tm_sec: [0, 60]
342 - tm_wday: [0, 6] (1)
343 - tm_yday: [0, 365] (2)
344 - tm_isdst: [-max(int), max(int)]
345
346 (1) gettmarg() handles bounds-checking.
347 (2) Python's acceptable range is one greater than the range in C,
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000348 thus need to check against automatic decrement by gettmarg().
349 */
350 if (buf->tm_mon == -1)
351 buf->tm_mon = 0;
352 else if (buf->tm_mon < 0 || buf->tm_mon > 11) {
353 PyErr_SetString(PyExc_ValueError, "month out of range");
354 return 0;
355 }
356 if (buf->tm_mday == 0)
357 buf->tm_mday = 1;
358 else if (buf->tm_mday < 0 || buf->tm_mday > 31) {
359 PyErr_SetString(PyExc_ValueError, "day of month out of range");
360 return 0;
361 }
362 if (buf->tm_hour < 0 || buf->tm_hour > 23) {
363 PyErr_SetString(PyExc_ValueError, "hour out of range");
364 return 0;
365 }
366 if (buf->tm_min < 0 || buf->tm_min > 59) {
367 PyErr_SetString(PyExc_ValueError, "minute out of range");
368 return 0;
369 }
370 if (buf->tm_sec < 0 || buf->tm_sec > 61) {
371 PyErr_SetString(PyExc_ValueError, "seconds out of range");
372 return 0;
373 }
374 /* tm_wday does not need checking of its upper-bound since taking
375 ``% 7`` in gettmarg() automatically restricts the range. */
376 if (buf->tm_wday < 0) {
377 PyErr_SetString(PyExc_ValueError, "day of week out of range");
378 return 0;
379 }
380 if (buf->tm_yday == -1)
381 buf->tm_yday = 0;
382 else if (buf->tm_yday < 0 || buf->tm_yday > 365) {
383 PyErr_SetString(PyExc_ValueError, "day of year out of range");
384 return 0;
385 }
386 return 1;
387}
388
Victor Stinnerc1f32ca2011-10-14 02:36:13 +0200389#ifdef MS_WINDOWS
390 /* wcsftime() doesn't format correctly time zones, see issue #10653 */
391# undef HAVE_WCSFTIME
392#endif
393
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000394#ifdef HAVE_STRFTIME
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000395#ifdef HAVE_WCSFTIME
396#define time_char wchar_t
397#define format_time wcsftime
398#define time_strlen wcslen
399#else
400#define time_char char
401#define format_time strftime
402#define time_strlen strlen
403#endif
404
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000405static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000406time_strftime(PyObject *self, PyObject *args)
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000407{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000408 PyObject *tup = NULL;
409 struct tm buf;
410 const time_char *fmt;
Victor Stinnerb2904782010-09-29 10:34:19 +0000411#ifdef HAVE_WCSFTIME
412 wchar_t *format;
413#else
414 PyObject *format;
415#endif
Victor Stinneref128102010-10-07 01:00:52 +0000416 PyObject *format_arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000417 size_t fmtlen, buflen;
Victor Stinnerb2904782010-09-29 10:34:19 +0000418 time_char *outbuf = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000419 size_t i;
Victor Stinnerb2904782010-09-29 10:34:19 +0000420 PyObject *ret = NULL;
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000421
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000422 memset((void *) &buf, '\0', sizeof(buf));
Guido van Rossum1f41f841998-04-27 19:04:26 +0000423
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000424 /* Will always expect a unicode string to be passed as format.
425 Given that there's no str type anymore in py3k this seems safe.
426 */
Victor Stinneref128102010-10-07 01:00:52 +0000427 if (!PyArg_ParseTuple(args, "U|O:strftime", &format_arg, &tup))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000428 return NULL;
Thomas Woutersfe385252001-01-19 23:16:56 +0000429
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000430 if (tup == NULL) {
431 time_t tt = time(NULL);
432 buf = *localtime(&tt);
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000433 }
434 else if (!gettmarg(tup, &buf) || !checktm(&buf))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000435 return NULL;
Guido van Rossum10b164a2001-09-25 13:59:01 +0000436
Victor Stinner06ec45e2011-01-08 03:35:36 +0000437#if defined(_MSC_VER) || defined(sun)
Victor Stinner73ea29c2011-01-08 01:56:31 +0000438 if (buf.tm_year + 1900 < 1 || 9999 < buf.tm_year + 1900) {
Victor Stinner6f0e4f92011-03-21 02:14:53 +0100439 PyErr_SetString(PyExc_ValueError,
440 "strftime() requires year in [1; 9999]");
Alexander Belopolsky0dd06f42011-01-08 01:23:02 +0000441 return NULL;
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000442 }
Victor Stinner73ea29c2011-01-08 01:56:31 +0000443#endif
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000444
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000445 /* Normalize tm_isdst just in case someone foolishly implements %Z
446 based on the assumption that tm_isdst falls within the range of
447 [-1, 1] */
448 if (buf.tm_isdst < -1)
449 buf.tm_isdst = -1;
450 else if (buf.tm_isdst > 1)
451 buf.tm_isdst = 1;
Brett Cannond1080a32004-03-02 04:38:10 +0000452
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000453#ifdef HAVE_WCSFTIME
Victor Stinnerbeb4135b2010-10-07 01:02:42 +0000454 format = PyUnicode_AsWideCharString(format_arg, NULL);
Victor Stinnerb2904782010-09-29 10:34:19 +0000455 if (format == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000456 return NULL;
Victor Stinnerb2904782010-09-29 10:34:19 +0000457 fmt = format;
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000458#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000459 /* Convert the unicode string to an ascii one */
Victor Stinneref128102010-10-07 01:00:52 +0000460 format = PyUnicode_AsEncodedString(format_arg, TZNAME_ENCODING, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000461 if (format == NULL)
462 return NULL;
463 fmt = PyBytes_AS_STRING(format);
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000464#endif
Amaury Forgeot d'Arcb5be6d42009-03-02 23:52:57 +0000465
Victor Stinner5a3ff792011-10-16 19:08:23 +0200466#if defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000467 /* check that the format string contains only valid directives */
Victor Stinner5a3ff792011-10-16 19:08:23 +0200468 for(outbuf = strchr(fmt, '%');
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000469 outbuf != NULL;
Victor Stinner5a3ff792011-10-16 19:08:23 +0200470 outbuf = strchr(outbuf+2, '%'))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000471 {
472 if (outbuf[1]=='#')
473 ++outbuf; /* not documented by python, */
474 if (outbuf[1]=='\0' ||
Victor Stinner5a3ff792011-10-16 19:08:23 +0200475 !strchr("aAbBcdHIjmMpSUwWxXyYzZ%", outbuf[1]))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000476 {
477 PyErr_SetString(PyExc_ValueError, "Invalid format string");
478 return 0;
479 }
480 }
Amaury Forgeot d'Arcb5be6d42009-03-02 23:52:57 +0000481#endif
482
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000483 fmtlen = time_strlen(fmt);
Guido van Rossumc222ec21999-02-23 00:00:10 +0000484
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000485 /* I hate these functions that presume you know how big the output
486 * will be ahead of time...
487 */
488 for (i = 1024; ; i += i) {
489 outbuf = (time_char *)PyMem_Malloc(i*sizeof(time_char));
490 if (outbuf == NULL) {
Victor Stinnerb2904782010-09-29 10:34:19 +0000491 PyErr_NoMemory();
492 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000493 }
494 buflen = format_time(outbuf, i, fmt, &buf);
495 if (buflen > 0 || i >= 256 * fmtlen) {
496 /* If the buffer is 256 times as long as the format,
497 it's probably not failing for lack of room!
498 More likely, the format yields an empty result,
499 e.g. an empty format, or %Z when the timezone
500 is unknown. */
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000501#ifdef HAVE_WCSFTIME
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000502 ret = PyUnicode_FromWideChar(outbuf, buflen);
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000503#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000504 ret = PyUnicode_Decode(outbuf, buflen,
505 TZNAME_ENCODING, NULL);
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000506#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000507 PyMem_Free(outbuf);
Victor Stinnerb2904782010-09-29 10:34:19 +0000508 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000509 }
510 PyMem_Free(outbuf);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000511#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000512 /* VisualStudio .NET 2005 does this properly */
513 if (buflen == 0 && errno == EINVAL) {
514 PyErr_SetString(PyExc_ValueError, "Invalid format string");
Victor Stinnerb2904782010-09-29 10:34:19 +0000515 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000516 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000517#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000518 }
Victor Stinnerb2904782010-09-29 10:34:19 +0000519#ifdef HAVE_WCSFTIME
520 PyMem_Free(format);
521#else
522 Py_DECREF(format);
523#endif
524 return ret;
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000525}
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000526
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000527#undef time_char
528#undef format_time
529
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000530PyDoc_STRVAR(strftime_doc,
Thomas Woutersfe385252001-01-19 23:16:56 +0000531"strftime(format[, tuple]) -> string\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000532\n\
533Convert a time tuple to a string according to a format specification.\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000534See the library reference manual for formatting codes. When the time tuple\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000535is not present, current time as returned by localtime() is used.");
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000536#endif /* HAVE_STRFTIME */
537
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000538static PyObject *
539time_strptime(PyObject *self, PyObject *args)
540{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000541 PyObject *strptime_module = PyImport_ImportModuleNoBlock("_strptime");
542 PyObject *strptime_result;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200543 _Py_IDENTIFIER(_strptime_time);
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000544
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000545 if (!strptime_module)
546 return NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200547 strptime_result = _PyObject_CallMethodId(strptime_module,
548 &PyId__strptime_time, "O", args);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000549 Py_DECREF(strptime_module);
550 return strptime_result;
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000551}
552
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000553
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000554PyDoc_STRVAR(strptime_doc,
Brett Cannon20def8b2003-07-01 05:16:08 +0000555"strptime(string, format) -> struct_time\n\
Martin v. Löwisb3cfc1d2001-12-02 12:27:43 +0000556\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000557Parse a string to a time tuple according to a format specification.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000558See the library reference manual for formatting codes (same as strftime()).");
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000559
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000560static PyObject *
561_asctime(struct tm *timeptr)
562{
563 /* Inspired by Open Group reference implementation available at
564 * http://pubs.opengroup.org/onlinepubs/009695399/functions/asctime.html */
Victor Stinner499dfcf2011-03-21 13:26:24 +0100565 static char wday_name[7][4] = {
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000566 "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
567 };
Victor Stinner499dfcf2011-03-21 13:26:24 +0100568 static char mon_name[12][4] = {
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000569 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
570 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
571 };
Victor Stinner499dfcf2011-03-21 13:26:24 +0100572 return PyUnicode_FromFormat(
573 "%s %s%3d %.2d:%.2d:%.2d %d",
574 wday_name[timeptr->tm_wday],
575 mon_name[timeptr->tm_mon],
576 timeptr->tm_mday, timeptr->tm_hour,
577 timeptr->tm_min, timeptr->tm_sec,
578 1900 + timeptr->tm_year);
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000579}
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000580
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000581static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000582time_asctime(PyObject *self, PyObject *args)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000583{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000584 PyObject *tup = NULL;
585 struct tm buf;
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000586
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000587 if (!PyArg_UnpackTuple(args, "asctime", 0, 1, &tup))
588 return NULL;
589 if (tup == NULL) {
590 time_t tt = time(NULL);
591 buf = *localtime(&tt);
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000592 } else if (!gettmarg(tup, &buf) || !checktm(&buf))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000593 return NULL;
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000594 return _asctime(&buf);
Guido van Rossum9e90a671993-06-24 11:10:19 +0000595}
596
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000597PyDoc_STRVAR(asctime_doc,
Thomas Woutersfe385252001-01-19 23:16:56 +0000598"asctime([tuple]) -> string\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000599\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000600Convert a time tuple to a string, e.g. 'Sat Jun 06 16:26:11 1998'.\n\
601When the time tuple is not present, current time as returned by localtime()\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000602is used.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000603
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000604static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000605time_ctime(PyObject *self, PyObject *args)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000606{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000607 PyObject *ot = NULL;
608 time_t tt;
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000609 struct tm *timeptr;
Guido van Rossum10b164a2001-09-25 13:59:01 +0000610
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000611 if (!PyArg_UnpackTuple(args, "ctime", 0, 1, &ot))
612 return NULL;
613 if (ot == NULL || ot == Py_None)
614 tt = time(NULL);
615 else {
616 double dt = PyFloat_AsDouble(ot);
617 if (PyErr_Occurred())
618 return NULL;
619 tt = _PyTime_DoubleToTimet(dt);
620 if (tt == (time_t)-1 && PyErr_Occurred())
621 return NULL;
622 }
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000623 timeptr = localtime(&tt);
624 if (timeptr == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000625 PyErr_SetString(PyExc_ValueError, "unconvertible time");
Alexander Belopolsky5da468f2011-01-04 17:15:52 +0000626 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000627 }
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000628 return _asctime(timeptr);
Guido van Rossum9e90a671993-06-24 11:10:19 +0000629}
630
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000631PyDoc_STRVAR(ctime_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000632"ctime(seconds) -> string\n\
633\n\
634Convert a time in seconds since the Epoch to a string in local time.\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000635This is equivalent to asctime(localtime(seconds)). When the time tuple is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000636not present, current time as returned by localtime() is used.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000637
Guido van Rossum60cd8131998-03-06 17:16:21 +0000638#ifdef HAVE_MKTIME
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000639static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000640time_mktime(PyObject *self, PyObject *tup)
Guido van Rossum234f9421993-06-17 12:35:49 +0000641{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000642 struct tm buf;
643 time_t tt;
644 if (!gettmarg(tup, &buf))
645 return NULL;
Alexander Belopolskyb7d40d12011-01-11 01:21:25 +0000646 buf.tm_wday = -1; /* sentinel; original value ignored */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000647 tt = mktime(&buf);
Alexander Belopolskyb7d40d12011-01-11 01:21:25 +0000648 /* Return value of -1 does not necessarily mean an error, but tm_wday
Ezio Melotti13925002011-03-16 11:05:33 +0200649 * cannot remain set to -1 if mktime succeeded. */
Alexander Belopolskyb7d40d12011-01-11 01:21:25 +0000650 if (tt == (time_t)(-1) && buf.tm_wday == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000651 PyErr_SetString(PyExc_OverflowError,
652 "mktime argument out of range");
653 return NULL;
654 }
655 return PyFloat_FromDouble((double)tt);
Guido van Rossum234f9421993-06-17 12:35:49 +0000656}
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000657
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000658PyDoc_STRVAR(mktime_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000659"mktime(tuple) -> floating point number\n\
660\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000661Convert a time tuple in local time to seconds since the Epoch.");
Guido van Rossum60cd8131998-03-06 17:16:21 +0000662#endif /* HAVE_MKTIME */
Guido van Rossum234f9421993-06-17 12:35:49 +0000663
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000664#ifdef HAVE_WORKING_TZSET
Martin v. Löwis1a214512008-06-11 05:26:20 +0000665static void PyInit_timezone(PyObject *module);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000666
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000667static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000668time_tzset(PyObject *self, PyObject *unused)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000669{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000670 PyObject* m;
Fred Drake9bb74322002-04-01 14:49:59 +0000671
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000672 m = PyImport_ImportModuleNoBlock("time");
673 if (m == NULL) {
674 return NULL;
675 }
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000676
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000677 tzset();
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000678
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000679 /* Reset timezone, altzone, daylight and tzname */
680 PyInit_timezone(m);
681 Py_DECREF(m);
Tim Peters1b6f7a92004-06-20 02:50:16 +0000682
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000683 Py_INCREF(Py_None);
684 return Py_None;
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000685}
686
687PyDoc_STRVAR(tzset_doc,
R. David Murray4d55bf92010-12-14 00:55:46 +0000688"tzset()\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000689\n\
690Initialize, or reinitialize, the local timezone to the value stored in\n\
691os.environ['TZ']. The TZ environment variable should be specified in\n\
Neal Norwitzdc8e1942004-07-20 22:34:37 +0000692standard Unix timezone format as documented in the tzset man page\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000693(eg. 'US/Eastern', 'Europe/Amsterdam'). Unknown timezones will silently\n\
694fall back to UTC. If the TZ environment variable is not set, the local\n\
695timezone is set to the systems best guess of wallclock time.\n\
696Changing the TZ environment variable without calling tzset *may* change\n\
697the local timezone used by methods such as localtime, but this behaviour\n\
698should not be relied on.");
699#endif /* HAVE_WORKING_TZSET */
700
Martin v. Löwisd218dc12008-04-07 03:17:54 +0000701static void
Martin v. Löwis1a214512008-06-11 05:26:20 +0000702PyInit_timezone(PyObject *m) {
703 /* This code moved from PyInit_time wholesale to allow calling it from
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000704 time_tzset. In the future, some parts of it can be moved back
705 (for platforms that don't HAVE_WORKING_TZSET, when we know what they
706 are), and the extraneous calls to tzset(3) should be removed.
707 I haven't done this yet, as I don't want to change this code as
708 little as possible when introducing the time.tzset and time.tzsetwall
709 methods. This should simply be a method of doing the following once,
710 at the top of this function and removing the call to tzset() from
711 time_tzset():
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000712
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000713 #ifdef HAVE_TZSET
714 tzset()
715 #endif
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000716
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000717 And I'm lazy and hate C so nyer.
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000718 */
Guido van Rossum10b164a2001-09-25 13:59:01 +0000719#if defined(HAVE_TZNAME) && !defined(__GLIBC__) && !defined(__CYGWIN__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000720 PyObject *otz0, *otz1;
721 tzset();
Guido van Rossum26452411998-09-28 22:07:11 +0000722#ifdef PYOS_OS2
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000723 PyModule_AddIntConstant(m, "timezone", _timezone);
Guido van Rossum26452411998-09-28 22:07:11 +0000724#else /* !PYOS_OS2 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000725 PyModule_AddIntConstant(m, "timezone", timezone);
Guido van Rossum26452411998-09-28 22:07:11 +0000726#endif /* PYOS_OS2 */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000727#ifdef HAVE_ALTZONE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000728 PyModule_AddIntConstant(m, "altzone", altzone);
Guido van Rossumb6775db1994-08-01 11:34:53 +0000729#else
Guido van Rossum26452411998-09-28 22:07:11 +0000730#ifdef PYOS_OS2
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000731 PyModule_AddIntConstant(m, "altzone", _timezone-3600);
Guido van Rossum26452411998-09-28 22:07:11 +0000732#else /* !PYOS_OS2 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000733 PyModule_AddIntConstant(m, "altzone", timezone-3600);
Guido van Rossum26452411998-09-28 22:07:11 +0000734#endif /* PYOS_OS2 */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000735#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000736 PyModule_AddIntConstant(m, "daylight", daylight);
737 otz0 = PyUnicode_Decode(tzname[0], strlen(tzname[0]), TZNAME_ENCODING, NULL);
738 otz1 = PyUnicode_Decode(tzname[1], strlen(tzname[1]), TZNAME_ENCODING, NULL);
739 PyModule_AddObject(m, "tzname", Py_BuildValue("(NN)", otz0, otz1));
Guido van Rossum10b164a2001-09-25 13:59:01 +0000740#else /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/
Martin v. Löwis60a5d722002-10-16 20:28:25 +0000741#ifdef HAVE_STRUCT_TM_TM_ZONE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000742 {
Guido van Rossum234f9421993-06-17 12:35:49 +0000743#define YEAR ((time_t)((365 * 24 + 6) * 3600))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000744 time_t t;
745 struct tm *p;
746 long janzone, julyzone;
747 char janname[10], julyname[10];
748 t = (time((time_t *)0) / YEAR) * YEAR;
749 p = localtime(&t);
750 janzone = -p->tm_gmtoff;
751 strncpy(janname, p->tm_zone ? p->tm_zone : " ", 9);
752 janname[9] = '\0';
753 t += YEAR/2;
754 p = localtime(&t);
755 julyzone = -p->tm_gmtoff;
756 strncpy(julyname, p->tm_zone ? p->tm_zone : " ", 9);
757 julyname[9] = '\0';
Guido van Rossum10b164a2001-09-25 13:59:01 +0000758
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000759 if( janzone < julyzone ) {
760 /* DST is reversed in the southern hemisphere */
761 PyModule_AddIntConstant(m, "timezone", julyzone);
762 PyModule_AddIntConstant(m, "altzone", janzone);
763 PyModule_AddIntConstant(m, "daylight",
764 janzone != julyzone);
765 PyModule_AddObject(m, "tzname",
766 Py_BuildValue("(zz)",
767 julyname, janname));
768 } else {
769 PyModule_AddIntConstant(m, "timezone", janzone);
770 PyModule_AddIntConstant(m, "altzone", julyzone);
771 PyModule_AddIntConstant(m, "daylight",
772 janzone != julyzone);
773 PyModule_AddObject(m, "tzname",
774 Py_BuildValue("(zz)",
775 janname, julyname));
776 }
777 }
Guido van Rossume6a4b7b1997-10-08 15:27:56 +0000778#else
Martin v. Löwis60a5d722002-10-16 20:28:25 +0000779#endif /* HAVE_STRUCT_TM_TM_ZONE */
Tim Peters26ae7cd2001-03-20 03:26:49 +0000780#ifdef __CYGWIN__
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000781 tzset();
782 PyModule_AddIntConstant(m, "timezone", _timezone);
783 PyModule_AddIntConstant(m, "altzone", _timezone-3600);
784 PyModule_AddIntConstant(m, "daylight", _daylight);
785 PyModule_AddObject(m, "tzname",
786 Py_BuildValue("(zz)", _tzname[0], _tzname[1]));
Tim Peters26ae7cd2001-03-20 03:26:49 +0000787#endif /* __CYGWIN__ */
Guido van Rossum10b164a2001-09-25 13:59:01 +0000788#endif /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000789}
790
791
792static PyMethodDef time_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000793 {"time", time_time, METH_NOARGS, time_doc},
Victor Stinner9122fdd2011-07-04 13:55:40 +0200794#if (defined(MS_WINDOWS) && !defined(__BORLANDC__)) || defined(HAVE_CLOCK)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000795 {"clock", time_clock, METH_NOARGS, clock_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000796#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000797 {"sleep", time_sleep, METH_VARARGS, sleep_doc},
798 {"gmtime", time_gmtime, METH_VARARGS, gmtime_doc},
799 {"localtime", time_localtime, METH_VARARGS, localtime_doc},
800 {"asctime", time_asctime, METH_VARARGS, asctime_doc},
801 {"ctime", time_ctime, METH_VARARGS, ctime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000802#ifdef HAVE_MKTIME
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000803 {"mktime", time_mktime, METH_O, mktime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000804#endif
805#ifdef HAVE_STRFTIME
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000806 {"strftime", time_strftime, METH_VARARGS, strftime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000807#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000808 {"strptime", time_strptime, METH_VARARGS, strptime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000809#ifdef HAVE_WORKING_TZSET
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000810 {"tzset", time_tzset, METH_NOARGS, tzset_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000811#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000812 {NULL, NULL} /* sentinel */
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000813};
814
815
816PyDoc_STRVAR(module_doc,
817"This module provides various functions to manipulate time values.\n\
818\n\
819There are two standard representations of time. One is the number\n\
820of seconds since the Epoch, in UTC (a.k.a. GMT). It may be an integer\n\
821or a floating point number (to represent fractions of seconds).\n\
822The Epoch is system-defined; on Unix, it is generally January 1st, 1970.\n\
823The actual value can be retrieved by calling gmtime(0).\n\
824\n\
825The other representation is a tuple of 9 integers giving local time.\n\
826The tuple items are:\n\
Alexander Belopolsky03163ac2011-05-02 12:20:52 -0400827 year (including century, e.g. 1998)\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000828 month (1-12)\n\
829 day (1-31)\n\
830 hours (0-23)\n\
831 minutes (0-59)\n\
832 seconds (0-59)\n\
833 weekday (0-6, Monday is 0)\n\
834 Julian day (day in the year, 1-366)\n\
835 DST (Daylight Savings Time) flag (-1, 0 or 1)\n\
836If the DST flag is 0, the time is given in the regular time zone;\n\
837if it is 1, the time is given in the DST time zone;\n\
838if it is -1, mktime() should guess based on the date and time.\n\
839\n\
840Variables:\n\
841\n\
842timezone -- difference in seconds between UTC and local standard time\n\
843altzone -- difference in seconds between UTC and local DST time\n\
844daylight -- whether local time should reflect DST\n\
845tzname -- tuple of (standard time zone name, DST time zone name)\n\
846\n\
847Functions:\n\
848\n\
849time() -- return current time in seconds since the Epoch as a float\n\
850clock() -- return CPU time since process start as a float\n\
851sleep() -- delay for a number of seconds given as a float\n\
852gmtime() -- convert seconds since Epoch to UTC tuple\n\
853localtime() -- convert seconds since Epoch to local time tuple\n\
854asctime() -- convert time tuple to string\n\
855ctime() -- convert time in seconds to string\n\
856mktime() -- convert local time tuple to seconds since Epoch\n\
857strftime() -- convert time tuple to string according to format specification\n\
858strptime() -- parse string to time tuple according to format specification\n\
859tzset() -- change the local timezone");
860
861
Martin v. Löwis1a214512008-06-11 05:26:20 +0000862
863static struct PyModuleDef timemodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000864 PyModuleDef_HEAD_INIT,
865 "time",
866 module_doc,
867 -1,
868 time_methods,
869 NULL,
870 NULL,
871 NULL,
872 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +0000873};
874
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000875PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +0000876PyInit_time(void)
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000877{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000878 PyObject *m;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000879 m = PyModule_Create(&timemodule);
880 if (m == NULL)
881 return NULL;
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000882
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000883 /* Set, or reset, module variables like time.timezone */
884 PyInit_timezone(m);
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000885
Mark Hammond975e3922002-07-16 01:29:19 +0000886#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000887 /* Helper to allow interrupts for Windows.
888 If Ctrl+C event delivered while not sleeping
889 it will be ignored.
890 */
891 main_thread = PyThread_get_thread_ident();
892 hInterruptEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
893 SetConsoleCtrlHandler( PyCtrlHandler, TRUE);
Mark Hammond975e3922002-07-16 01:29:19 +0000894#endif /* MS_WINDOWS */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000895 if (!initialized) {
896 PyStructSequence_InitType(&StructTimeType,
897 &struct_time_type_desc);
898 }
899 Py_INCREF(&StructTimeType);
900 PyModule_AddObject(m, "struct_time", (PyObject*) &StructTimeType);
901 initialized = 1;
902 return m;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000903}
904
Guido van Rossumb6775db1994-08-01 11:34:53 +0000905static double
Thomas Woutersf3f33dc2000-07-21 06:00:07 +0000906floattime(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000907{
Alexander Belopolsky6fc4ade2010-08-05 17:34:27 +0000908 _PyTime_timeval t;
909 _PyTime_gettimeofday(&t);
910 return (double)t.tv_sec + t.tv_usec*0.000001;
Guido van Rossum426035c1991-02-19 12:27:35 +0000911}
912
Guido van Rossumb6775db1994-08-01 11:34:53 +0000913
914/* Implement floatsleep() for various platforms.
915 When interrupted (or when another error occurs), return -1 and
916 set an exception; else return 0. */
917
918static int
Guido van Rossuma320fd31995-03-09 12:14:15 +0000919floatsleep(double secs)
Guido van Rossum426035c1991-02-19 12:27:35 +0000920{
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000921/* XXX Should test for MS_WINDOWS first! */
Skip Montanaroeb33e5a2007-08-17 12:57:41 +0000922#if defined(HAVE_SELECT) && !defined(__EMX__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000923 struct timeval t;
924 double frac;
Victor Stinner48b1ce52011-07-01 13:50:09 +0200925 int err;
926
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000927 frac = fmod(secs, 1.0);
928 secs = floor(secs);
929 t.tv_sec = (long)secs;
930 t.tv_usec = (long)(frac*1000000.0);
931 Py_BEGIN_ALLOW_THREADS
Victor Stinner48b1ce52011-07-01 13:50:09 +0200932 err = select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &t);
933 Py_END_ALLOW_THREADS
934 if (err != 0) {
Guido van Rossum09cbb011999-11-08 15:32:27 +0000935#ifdef EINTR
Victor Stinner48b1ce52011-07-01 13:50:09 +0200936 if (errno == EINTR) {
937 if (PyErr_CheckSignals())
938 return -1;
939 }
940 else
Guido van Rossum09cbb011999-11-08 15:32:27 +0000941#endif
Victor Stinner48b1ce52011-07-01 13:50:09 +0200942 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000943 PyErr_SetFromErrno(PyExc_IOError);
944 return -1;
945 }
946 }
Martin v. Löwis02af9642002-01-16 11:04:06 +0000947#elif defined(__WATCOMC__) && !defined(__QNX__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000948 /* XXX Can't interrupt this sleep */
949 Py_BEGIN_ALLOW_THREADS
950 delay((int)(secs * 1000 + 0.5)); /* delay() uses milliseconds */
951 Py_END_ALLOW_THREADS
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000952#elif defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000953 {
954 double millisecs = secs * 1000.0;
955 unsigned long ul_millis;
Tim Peters513a1cd2003-01-19 04:54:58 +0000956
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000957 if (millisecs > (double)ULONG_MAX) {
958 PyErr_SetString(PyExc_OverflowError,
959 "sleep length is too large");
960 return -1;
961 }
962 Py_BEGIN_ALLOW_THREADS
963 /* Allow sleep(0) to maintain win32 semantics, and as decreed
964 * by Guido, only the main thread can be interrupted.
965 */
966 ul_millis = (unsigned long)millisecs;
967 if (ul_millis == 0 ||
968 main_thread != PyThread_get_thread_ident())
969 Sleep(ul_millis);
970 else {
971 DWORD rc;
972 ResetEvent(hInterruptEvent);
973 rc = WaitForSingleObject(hInterruptEvent, ul_millis);
974 if (rc == WAIT_OBJECT_0) {
975 /* Yield to make sure real Python signal
976 * handler called.
977 */
978 Sleep(1);
979 Py_BLOCK_THREADS
980 errno = EINTR;
981 PyErr_SetFromErrno(PyExc_IOError);
982 return -1;
983 }
984 }
985 Py_END_ALLOW_THREADS
986 }
Martin v. Löwis02af9642002-01-16 11:04:06 +0000987#elif defined(PYOS_OS2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000988 /* This Sleep *IS* Interruptable by Exceptions */
989 Py_BEGIN_ALLOW_THREADS
990 if (DosSleep(secs * 1000) != NO_ERROR) {
991 Py_BLOCK_THREADS
992 PyErr_SetFromErrno(PyExc_IOError);
993 return -1;
994 }
995 Py_END_ALLOW_THREADS
Martin v. Löwis02af9642002-01-16 11:04:06 +0000996#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000997 /* XXX Can't interrupt this sleep */
998 Py_BEGIN_ALLOW_THREADS
999 sleep((int)secs);
1000 Py_END_ALLOW_THREADS
Martin v. Löwis02af9642002-01-16 11:04:06 +00001001#endif
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001002
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001003 return 0;
Guido van Rossum80c9d881991-04-16 08:47:51 +00001004}