blob: 2b86bcb4914010eea8152dc3619a0f34a0cfee62 [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
Martin v. Löwis8a7c8662007-08-30 15:40:24 +00006#define TZNAME_ENCODING "utf-8"
7
Guido van Rossum87ce7bb1998-06-09 16:30:31 +00008#include <ctype.h>
9
Thomas Wouters0e3f5912006-08-11 14:57:12 +000010#ifdef HAVE_SYS_TYPES_H
Guido van Rossumb6775db1994-08-01 11:34:53 +000011#include <sys/types.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012#endif /* HAVE_SYS_TYPES_H */
Guido van Rossum6d946f91992-08-14 13:49:30 +000013
Guido van Rossumb6775db1994-08-01 11:34:53 +000014#ifdef QUICKWIN
15#include <io.h>
16#endif
17
Guido van Rossum7bf22de1997-12-02 20:34:19 +000018#if defined(__WATCOMC__) && !defined(__QNX__)
Guido van Rossumbceeac81996-05-23 22:53:47 +000019#include <i86.h>
20#else
Guido van Rossumcac6c721996-09-06 13:34:02 +000021#ifdef MS_WINDOWS
Mark Hammond975e3922002-07-16 01:29:19 +000022#define WIN32_LEAN_AND_MEAN
Guido van Rossum258ccd42001-03-02 06:53:29 +000023#include <windows.h>
Mark Hammond975e3922002-07-16 01:29:19 +000024#include "pythread.h"
25
26/* helper to allow us to interrupt sleep() on Windows*/
27static HANDLE hInterruptEvent = NULL;
28static BOOL WINAPI PyCtrlHandler(DWORD dwCtrlType)
29{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000030 SetEvent(hInterruptEvent);
31 /* allow other default handlers to be called.
32 Default Python handler will setup the
33 KeyboardInterrupt exception.
34 */
35 return FALSE;
Mark Hammond975e3922002-07-16 01:29:19 +000036}
37static long main_thread;
38
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000039#if defined(__BORLANDC__)
Guido van Rossumb2fb3641996-09-07 00:47:35 +000040/* These overrides not needed for Win32 */
Guido van Rossumb6775db1994-08-01 11:34:53 +000041#define timezone _timezone
Guido van Rossumcc081121995-03-14 15:05:41 +000042#define tzname _tzname
43#define daylight _daylight
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000044#endif /* __BORLANDC__ */
Guido van Rossumcac6c721996-09-06 13:34:02 +000045#endif /* MS_WINDOWS */
Guido van Rossum7bf22de1997-12-02 20:34:19 +000046#endif /* !__WATCOMC__ || __QNX__ */
Guido van Rossum234f9421993-06-17 12:35:49 +000047
Thomas Wouters477c8d52006-05-27 19:21:47 +000048#if defined(MS_WINDOWS) && !defined(__BORLANDC__)
49/* Win32 has better clock replacement; we have our own version below. */
50#undef HAVE_CLOCK
Martin v. Löwis3bb00702007-08-30 14:37:48 +000051#undef TZNAME_ENCODING
52#define TZNAME_ENCODING "mbcs"
Thomas Wouters477c8d52006-05-27 19:21:47 +000053#endif /* MS_WINDOWS && !defined(__BORLANDC__) */
Guido van Rossum3917c221997-04-02 05:35:28 +000054
Andrew MacIntyre7bf68332002-03-03 02:59:16 +000055#if defined(PYOS_OS2)
56#define INCL_DOS
57#define INCL_ERRORS
58#include <os2.h>
59#endif
60
Guido van Rossum8e9ebfd1997-11-22 21:53:48 +000061#if defined(PYCC_VACPP)
Guido van Rossum26452411998-09-28 22:07:11 +000062#include <sys/time.h>
Guido van Rossum8e9ebfd1997-11-22 21:53:48 +000063#endif
64
Guido van Rossum234f9421993-06-17 12:35:49 +000065/* Forward declarations */
Tim Petersdbd9ba62000-07-09 03:09:57 +000066static int floatsleep(double);
Thomas Woutersed77bac2000-07-24 15:26:39 +000067static double floattime(void);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000068
Barry Warsaw9a2a8a81996-12-06 23:32:14 +000069static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000070time_time(PyObject *self, PyObject *unused)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000071{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000072 double secs;
73 secs = floattime();
74 if (secs == 0.0) {
75 PyErr_SetFromErrno(PyExc_IOError);
76 return NULL;
77 }
78 return PyFloat_FromDouble(secs);
Guido van Rossumb6775db1994-08-01 11:34:53 +000079}
80
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000081PyDoc_STRVAR(time_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +000082"time() -> floating point number\n\
83\n\
84Return the current time in seconds since the Epoch.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000085Fractions of a second may be present if the system clock provides them.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +000086
Guido van Rossumb6775db1994-08-01 11:34:53 +000087#ifdef HAVE_CLOCK
88
89#ifndef CLOCKS_PER_SEC
Guido van Rossum1b66a4f1996-02-25 04:50:33 +000090#ifdef CLK_TCK
91#define CLOCKS_PER_SEC CLK_TCK
92#else
Guido van Rossumb6775db1994-08-01 11:34:53 +000093#define CLOCKS_PER_SEC 1000000
94#endif
Guido van Rossum1b66a4f1996-02-25 04:50:33 +000095#endif
Guido van Rossumb6775db1994-08-01 11:34:53 +000096
Barry Warsaw9a2a8a81996-12-06 23:32:14 +000097static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000098time_clock(PyObject *self, PyObject *unused)
Guido van Rossumb6775db1994-08-01 11:34:53 +000099{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000100 return PyFloat_FromDouble(((double)clock()) / CLOCKS_PER_SEC);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000101}
Guido van Rossumb6775db1994-08-01 11:34:53 +0000102#endif /* HAVE_CLOCK */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000103
Thomas Wouters477c8d52006-05-27 19:21:47 +0000104#if defined(MS_WINDOWS) && !defined(__BORLANDC__)
Mark Hammond7ba5e812002-02-12 04:02:33 +0000105/* Due to Mark Hammond and Tim Peters */
Guido van Rossum3917c221997-04-02 05:35:28 +0000106static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000107time_clock(PyObject *self, PyObject *unused)
Guido van Rossum3917c221997-04-02 05:35:28 +0000108{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000109 static LARGE_INTEGER ctrStart;
110 static double divisor = 0.0;
111 LARGE_INTEGER now;
112 double diff;
Guido van Rossum3917c221997-04-02 05:35:28 +0000113
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000114 if (divisor == 0.0) {
115 LARGE_INTEGER freq;
116 QueryPerformanceCounter(&ctrStart);
117 if (!QueryPerformanceFrequency(&freq) || freq.QuadPart == 0) {
118 /* Unlikely to happen - this works on all intel
119 machines at least! Revert to clock() */
120 return PyFloat_FromDouble(((double)clock()) /
121 CLOCKS_PER_SEC);
122 }
123 divisor = (double)freq.QuadPart;
124 }
125 QueryPerformanceCounter(&now);
126 diff = (double)(now.QuadPart - ctrStart.QuadPart);
127 return PyFloat_FromDouble(diff / divisor);
Guido van Rossum3917c221997-04-02 05:35:28 +0000128}
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000129
Guido van Rossum3917c221997-04-02 05:35:28 +0000130#define HAVE_CLOCK /* So it gets included in the methods */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000131#endif /* MS_WINDOWS && !defined(__BORLANDC__) */
Guido van Rossum3917c221997-04-02 05:35:28 +0000132
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000133#ifdef HAVE_CLOCK
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000134PyDoc_STRVAR(clock_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000135"clock() -> floating point number\n\
136\n\
137Return the CPU time or real time since the start of the process or since\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000138the first call to clock(). This has as much precision as the system\n\
139records.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000140#endif
141
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000142static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000143time_sleep(PyObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000144{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000145 double secs;
146 if (!PyArg_ParseTuple(args, "d:sleep", &secs))
147 return NULL;
148 if (floatsleep(secs) != 0)
149 return NULL;
150 Py_INCREF(Py_None);
151 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000152}
153
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000154PyDoc_STRVAR(sleep_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000155"sleep(seconds)\n\
156\n\
157Delay execution for a given number of seconds. The argument may be\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000158a floating point number for subsecond precision.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000159
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000160static PyStructSequence_Field struct_time_type_fields[] = {
Alexander Belopolsky69f3fd02010-06-05 15:04:51 +0000161 {"tm_year", "year, for example, 1993"},
162 {"tm_mon", "month of year, range [1, 12]"},
163 {"tm_mday", "day of month, range [1, 31]"},
164 {"tm_hour", "hours, range [0, 23]"},
165 {"tm_min", "minutes, range [0, 59]"},
166 {"tm_sec", "seconds, range [0, 61])"},
167 {"tm_wday", "day of week, range [0, 6], Monday is 0"},
168 {"tm_yday", "day of year, range [1, 366]"},
169 {"tm_isdst", "1 if summer time is in effect, 0 if not, and -1 if unknown"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000170 {0}
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000171};
172
173static PyStructSequence_Desc struct_time_type_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000174 "time.struct_time",
Alexander Belopolsky69f3fd02010-06-05 15:04:51 +0000175 "The time value as returned by gmtime(), localtime(), and strptime(), and\n"
176 " accepted by asctime(), mktime() and strftime(). May be considered as a\n"
177 " sequence of 9 integers.\n\n"
178 " Note that several fields' values are not the same as those defined by\n"
179 " the C language standard for struct tm. For example, the value of the\n"
180 " field tm_year is the actual year, not year - 1900. See individual\n"
181 " fields' descriptions for details.",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000182 struct_time_type_fields,
183 9,
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000184};
Tim Peters9ad4b682002-02-13 05:14:18 +0000185
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000186static int initialized;
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000187static PyTypeObject StructTimeType;
188
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000189static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000190tmtotuple(struct tm *p)
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000191{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000192 PyObject *v = PyStructSequence_New(&StructTimeType);
193 if (v == NULL)
194 return NULL;
Tim Peters9ad4b682002-02-13 05:14:18 +0000195
Christian Heimes217cfd12007-12-02 14:31:20 +0000196#define SET(i,val) PyStructSequence_SET_ITEM(v, i, PyLong_FromLong((long) val))
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000197
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000198 SET(0, p->tm_year + 1900);
199 SET(1, p->tm_mon + 1); /* Want January == 1 */
200 SET(2, p->tm_mday);
201 SET(3, p->tm_hour);
202 SET(4, p->tm_min);
203 SET(5, p->tm_sec);
204 SET(6, (p->tm_wday + 6) % 7); /* Want Monday == 0 */
205 SET(7, p->tm_yday + 1); /* Want January, 1 == 1 */
206 SET(8, p->tm_isdst);
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000207#undef SET
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000208 if (PyErr_Occurred()) {
209 Py_XDECREF(v);
210 return NULL;
211 }
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000212
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000213 return v;
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000214}
215
216static PyObject *
Brett Cannon298c3802004-06-19 20:48:43 +0000217time_convert(double when, struct tm * (*function)(const time_t *))
Guido van Rossum234f9421993-06-17 12:35:49 +0000218{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000219 struct tm *p;
220 time_t whent = _PyTime_DoubleToTimet(when);
Brett Cannon298c3802004-06-19 20:48:43 +0000221
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000222 if (whent == (time_t)-1 && PyErr_Occurred())
223 return NULL;
224 errno = 0;
225 p = function(&whent);
226 if (p == NULL) {
Guido van Rossum6e8583d1996-10-08 14:19:52 +0000227#ifdef EINVAL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000228 if (errno == 0)
229 errno = EINVAL;
Guido van Rossum6e8583d1996-10-08 14:19:52 +0000230#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000231 return PyErr_SetFromErrno(PyExc_ValueError);
232 }
233 return tmtotuple(p);
Guido van Rossum234f9421993-06-17 12:35:49 +0000234}
235
Fred Drakef901abd2004-08-03 17:58:55 +0000236/* Parse arg tuple that can contain an optional float-or-None value;
237 format needs to be "|O:name".
238 Returns non-zero on success (parallels PyArg_ParseTuple).
239*/
240static int
241parse_time_double_args(PyObject *args, char *format, double *pwhen)
242{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000243 PyObject *ot = NULL;
Fred Drakef901abd2004-08-03 17:58:55 +0000244
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000245 if (!PyArg_ParseTuple(args, format, &ot))
246 return 0;
247 if (ot == NULL || ot == Py_None)
248 *pwhen = floattime();
249 else {
250 double when = PyFloat_AsDouble(ot);
251 if (PyErr_Occurred())
252 return 0;
253 *pwhen = when;
254 }
255 return 1;
Fred Drakef901abd2004-08-03 17:58:55 +0000256}
257
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000258static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000259time_gmtime(PyObject *self, PyObject *args)
Guido van Rossum234f9421993-06-17 12:35:49 +0000260{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000261 double when;
262 if (!parse_time_double_args(args, "|O:gmtime", &when))
263 return NULL;
264 return time_convert(when, gmtime);
Guido van Rossum234f9421993-06-17 12:35:49 +0000265}
266
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000267PyDoc_STRVAR(gmtime_doc,
Christian Heimes9a371592007-12-28 14:08:13 +0000268"gmtime([seconds]) -> (tm_year, tm_mon, tm_mday, tm_hour, tm_min,\n\
Fred Drake193a3f62002-03-12 21:38:49 +0000269 tm_sec, tm_wday, tm_yday, tm_isdst)\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000270\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000271Convert seconds since the Epoch to a time tuple expressing UTC (a.k.a.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000272GMT). When 'seconds' is not passed in, convert the current time instead.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000273
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000274static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000275time_localtime(PyObject *self, PyObject *args)
Guido van Rossum234f9421993-06-17 12:35:49 +0000276{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000277 double when;
278 if (!parse_time_double_args(args, "|O:localtime", &when))
279 return NULL;
280 return time_convert(when, localtime);
Guido van Rossum234f9421993-06-17 12:35:49 +0000281}
282
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000283PyDoc_STRVAR(localtime_doc,
Christian Heimes9a371592007-12-28 14:08:13 +0000284"localtime([seconds]) -> (tm_year,tm_mon,tm_mday,tm_hour,tm_min,\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000285 tm_sec,tm_wday,tm_yday,tm_isdst)\n\
Martin v. Löwisb3cfc1d2001-12-02 12:27:43 +0000286\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000287Convert seconds since the Epoch to a time tuple expressing local time.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000288When 'seconds' is not passed in, convert the current time instead.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000289
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000290/* Convert 9-item tuple to tm structure. Return 1 on success, set
291 * an exception and return 0 on error.
292 */
Guido van Rossum9e90a671993-06-24 11:10:19 +0000293static int
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000294gettmarg(PyObject *args, struct tm *p)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000295{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000296 int y;
Guido van Rossumcfbaecc1998-08-25 14:51:12 +0000297
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000298 memset((void *) p, '\0', sizeof(struct tm));
Guido van Rossumb9081262007-08-25 03:14:09 +0000299
Alexander Belopolsky610e5442011-01-06 21:57:06 +0000300 if (!PyTuple_Check(args)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000301 PyErr_SetString(PyExc_TypeError,
302 "Tuple or struct_time argument required");
303 return 0;
304 }
Skip Montanaro41cfce92007-08-24 21:11:00 +0000305
Alexander Belopolsky610e5442011-01-06 21:57:06 +0000306 if (!PyArg_ParseTuple(args, "iiiiiiiii",
307 &y, &p->tm_mon, &p->tm_mday,
308 &p->tm_hour, &p->tm_min, &p->tm_sec,
309 &p->tm_wday, &p->tm_yday, &p->tm_isdst))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000310 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000311 p->tm_year = y - 1900;
312 p->tm_mon--;
313 p->tm_wday = (p->tm_wday + 1) % 7;
314 p->tm_yday--;
315 return 1;
Guido van Rossum9e90a671993-06-24 11:10:19 +0000316}
317
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000318/* Check values of the struct tm fields before it is passed to strftime() and
319 * asctime(). Return 1 if all values are valid, otherwise set an exception
320 * and returns 0.
321 */
Victor Stinneref128102010-10-07 01:00:52 +0000322static int
323checktm(struct tm* buf)
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000324{
Victor Stinneref128102010-10-07 01:00:52 +0000325 /* Checks added to make sure strftime() and asctime() does not crash Python by
326 indexing blindly into some array for a textual representation
327 by some bad index (fixes bug #897625 and #6608).
328
329 Also support values of zero from Python code for arguments in which
330 that is out of range by forcing that value to the lowest value that
331 is valid (fixed bug #1520914).
332
333 Valid ranges based on what is allowed in struct tm:
334
335 - tm_year: [0, max(int)] (1)
336 - tm_mon: [0, 11] (2)
337 - tm_mday: [1, 31]
338 - tm_hour: [0, 23]
339 - tm_min: [0, 59]
340 - tm_sec: [0, 60]
341 - tm_wday: [0, 6] (1)
342 - tm_yday: [0, 365] (2)
343 - tm_isdst: [-max(int), max(int)]
344
345 (1) gettmarg() handles bounds-checking.
346 (2) Python's acceptable range is one greater than the range in C,
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000347 thus need to check against automatic decrement by gettmarg().
348 */
349 if (buf->tm_mon == -1)
350 buf->tm_mon = 0;
351 else if (buf->tm_mon < 0 || buf->tm_mon > 11) {
352 PyErr_SetString(PyExc_ValueError, "month out of range");
353 return 0;
354 }
355 if (buf->tm_mday == 0)
356 buf->tm_mday = 1;
357 else if (buf->tm_mday < 0 || buf->tm_mday > 31) {
358 PyErr_SetString(PyExc_ValueError, "day of month out of range");
359 return 0;
360 }
361 if (buf->tm_hour < 0 || buf->tm_hour > 23) {
362 PyErr_SetString(PyExc_ValueError, "hour out of range");
363 return 0;
364 }
365 if (buf->tm_min < 0 || buf->tm_min > 59) {
366 PyErr_SetString(PyExc_ValueError, "minute out of range");
367 return 0;
368 }
369 if (buf->tm_sec < 0 || buf->tm_sec > 61) {
370 PyErr_SetString(PyExc_ValueError, "seconds out of range");
371 return 0;
372 }
373 /* tm_wday does not need checking of its upper-bound since taking
374 ``% 7`` in gettmarg() automatically restricts the range. */
375 if (buf->tm_wday < 0) {
376 PyErr_SetString(PyExc_ValueError, "day of week out of range");
377 return 0;
378 }
379 if (buf->tm_yday == -1)
380 buf->tm_yday = 0;
381 else if (buf->tm_yday < 0 || buf->tm_yday > 365) {
382 PyErr_SetString(PyExc_ValueError, "day of year out of range");
383 return 0;
384 }
385 return 1;
386}
387
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000388#ifdef HAVE_STRFTIME
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000389#ifdef HAVE_WCSFTIME
390#define time_char wchar_t
391#define format_time wcsftime
392#define time_strlen wcslen
393#else
394#define time_char char
395#define format_time strftime
396#define time_strlen strlen
397#endif
398
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000399static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000400time_strftime(PyObject *self, PyObject *args)
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000401{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000402 PyObject *tup = NULL;
403 struct tm buf;
404 const time_char *fmt;
Victor Stinnerb2904782010-09-29 10:34:19 +0000405#ifdef HAVE_WCSFTIME
406 wchar_t *format;
407#else
408 PyObject *format;
409#endif
Victor Stinneref128102010-10-07 01:00:52 +0000410 PyObject *format_arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000411 size_t fmtlen, buflen;
Victor Stinnerb2904782010-09-29 10:34:19 +0000412 time_char *outbuf = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000413 size_t i;
Victor Stinnerb2904782010-09-29 10:34:19 +0000414 PyObject *ret = NULL;
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000415
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000416 memset((void *) &buf, '\0', sizeof(buf));
Guido van Rossum1f41f841998-04-27 19:04:26 +0000417
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000418 /* Will always expect a unicode string to be passed as format.
419 Given that there's no str type anymore in py3k this seems safe.
420 */
Victor Stinneref128102010-10-07 01:00:52 +0000421 if (!PyArg_ParseTuple(args, "U|O:strftime", &format_arg, &tup))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000422 return NULL;
Thomas Woutersfe385252001-01-19 23:16:56 +0000423
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000424 if (tup == NULL) {
425 time_t tt = time(NULL);
426 buf = *localtime(&tt);
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000427 }
428 else if (!gettmarg(tup, &buf) || !checktm(&buf))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000429 return NULL;
Guido van Rossum10b164a2001-09-25 13:59:01 +0000430
Victor Stinner06ec45e2011-01-08 03:35:36 +0000431#if defined(_MSC_VER) || defined(sun)
Victor Stinner73ea29c2011-01-08 01:56:31 +0000432 if (buf.tm_year + 1900 < 1 || 9999 < buf.tm_year + 1900) {
Victor Stinner6f0e4f92011-03-21 02:14:53 +0100433 PyErr_SetString(PyExc_ValueError,
434 "strftime() requires year in [1; 9999]");
Alexander Belopolsky0dd06f42011-01-08 01:23:02 +0000435 return NULL;
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000436 }
Victor Stinner73ea29c2011-01-08 01:56:31 +0000437#endif
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000438
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000439 /* Normalize tm_isdst just in case someone foolishly implements %Z
440 based on the assumption that tm_isdst falls within the range of
441 [-1, 1] */
442 if (buf.tm_isdst < -1)
443 buf.tm_isdst = -1;
444 else if (buf.tm_isdst > 1)
445 buf.tm_isdst = 1;
Brett Cannond1080a32004-03-02 04:38:10 +0000446
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000447#ifdef HAVE_WCSFTIME
Victor Stinnerbeb4135b2010-10-07 01:02:42 +0000448 format = PyUnicode_AsWideCharString(format_arg, NULL);
Victor Stinnerb2904782010-09-29 10:34:19 +0000449 if (format == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000450 return NULL;
Victor Stinnerb2904782010-09-29 10:34:19 +0000451 fmt = format;
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000452#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000453 /* Convert the unicode string to an ascii one */
Victor Stinneref128102010-10-07 01:00:52 +0000454 format = PyUnicode_AsEncodedString(format_arg, TZNAME_ENCODING, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000455 if (format == NULL)
456 return NULL;
457 fmt = PyBytes_AS_STRING(format);
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000458#endif
Amaury Forgeot d'Arcb5be6d42009-03-02 23:52:57 +0000459
Hirokazu Yamamoto6b0e51a2009-06-03 05:19:18 +0000460#if defined(MS_WINDOWS) && defined(HAVE_WCSFTIME)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000461 /* check that the format string contains only valid directives */
462 for(outbuf = wcschr(fmt, L'%');
463 outbuf != NULL;
464 outbuf = wcschr(outbuf+2, L'%'))
465 {
466 if (outbuf[1]=='#')
467 ++outbuf; /* not documented by python, */
468 if (outbuf[1]=='\0' ||
Senthil Kumaran8f377a32011-04-06 12:54:06 +0800469 !wcschr(L"aAbBcdHIjmMpSUwWxXyYzZ%", outbuf[1]))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000470 {
471 PyErr_SetString(PyExc_ValueError, "Invalid format string");
472 return 0;
473 }
474 }
Amaury Forgeot d'Arcb5be6d42009-03-02 23:52:57 +0000475#endif
476
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000477 fmtlen = time_strlen(fmt);
Guido van Rossumc222ec21999-02-23 00:00:10 +0000478
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000479 /* I hate these functions that presume you know how big the output
480 * will be ahead of time...
481 */
482 for (i = 1024; ; i += i) {
483 outbuf = (time_char *)PyMem_Malloc(i*sizeof(time_char));
484 if (outbuf == NULL) {
Victor Stinnerb2904782010-09-29 10:34:19 +0000485 PyErr_NoMemory();
486 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000487 }
488 buflen = format_time(outbuf, i, fmt, &buf);
489 if (buflen > 0 || i >= 256 * fmtlen) {
490 /* If the buffer is 256 times as long as the format,
491 it's probably not failing for lack of room!
492 More likely, the format yields an empty result,
493 e.g. an empty format, or %Z when the timezone
494 is unknown. */
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000495#ifdef HAVE_WCSFTIME
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000496 ret = PyUnicode_FromWideChar(outbuf, buflen);
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000497#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000498 ret = PyUnicode_Decode(outbuf, buflen,
499 TZNAME_ENCODING, NULL);
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000500#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000501 PyMem_Free(outbuf);
Victor Stinnerb2904782010-09-29 10:34:19 +0000502 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000503 }
504 PyMem_Free(outbuf);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000505#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000506 /* VisualStudio .NET 2005 does this properly */
507 if (buflen == 0 && errno == EINVAL) {
508 PyErr_SetString(PyExc_ValueError, "Invalid format string");
Victor Stinnerb2904782010-09-29 10:34:19 +0000509 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000510 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000511#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000512 }
Victor Stinnerb2904782010-09-29 10:34:19 +0000513#ifdef HAVE_WCSFTIME
514 PyMem_Free(format);
515#else
516 Py_DECREF(format);
517#endif
518 return ret;
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000519}
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000520
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000521#undef time_char
522#undef format_time
523
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000524PyDoc_STRVAR(strftime_doc,
Thomas Woutersfe385252001-01-19 23:16:56 +0000525"strftime(format[, tuple]) -> string\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000526\n\
527Convert a time tuple to a string according to a format specification.\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000528See the library reference manual for formatting codes. When the time tuple\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000529is not present, current time as returned by localtime() is used.");
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000530#endif /* HAVE_STRFTIME */
531
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000532static PyObject *
533time_strptime(PyObject *self, PyObject *args)
534{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000535 PyObject *strptime_module = PyImport_ImportModuleNoBlock("_strptime");
536 PyObject *strptime_result;
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000537
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000538 if (!strptime_module)
539 return NULL;
540 strptime_result = PyObject_CallMethod(strptime_module,
541 "_strptime_time", "O", args);
542 Py_DECREF(strptime_module);
543 return strptime_result;
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000544}
545
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000546
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000547PyDoc_STRVAR(strptime_doc,
Brett Cannon20def8b2003-07-01 05:16:08 +0000548"strptime(string, format) -> struct_time\n\
Martin v. Löwisb3cfc1d2001-12-02 12:27:43 +0000549\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000550Parse a string to a time tuple according to a format specification.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000551See the library reference manual for formatting codes (same as strftime()).");
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000552
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000553static PyObject *
554_asctime(struct tm *timeptr)
555{
556 /* Inspired by Open Group reference implementation available at
557 * http://pubs.opengroup.org/onlinepubs/009695399/functions/asctime.html */
Victor Stinner499dfcf2011-03-21 13:26:24 +0100558 static char wday_name[7][4] = {
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000559 "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
560 };
Victor Stinner499dfcf2011-03-21 13:26:24 +0100561 static char mon_name[12][4] = {
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000562 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
563 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
564 };
Victor Stinner499dfcf2011-03-21 13:26:24 +0100565 return PyUnicode_FromFormat(
566 "%s %s%3d %.2d:%.2d:%.2d %d",
567 wday_name[timeptr->tm_wday],
568 mon_name[timeptr->tm_mon],
569 timeptr->tm_mday, timeptr->tm_hour,
570 timeptr->tm_min, timeptr->tm_sec,
571 1900 + timeptr->tm_year);
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000572}
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000573
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000574static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000575time_asctime(PyObject *self, PyObject *args)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000576{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000577 PyObject *tup = NULL;
578 struct tm buf;
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000579
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000580 if (!PyArg_UnpackTuple(args, "asctime", 0, 1, &tup))
581 return NULL;
582 if (tup == NULL) {
583 time_t tt = time(NULL);
584 buf = *localtime(&tt);
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000585 } else if (!gettmarg(tup, &buf) || !checktm(&buf))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000586 return NULL;
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000587 return _asctime(&buf);
Guido van Rossum9e90a671993-06-24 11:10:19 +0000588}
589
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000590PyDoc_STRVAR(asctime_doc,
Thomas Woutersfe385252001-01-19 23:16:56 +0000591"asctime([tuple]) -> string\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000592\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000593Convert a time tuple to a string, e.g. 'Sat Jun 06 16:26:11 1998'.\n\
594When the time tuple is not present, current time as returned by localtime()\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000595is used.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000596
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000597static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000598time_ctime(PyObject *self, PyObject *args)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000599{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000600 PyObject *ot = NULL;
601 time_t tt;
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000602 struct tm *timeptr;
Guido van Rossum10b164a2001-09-25 13:59:01 +0000603
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000604 if (!PyArg_UnpackTuple(args, "ctime", 0, 1, &ot))
605 return NULL;
606 if (ot == NULL || ot == Py_None)
607 tt = time(NULL);
608 else {
609 double dt = PyFloat_AsDouble(ot);
610 if (PyErr_Occurred())
611 return NULL;
612 tt = _PyTime_DoubleToTimet(dt);
613 if (tt == (time_t)-1 && PyErr_Occurred())
614 return NULL;
615 }
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000616 timeptr = localtime(&tt);
617 if (timeptr == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000618 PyErr_SetString(PyExc_ValueError, "unconvertible time");
Alexander Belopolsky5da468f2011-01-04 17:15:52 +0000619 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000620 }
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000621 return _asctime(timeptr);
Guido van Rossum9e90a671993-06-24 11:10:19 +0000622}
623
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000624PyDoc_STRVAR(ctime_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000625"ctime(seconds) -> string\n\
626\n\
627Convert a time in seconds since the Epoch to a string in local time.\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000628This is equivalent to asctime(localtime(seconds)). When the time tuple is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000629not present, current time as returned by localtime() is used.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000630
Guido van Rossum60cd8131998-03-06 17:16:21 +0000631#ifdef HAVE_MKTIME
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000632static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000633time_mktime(PyObject *self, PyObject *tup)
Guido van Rossum234f9421993-06-17 12:35:49 +0000634{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000635 struct tm buf;
636 time_t tt;
637 if (!gettmarg(tup, &buf))
638 return NULL;
Alexander Belopolskyb7d40d12011-01-11 01:21:25 +0000639 buf.tm_wday = -1; /* sentinel; original value ignored */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000640 tt = mktime(&buf);
Alexander Belopolskyb7d40d12011-01-11 01:21:25 +0000641 /* Return value of -1 does not necessarily mean an error, but tm_wday
Ezio Melotti13925002011-03-16 11:05:33 +0200642 * cannot remain set to -1 if mktime succeeded. */
Alexander Belopolskyb7d40d12011-01-11 01:21:25 +0000643 if (tt == (time_t)(-1) && buf.tm_wday == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000644 PyErr_SetString(PyExc_OverflowError,
645 "mktime argument out of range");
646 return NULL;
647 }
648 return PyFloat_FromDouble((double)tt);
Guido van Rossum234f9421993-06-17 12:35:49 +0000649}
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000650
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000651PyDoc_STRVAR(mktime_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000652"mktime(tuple) -> floating point number\n\
653\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000654Convert a time tuple in local time to seconds since the Epoch.");
Guido van Rossum60cd8131998-03-06 17:16:21 +0000655#endif /* HAVE_MKTIME */
Guido van Rossum234f9421993-06-17 12:35:49 +0000656
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000657#ifdef HAVE_WORKING_TZSET
Martin v. Löwis1a214512008-06-11 05:26:20 +0000658static void PyInit_timezone(PyObject *module);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000659
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000660static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000661time_tzset(PyObject *self, PyObject *unused)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000662{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000663 PyObject* m;
Fred Drake9bb74322002-04-01 14:49:59 +0000664
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000665 m = PyImport_ImportModuleNoBlock("time");
666 if (m == NULL) {
667 return NULL;
668 }
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000669
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000670 tzset();
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000671
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000672 /* Reset timezone, altzone, daylight and tzname */
673 PyInit_timezone(m);
674 Py_DECREF(m);
Tim Peters1b6f7a92004-06-20 02:50:16 +0000675
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000676 Py_INCREF(Py_None);
677 return Py_None;
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000678}
679
680PyDoc_STRVAR(tzset_doc,
R. David Murray4d55bf92010-12-14 00:55:46 +0000681"tzset()\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000682\n\
683Initialize, or reinitialize, the local timezone to the value stored in\n\
684os.environ['TZ']. The TZ environment variable should be specified in\n\
Neal Norwitzdc8e1942004-07-20 22:34:37 +0000685standard Unix timezone format as documented in the tzset man page\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000686(eg. 'US/Eastern', 'Europe/Amsterdam'). Unknown timezones will silently\n\
687fall back to UTC. If the TZ environment variable is not set, the local\n\
688timezone is set to the systems best guess of wallclock time.\n\
689Changing the TZ environment variable without calling tzset *may* change\n\
690the local timezone used by methods such as localtime, but this behaviour\n\
691should not be relied on.");
692#endif /* HAVE_WORKING_TZSET */
693
Martin v. Löwisd218dc12008-04-07 03:17:54 +0000694static void
Martin v. Löwis1a214512008-06-11 05:26:20 +0000695PyInit_timezone(PyObject *m) {
696 /* This code moved from PyInit_time wholesale to allow calling it from
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000697 time_tzset. In the future, some parts of it can be moved back
698 (for platforms that don't HAVE_WORKING_TZSET, when we know what they
699 are), and the extraneous calls to tzset(3) should be removed.
700 I haven't done this yet, as I don't want to change this code as
701 little as possible when introducing the time.tzset and time.tzsetwall
702 methods. This should simply be a method of doing the following once,
703 at the top of this function and removing the call to tzset() from
704 time_tzset():
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000705
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000706 #ifdef HAVE_TZSET
707 tzset()
708 #endif
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000709
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000710 And I'm lazy and hate C so nyer.
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000711 */
Guido van Rossum10b164a2001-09-25 13:59:01 +0000712#if defined(HAVE_TZNAME) && !defined(__GLIBC__) && !defined(__CYGWIN__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000713 PyObject *otz0, *otz1;
714 tzset();
Guido van Rossum26452411998-09-28 22:07:11 +0000715#ifdef PYOS_OS2
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000716 PyModule_AddIntConstant(m, "timezone", _timezone);
Guido van Rossum26452411998-09-28 22:07:11 +0000717#else /* !PYOS_OS2 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000718 PyModule_AddIntConstant(m, "timezone", timezone);
Guido van Rossum26452411998-09-28 22:07:11 +0000719#endif /* PYOS_OS2 */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000720#ifdef HAVE_ALTZONE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000721 PyModule_AddIntConstant(m, "altzone", altzone);
Guido van Rossumb6775db1994-08-01 11:34:53 +0000722#else
Guido van Rossum26452411998-09-28 22:07:11 +0000723#ifdef PYOS_OS2
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000724 PyModule_AddIntConstant(m, "altzone", _timezone-3600);
Guido van Rossum26452411998-09-28 22:07:11 +0000725#else /* !PYOS_OS2 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000726 PyModule_AddIntConstant(m, "altzone", timezone-3600);
Guido van Rossum26452411998-09-28 22:07:11 +0000727#endif /* PYOS_OS2 */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000728#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000729 PyModule_AddIntConstant(m, "daylight", daylight);
730 otz0 = PyUnicode_Decode(tzname[0], strlen(tzname[0]), TZNAME_ENCODING, NULL);
731 otz1 = PyUnicode_Decode(tzname[1], strlen(tzname[1]), TZNAME_ENCODING, NULL);
732 PyModule_AddObject(m, "tzname", Py_BuildValue("(NN)", otz0, otz1));
Guido van Rossum10b164a2001-09-25 13:59:01 +0000733#else /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/
Martin v. Löwis60a5d722002-10-16 20:28:25 +0000734#ifdef HAVE_STRUCT_TM_TM_ZONE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000735 {
Guido van Rossum234f9421993-06-17 12:35:49 +0000736#define YEAR ((time_t)((365 * 24 + 6) * 3600))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000737 time_t t;
738 struct tm *p;
739 long janzone, julyzone;
740 char janname[10], julyname[10];
741 t = (time((time_t *)0) / YEAR) * YEAR;
742 p = localtime(&t);
743 janzone = -p->tm_gmtoff;
744 strncpy(janname, p->tm_zone ? p->tm_zone : " ", 9);
745 janname[9] = '\0';
746 t += YEAR/2;
747 p = localtime(&t);
748 julyzone = -p->tm_gmtoff;
749 strncpy(julyname, p->tm_zone ? p->tm_zone : " ", 9);
750 julyname[9] = '\0';
Guido van Rossum10b164a2001-09-25 13:59:01 +0000751
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000752 if( janzone < julyzone ) {
753 /* DST is reversed in the southern hemisphere */
754 PyModule_AddIntConstant(m, "timezone", julyzone);
755 PyModule_AddIntConstant(m, "altzone", janzone);
756 PyModule_AddIntConstant(m, "daylight",
757 janzone != julyzone);
758 PyModule_AddObject(m, "tzname",
759 Py_BuildValue("(zz)",
760 julyname, janname));
761 } else {
762 PyModule_AddIntConstant(m, "timezone", janzone);
763 PyModule_AddIntConstant(m, "altzone", julyzone);
764 PyModule_AddIntConstant(m, "daylight",
765 janzone != julyzone);
766 PyModule_AddObject(m, "tzname",
767 Py_BuildValue("(zz)",
768 janname, julyname));
769 }
770 }
Guido van Rossume6a4b7b1997-10-08 15:27:56 +0000771#else
Martin v. Löwis60a5d722002-10-16 20:28:25 +0000772#endif /* HAVE_STRUCT_TM_TM_ZONE */
Tim Peters26ae7cd2001-03-20 03:26:49 +0000773#ifdef __CYGWIN__
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000774 tzset();
775 PyModule_AddIntConstant(m, "timezone", _timezone);
776 PyModule_AddIntConstant(m, "altzone", _timezone-3600);
777 PyModule_AddIntConstant(m, "daylight", _daylight);
778 PyModule_AddObject(m, "tzname",
779 Py_BuildValue("(zz)", _tzname[0], _tzname[1]));
Tim Peters26ae7cd2001-03-20 03:26:49 +0000780#endif /* __CYGWIN__ */
Guido van Rossum10b164a2001-09-25 13:59:01 +0000781#endif /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000782}
783
784
785static PyMethodDef time_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000786 {"time", time_time, METH_NOARGS, time_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000787#ifdef HAVE_CLOCK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000788 {"clock", time_clock, METH_NOARGS, clock_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000789#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000790 {"sleep", time_sleep, METH_VARARGS, sleep_doc},
791 {"gmtime", time_gmtime, METH_VARARGS, gmtime_doc},
792 {"localtime", time_localtime, METH_VARARGS, localtime_doc},
793 {"asctime", time_asctime, METH_VARARGS, asctime_doc},
794 {"ctime", time_ctime, METH_VARARGS, ctime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000795#ifdef HAVE_MKTIME
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000796 {"mktime", time_mktime, METH_O, mktime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000797#endif
798#ifdef HAVE_STRFTIME
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000799 {"strftime", time_strftime, METH_VARARGS, strftime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000800#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000801 {"strptime", time_strptime, METH_VARARGS, strptime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000802#ifdef HAVE_WORKING_TZSET
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000803 {"tzset", time_tzset, METH_NOARGS, tzset_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000804#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000805 {NULL, NULL} /* sentinel */
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000806};
807
808
809PyDoc_STRVAR(module_doc,
810"This module provides various functions to manipulate time values.\n\
811\n\
812There are two standard representations of time. One is the number\n\
813of seconds since the Epoch, in UTC (a.k.a. GMT). It may be an integer\n\
814or a floating point number (to represent fractions of seconds).\n\
815The Epoch is system-defined; on Unix, it is generally January 1st, 1970.\n\
816The actual value can be retrieved by calling gmtime(0).\n\
817\n\
818The other representation is a tuple of 9 integers giving local time.\n\
819The tuple items are:\n\
Alexander Belopolsky03163ac2011-05-02 12:20:52 -0400820 year (including century, e.g. 1998)\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000821 month (1-12)\n\
822 day (1-31)\n\
823 hours (0-23)\n\
824 minutes (0-59)\n\
825 seconds (0-59)\n\
826 weekday (0-6, Monday is 0)\n\
827 Julian day (day in the year, 1-366)\n\
828 DST (Daylight Savings Time) flag (-1, 0 or 1)\n\
829If the DST flag is 0, the time is given in the regular time zone;\n\
830if it is 1, the time is given in the DST time zone;\n\
831if it is -1, mktime() should guess based on the date and time.\n\
832\n\
833Variables:\n\
834\n\
835timezone -- difference in seconds between UTC and local standard time\n\
836altzone -- difference in seconds between UTC and local DST time\n\
837daylight -- whether local time should reflect DST\n\
838tzname -- tuple of (standard time zone name, DST time zone name)\n\
839\n\
840Functions:\n\
841\n\
842time() -- return current time in seconds since the Epoch as a float\n\
843clock() -- return CPU time since process start as a float\n\
844sleep() -- delay for a number of seconds given as a float\n\
845gmtime() -- convert seconds since Epoch to UTC tuple\n\
846localtime() -- convert seconds since Epoch to local time tuple\n\
847asctime() -- convert time tuple to string\n\
848ctime() -- convert time in seconds to string\n\
849mktime() -- convert local time tuple to seconds since Epoch\n\
850strftime() -- convert time tuple to string according to format specification\n\
851strptime() -- parse string to time tuple according to format specification\n\
852tzset() -- change the local timezone");
853
854
Martin v. Löwis1a214512008-06-11 05:26:20 +0000855
856static struct PyModuleDef timemodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000857 PyModuleDef_HEAD_INIT,
858 "time",
859 module_doc,
860 -1,
861 time_methods,
862 NULL,
863 NULL,
864 NULL,
865 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +0000866};
867
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000868PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +0000869PyInit_time(void)
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000870{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000871 PyObject *m;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000872 m = PyModule_Create(&timemodule);
873 if (m == NULL)
874 return NULL;
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000875
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000876 /* Set, or reset, module variables like time.timezone */
877 PyInit_timezone(m);
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000878
Mark Hammond975e3922002-07-16 01:29:19 +0000879#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000880 /* Helper to allow interrupts for Windows.
881 If Ctrl+C event delivered while not sleeping
882 it will be ignored.
883 */
884 main_thread = PyThread_get_thread_ident();
885 hInterruptEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
886 SetConsoleCtrlHandler( PyCtrlHandler, TRUE);
Mark Hammond975e3922002-07-16 01:29:19 +0000887#endif /* MS_WINDOWS */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000888 if (!initialized) {
889 PyStructSequence_InitType(&StructTimeType,
890 &struct_time_type_desc);
891 }
892 Py_INCREF(&StructTimeType);
893 PyModule_AddObject(m, "struct_time", (PyObject*) &StructTimeType);
894 initialized = 1;
895 return m;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000896}
897
Guido van Rossumb6775db1994-08-01 11:34:53 +0000898static double
Thomas Woutersf3f33dc2000-07-21 06:00:07 +0000899floattime(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000900{
Alexander Belopolsky6fc4ade2010-08-05 17:34:27 +0000901 _PyTime_timeval t;
902 _PyTime_gettimeofday(&t);
903 return (double)t.tv_sec + t.tv_usec*0.000001;
Guido van Rossum426035c1991-02-19 12:27:35 +0000904}
905
Guido van Rossumb6775db1994-08-01 11:34:53 +0000906
907/* Implement floatsleep() for various platforms.
908 When interrupted (or when another error occurs), return -1 and
909 set an exception; else return 0. */
910
911static int
Guido van Rossuma320fd31995-03-09 12:14:15 +0000912floatsleep(double secs)
Guido van Rossum426035c1991-02-19 12:27:35 +0000913{
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000914/* XXX Should test for MS_WINDOWS first! */
Skip Montanaroeb33e5a2007-08-17 12:57:41 +0000915#if defined(HAVE_SELECT) && !defined(__EMX__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000916 struct timeval t;
917 double frac;
918 frac = fmod(secs, 1.0);
919 secs = floor(secs);
920 t.tv_sec = (long)secs;
921 t.tv_usec = (long)(frac*1000000.0);
922 Py_BEGIN_ALLOW_THREADS
923 if (select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &t) != 0) {
Guido van Rossum09cbb011999-11-08 15:32:27 +0000924#ifdef EINTR
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000925 if (errno != EINTR) {
Guido van Rossum09cbb011999-11-08 15:32:27 +0000926#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000927 if (1) {
Guido van Rossum09cbb011999-11-08 15:32:27 +0000928#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000929 Py_BLOCK_THREADS
930 PyErr_SetFromErrno(PyExc_IOError);
931 return -1;
932 }
933 }
934 Py_END_ALLOW_THREADS
Martin v. Löwis02af9642002-01-16 11:04:06 +0000935#elif defined(__WATCOMC__) && !defined(__QNX__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000936 /* XXX Can't interrupt this sleep */
937 Py_BEGIN_ALLOW_THREADS
938 delay((int)(secs * 1000 + 0.5)); /* delay() uses milliseconds */
939 Py_END_ALLOW_THREADS
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000940#elif defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000941 {
942 double millisecs = secs * 1000.0;
943 unsigned long ul_millis;
Tim Peters513a1cd2003-01-19 04:54:58 +0000944
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000945 if (millisecs > (double)ULONG_MAX) {
946 PyErr_SetString(PyExc_OverflowError,
947 "sleep length is too large");
948 return -1;
949 }
950 Py_BEGIN_ALLOW_THREADS
951 /* Allow sleep(0) to maintain win32 semantics, and as decreed
952 * by Guido, only the main thread can be interrupted.
953 */
954 ul_millis = (unsigned long)millisecs;
955 if (ul_millis == 0 ||
956 main_thread != PyThread_get_thread_ident())
957 Sleep(ul_millis);
958 else {
959 DWORD rc;
960 ResetEvent(hInterruptEvent);
961 rc = WaitForSingleObject(hInterruptEvent, ul_millis);
962 if (rc == WAIT_OBJECT_0) {
963 /* Yield to make sure real Python signal
964 * handler called.
965 */
966 Sleep(1);
967 Py_BLOCK_THREADS
968 errno = EINTR;
969 PyErr_SetFromErrno(PyExc_IOError);
970 return -1;
971 }
972 }
973 Py_END_ALLOW_THREADS
974 }
Martin v. Löwis02af9642002-01-16 11:04:06 +0000975#elif defined(PYOS_OS2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000976 /* This Sleep *IS* Interruptable by Exceptions */
977 Py_BEGIN_ALLOW_THREADS
978 if (DosSleep(secs * 1000) != NO_ERROR) {
979 Py_BLOCK_THREADS
980 PyErr_SetFromErrno(PyExc_IOError);
981 return -1;
982 }
983 Py_END_ALLOW_THREADS
Martin v. Löwis02af9642002-01-16 11:04:06 +0000984#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000985 /* XXX Can't interrupt this sleep */
986 Py_BEGIN_ALLOW_THREADS
987 sleep((int)secs);
988 Py_END_ALLOW_THREADS
Martin v. Löwis02af9642002-01-16 11:04:06 +0000989#endif
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000990
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000991 return 0;
Guido van Rossum80c9d881991-04-16 08:47:51 +0000992}