blob: 46c90ecdc971194c4148dc29605d657e480e94ff [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
Guido van Rossumcfbaecc1998-08-25 14:51:12 +000069/* For Y2K check */
70static PyObject *moddict;
71
Barry Warsaw9a2a8a81996-12-06 23:32:14 +000072static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000073time_time(PyObject *self, PyObject *unused)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000074{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000075 double secs;
76 secs = floattime();
77 if (secs == 0.0) {
78 PyErr_SetFromErrno(PyExc_IOError);
79 return NULL;
80 }
81 return PyFloat_FromDouble(secs);
Guido van Rossumb6775db1994-08-01 11:34:53 +000082}
83
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000084PyDoc_STRVAR(time_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +000085"time() -> floating point number\n\
86\n\
87Return the current time in seconds since the Epoch.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000088Fractions of a second may be present if the system clock provides them.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +000089
Guido van Rossumb6775db1994-08-01 11:34:53 +000090#ifdef HAVE_CLOCK
91
92#ifndef CLOCKS_PER_SEC
Guido van Rossum1b66a4f1996-02-25 04:50:33 +000093#ifdef CLK_TCK
94#define CLOCKS_PER_SEC CLK_TCK
95#else
Guido van Rossumb6775db1994-08-01 11:34:53 +000096#define CLOCKS_PER_SEC 1000000
97#endif
Guido van Rossum1b66a4f1996-02-25 04:50:33 +000098#endif
Guido van Rossumb6775db1994-08-01 11:34:53 +000099
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000100static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000101time_clock(PyObject *self, PyObject *unused)
Guido van Rossumb6775db1994-08-01 11:34:53 +0000102{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000103 return PyFloat_FromDouble(((double)clock()) / CLOCKS_PER_SEC);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000104}
Guido van Rossumb6775db1994-08-01 11:34:53 +0000105#endif /* HAVE_CLOCK */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000106
Thomas Wouters477c8d52006-05-27 19:21:47 +0000107#if defined(MS_WINDOWS) && !defined(__BORLANDC__)
Mark Hammond7ba5e812002-02-12 04:02:33 +0000108/* Due to Mark Hammond and Tim Peters */
Guido van Rossum3917c221997-04-02 05:35:28 +0000109static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000110time_clock(PyObject *self, PyObject *unused)
Guido van Rossum3917c221997-04-02 05:35:28 +0000111{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000112 static LARGE_INTEGER ctrStart;
113 static double divisor = 0.0;
114 LARGE_INTEGER now;
115 double diff;
Guido van Rossum3917c221997-04-02 05:35:28 +0000116
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000117 if (divisor == 0.0) {
118 LARGE_INTEGER freq;
119 QueryPerformanceCounter(&ctrStart);
120 if (!QueryPerformanceFrequency(&freq) || freq.QuadPart == 0) {
121 /* Unlikely to happen - this works on all intel
122 machines at least! Revert to clock() */
123 return PyFloat_FromDouble(((double)clock()) /
124 CLOCKS_PER_SEC);
125 }
126 divisor = (double)freq.QuadPart;
127 }
128 QueryPerformanceCounter(&now);
129 diff = (double)(now.QuadPart - ctrStart.QuadPart);
130 return PyFloat_FromDouble(diff / divisor);
Guido van Rossum3917c221997-04-02 05:35:28 +0000131}
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000132
Guido van Rossum3917c221997-04-02 05:35:28 +0000133#define HAVE_CLOCK /* So it gets included in the methods */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000134#endif /* MS_WINDOWS && !defined(__BORLANDC__) */
Guido van Rossum3917c221997-04-02 05:35:28 +0000135
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000136#ifdef HAVE_CLOCK
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000137PyDoc_STRVAR(clock_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000138"clock() -> floating point number\n\
139\n\
140Return the CPU time or real time since the start of the process or since\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000141the first call to clock(). This has as much precision as the system\n\
142records.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000143#endif
144
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000145static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000146time_sleep(PyObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000147{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000148 double secs;
149 if (!PyArg_ParseTuple(args, "d:sleep", &secs))
150 return NULL;
151 if (floatsleep(secs) != 0)
152 return NULL;
153 Py_INCREF(Py_None);
154 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000155}
156
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000157PyDoc_STRVAR(sleep_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000158"sleep(seconds)\n\
159\n\
160Delay execution for a given number of seconds. The argument may be\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000161a floating point number for subsecond precision.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000162
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000163static PyStructSequence_Field struct_time_type_fields[] = {
Alexander Belopolsky69f3fd02010-06-05 15:04:51 +0000164 {"tm_year", "year, for example, 1993"},
165 {"tm_mon", "month of year, range [1, 12]"},
166 {"tm_mday", "day of month, range [1, 31]"},
167 {"tm_hour", "hours, range [0, 23]"},
168 {"tm_min", "minutes, range [0, 59]"},
169 {"tm_sec", "seconds, range [0, 61])"},
170 {"tm_wday", "day of week, range [0, 6], Monday is 0"},
171 {"tm_yday", "day of year, range [1, 366]"},
172 {"tm_isdst", "1 if summer time is in effect, 0 if not, and -1 if unknown"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000173 {0}
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000174};
175
176static PyStructSequence_Desc struct_time_type_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000177 "time.struct_time",
Alexander Belopolsky69f3fd02010-06-05 15:04:51 +0000178 "The time value as returned by gmtime(), localtime(), and strptime(), and\n"
179 " accepted by asctime(), mktime() and strftime(). May be considered as a\n"
180 " sequence of 9 integers.\n\n"
181 " Note that several fields' values are not the same as those defined by\n"
182 " the C language standard for struct tm. For example, the value of the\n"
183 " field tm_year is the actual year, not year - 1900. See individual\n"
184 " fields' descriptions for details.",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000185 struct_time_type_fields,
186 9,
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000187};
Tim Peters9ad4b682002-02-13 05:14:18 +0000188
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000189static int initialized;
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000190static PyTypeObject StructTimeType;
191
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000192static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000193tmtotuple(struct tm *p)
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000194{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000195 PyObject *v = PyStructSequence_New(&StructTimeType);
196 if (v == NULL)
197 return NULL;
Tim Peters9ad4b682002-02-13 05:14:18 +0000198
Christian Heimes217cfd12007-12-02 14:31:20 +0000199#define SET(i,val) PyStructSequence_SET_ITEM(v, i, PyLong_FromLong((long) val))
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000200
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000201 SET(0, p->tm_year + 1900);
202 SET(1, p->tm_mon + 1); /* Want January == 1 */
203 SET(2, p->tm_mday);
204 SET(3, p->tm_hour);
205 SET(4, p->tm_min);
206 SET(5, p->tm_sec);
207 SET(6, (p->tm_wday + 6) % 7); /* Want Monday == 0 */
208 SET(7, p->tm_yday + 1); /* Want January, 1 == 1 */
209 SET(8, p->tm_isdst);
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000210#undef SET
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000211 if (PyErr_Occurred()) {
212 Py_XDECREF(v);
213 return NULL;
214 }
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000215
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000216 return v;
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000217}
218
219static PyObject *
Brett Cannon298c3802004-06-19 20:48:43 +0000220time_convert(double when, struct tm * (*function)(const time_t *))
Guido van Rossum234f9421993-06-17 12:35:49 +0000221{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000222 struct tm *p;
223 time_t whent = _PyTime_DoubleToTimet(when);
Brett Cannon298c3802004-06-19 20:48:43 +0000224
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000225 if (whent == (time_t)-1 && PyErr_Occurred())
226 return NULL;
227 errno = 0;
228 p = function(&whent);
229 if (p == NULL) {
Guido van Rossum6e8583d1996-10-08 14:19:52 +0000230#ifdef EINVAL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000231 if (errno == 0)
232 errno = EINVAL;
Guido van Rossum6e8583d1996-10-08 14:19:52 +0000233#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000234 return PyErr_SetFromErrno(PyExc_ValueError);
235 }
236 return tmtotuple(p);
Guido van Rossum234f9421993-06-17 12:35:49 +0000237}
238
Fred Drakef901abd2004-08-03 17:58:55 +0000239/* Parse arg tuple that can contain an optional float-or-None value;
240 format needs to be "|O:name".
241 Returns non-zero on success (parallels PyArg_ParseTuple).
242*/
243static int
244parse_time_double_args(PyObject *args, char *format, double *pwhen)
245{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000246 PyObject *ot = NULL;
Fred Drakef901abd2004-08-03 17:58:55 +0000247
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000248 if (!PyArg_ParseTuple(args, format, &ot))
249 return 0;
250 if (ot == NULL || ot == Py_None)
251 *pwhen = floattime();
252 else {
253 double when = PyFloat_AsDouble(ot);
254 if (PyErr_Occurred())
255 return 0;
256 *pwhen = when;
257 }
258 return 1;
Fred Drakef901abd2004-08-03 17:58:55 +0000259}
260
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000261static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000262time_gmtime(PyObject *self, PyObject *args)
Guido van Rossum234f9421993-06-17 12:35:49 +0000263{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000264 double when;
265 if (!parse_time_double_args(args, "|O:gmtime", &when))
266 return NULL;
267 return time_convert(when, gmtime);
Guido van Rossum234f9421993-06-17 12:35:49 +0000268}
269
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000270PyDoc_STRVAR(gmtime_doc,
Christian Heimes9a371592007-12-28 14:08:13 +0000271"gmtime([seconds]) -> (tm_year, tm_mon, tm_mday, tm_hour, tm_min,\n\
Fred Drake193a3f62002-03-12 21:38:49 +0000272 tm_sec, tm_wday, tm_yday, tm_isdst)\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000273\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000274Convert seconds since the Epoch to a time tuple expressing UTC (a.k.a.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000275GMT). When 'seconds' is not passed in, convert the current time instead.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000276
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000277static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000278time_localtime(PyObject *self, PyObject *args)
Guido van Rossum234f9421993-06-17 12:35:49 +0000279{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000280 double when;
281 if (!parse_time_double_args(args, "|O:localtime", &when))
282 return NULL;
283 return time_convert(when, localtime);
Guido van Rossum234f9421993-06-17 12:35:49 +0000284}
285
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000286PyDoc_STRVAR(localtime_doc,
Christian Heimes9a371592007-12-28 14:08:13 +0000287"localtime([seconds]) -> (tm_year,tm_mon,tm_mday,tm_hour,tm_min,\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000288 tm_sec,tm_wday,tm_yday,tm_isdst)\n\
Martin v. Löwisb3cfc1d2001-12-02 12:27:43 +0000289\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000290Convert seconds since the Epoch to a time tuple expressing local time.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000291When 'seconds' is not passed in, convert the current time instead.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000292
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000293/* Convert 9-item tuple to tm structure. Return 1 on success, set
294 * an exception and return 0 on error.
295 */
Guido van Rossum9e90a671993-06-24 11:10:19 +0000296static int
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000297gettmarg(PyObject *args, struct tm *p)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000298{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000299 int y;
Guido van Rossumcfbaecc1998-08-25 14:51:12 +0000300
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000301 memset((void *) p, '\0', sizeof(struct tm));
Guido van Rossumb9081262007-08-25 03:14:09 +0000302
Alexander Belopolsky610e5442011-01-06 21:57:06 +0000303 if (!PyTuple_Check(args)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000304 PyErr_SetString(PyExc_TypeError,
305 "Tuple or struct_time argument required");
306 return 0;
307 }
Skip Montanaro41cfce92007-08-24 21:11:00 +0000308
Alexander Belopolsky610e5442011-01-06 21:57:06 +0000309 if (!PyArg_ParseTuple(args, "iiiiiiiii",
310 &y, &p->tm_mon, &p->tm_mday,
311 &p->tm_hour, &p->tm_min, &p->tm_sec,
312 &p->tm_wday, &p->tm_yday, &p->tm_isdst))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000313 return 0;
Skip Montanaro41cfce92007-08-24 21:11:00 +0000314
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000315 /* If year is specified with less than 4 digits, its interpretation
316 * depends on the accept2dyear value.
317 *
318 * If accept2dyear is true (default), a backward compatibility behavior is
319 * invoked as follows:
320 *
321 * - for 2-digit year, century is guessed according to POSIX rules for
322 * %y strptime format: 21st century for y < 69, 20th century
323 * otherwise. A deprecation warning is issued when century
324 * information is guessed in this way.
325 *
326 * - for 3-digit or negative year, a ValueError exception is raised.
327 *
328 * If accept2dyear is false (set by the program or as a result of a
329 * non-empty value assigned to PYTHONY2K environment variable) all year
330 * values are interpreted as given.
Alexander Belopolskya6867252011-01-05 23:00:47 +0000331 */
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000332 if (y < 1000) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000333 PyObject *accept = PyDict_GetItemString(moddict,
334 "accept2dyear");
Alexander Belopolsky0dd06f42011-01-08 01:23:02 +0000335 if (accept != NULL) {
336 int acceptval = PyObject_IsTrue(accept);
337 if (acceptval == -1)
Alexander Belopolskya6867252011-01-05 23:00:47 +0000338 return 0;
Alexander Belopolsky0dd06f42011-01-08 01:23:02 +0000339 if (acceptval) {
340 if (0 <= y && y < 69)
341 y += 2000;
342 else if (69 <= y && y < 100)
343 y += 1900;
344 else {
345 PyErr_SetString(PyExc_ValueError,
346 "year out of range");
347 return 0;
348 }
349 if (PyErr_WarnEx(PyExc_DeprecationWarning,
350 "Century info guessed for a 2-digit year.", 1) != 0)
351 return 0;
Alexander Belopolskya6867252011-01-05 23:00:47 +0000352 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000353 }
Alexander Belopolsky0dd06f42011-01-08 01:23:02 +0000354 else
355 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000356 }
357 p->tm_year = y - 1900;
358 p->tm_mon--;
359 p->tm_wday = (p->tm_wday + 1) % 7;
360 p->tm_yday--;
361 return 1;
Guido van Rossum9e90a671993-06-24 11:10:19 +0000362}
363
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000364/* Check values of the struct tm fields before it is passed to strftime() and
365 * asctime(). Return 1 if all values are valid, otherwise set an exception
366 * and returns 0.
367 */
Victor Stinneref128102010-10-07 01:00:52 +0000368static int
369checktm(struct tm* buf)
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000370{
Victor Stinneref128102010-10-07 01:00:52 +0000371 /* Checks added to make sure strftime() and asctime() does not crash Python by
372 indexing blindly into some array for a textual representation
373 by some bad index (fixes bug #897625 and #6608).
374
375 Also support values of zero from Python code for arguments in which
376 that is out of range by forcing that value to the lowest value that
377 is valid (fixed bug #1520914).
378
379 Valid ranges based on what is allowed in struct tm:
380
381 - tm_year: [0, max(int)] (1)
382 - tm_mon: [0, 11] (2)
383 - tm_mday: [1, 31]
384 - tm_hour: [0, 23]
385 - tm_min: [0, 59]
386 - tm_sec: [0, 60]
387 - tm_wday: [0, 6] (1)
388 - tm_yday: [0, 365] (2)
389 - tm_isdst: [-max(int), max(int)]
390
391 (1) gettmarg() handles bounds-checking.
392 (2) Python's acceptable range is one greater than the range in C,
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000393 thus need to check against automatic decrement by gettmarg().
394 */
395 if (buf->tm_mon == -1)
396 buf->tm_mon = 0;
397 else if (buf->tm_mon < 0 || buf->tm_mon > 11) {
398 PyErr_SetString(PyExc_ValueError, "month out of range");
399 return 0;
400 }
401 if (buf->tm_mday == 0)
402 buf->tm_mday = 1;
403 else if (buf->tm_mday < 0 || buf->tm_mday > 31) {
404 PyErr_SetString(PyExc_ValueError, "day of month out of range");
405 return 0;
406 }
407 if (buf->tm_hour < 0 || buf->tm_hour > 23) {
408 PyErr_SetString(PyExc_ValueError, "hour out of range");
409 return 0;
410 }
411 if (buf->tm_min < 0 || buf->tm_min > 59) {
412 PyErr_SetString(PyExc_ValueError, "minute out of range");
413 return 0;
414 }
415 if (buf->tm_sec < 0 || buf->tm_sec > 61) {
416 PyErr_SetString(PyExc_ValueError, "seconds out of range");
417 return 0;
418 }
419 /* tm_wday does not need checking of its upper-bound since taking
420 ``% 7`` in gettmarg() automatically restricts the range. */
421 if (buf->tm_wday < 0) {
422 PyErr_SetString(PyExc_ValueError, "day of week out of range");
423 return 0;
424 }
425 if (buf->tm_yday == -1)
426 buf->tm_yday = 0;
427 else if (buf->tm_yday < 0 || buf->tm_yday > 365) {
428 PyErr_SetString(PyExc_ValueError, "day of year out of range");
429 return 0;
430 }
431 return 1;
432}
433
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000434#ifdef HAVE_STRFTIME
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000435#ifdef HAVE_WCSFTIME
436#define time_char wchar_t
437#define format_time wcsftime
438#define time_strlen wcslen
439#else
440#define time_char char
441#define format_time strftime
442#define time_strlen strlen
443#endif
444
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000445static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000446time_strftime(PyObject *self, PyObject *args)
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000447{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000448 PyObject *tup = NULL;
449 struct tm buf;
450 const time_char *fmt;
Victor Stinnerb2904782010-09-29 10:34:19 +0000451#ifdef HAVE_WCSFTIME
452 wchar_t *format;
453#else
454 PyObject *format;
455#endif
Victor Stinneref128102010-10-07 01:00:52 +0000456 PyObject *format_arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000457 size_t fmtlen, buflen;
Victor Stinnerb2904782010-09-29 10:34:19 +0000458 time_char *outbuf = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000459 size_t i;
Victor Stinnerb2904782010-09-29 10:34:19 +0000460 PyObject *ret = NULL;
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000461
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000462 memset((void *) &buf, '\0', sizeof(buf));
Guido van Rossum1f41f841998-04-27 19:04:26 +0000463
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000464 /* Will always expect a unicode string to be passed as format.
465 Given that there's no str type anymore in py3k this seems safe.
466 */
Victor Stinneref128102010-10-07 01:00:52 +0000467 if (!PyArg_ParseTuple(args, "U|O:strftime", &format_arg, &tup))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000468 return NULL;
Thomas Woutersfe385252001-01-19 23:16:56 +0000469
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000470 if (tup == NULL) {
471 time_t tt = time(NULL);
472 buf = *localtime(&tt);
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000473 }
474 else if (!gettmarg(tup, &buf) || !checktm(&buf))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000475 return NULL;
Guido van Rossum10b164a2001-09-25 13:59:01 +0000476
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000477 /* XXX: Reportedly, some systems have issues formating dates prior to year
Alexander Belopolskyb8bb4662011-01-08 00:13:34 +0000478 * 1000. These systems should be identified and this check should be
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000479 * moved to appropriate system specific section below. */
Alexander Belopolskyb8bb4662011-01-08 00:13:34 +0000480 if (buf.tm_year < -900) {
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000481 PyErr_Format(PyExc_ValueError, "year=%d is before 1900; "
482 "the strftime() method requires year >= 1900",
483 buf.tm_year + 1900);
Alexander Belopolsky0dd06f42011-01-08 01:23:02 +0000484 return NULL;
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000485 }
486
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000487 /* Normalize tm_isdst just in case someone foolishly implements %Z
488 based on the assumption that tm_isdst falls within the range of
489 [-1, 1] */
490 if (buf.tm_isdst < -1)
491 buf.tm_isdst = -1;
492 else if (buf.tm_isdst > 1)
493 buf.tm_isdst = 1;
Brett Cannond1080a32004-03-02 04:38:10 +0000494
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000495#ifdef HAVE_WCSFTIME
Victor Stinnerbeb4135b2010-10-07 01:02:42 +0000496 format = PyUnicode_AsWideCharString(format_arg, NULL);
Victor Stinnerb2904782010-09-29 10:34:19 +0000497 if (format == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000498 return NULL;
Victor Stinnerb2904782010-09-29 10:34:19 +0000499 fmt = format;
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000500#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000501 /* Convert the unicode string to an ascii one */
Victor Stinneref128102010-10-07 01:00:52 +0000502 format = PyUnicode_AsEncodedString(format_arg, TZNAME_ENCODING, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000503 if (format == NULL)
504 return NULL;
505 fmt = PyBytes_AS_STRING(format);
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000506#endif
Amaury Forgeot d'Arcb5be6d42009-03-02 23:52:57 +0000507
Hirokazu Yamamoto6b0e51a2009-06-03 05:19:18 +0000508#if defined(MS_WINDOWS) && defined(HAVE_WCSFTIME)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000509 /* check that the format string contains only valid directives */
510 for(outbuf = wcschr(fmt, L'%');
511 outbuf != NULL;
512 outbuf = wcschr(outbuf+2, L'%'))
513 {
514 if (outbuf[1]=='#')
515 ++outbuf; /* not documented by python, */
516 if (outbuf[1]=='\0' ||
517 !wcschr(L"aAbBcdfHIjmMpSUwWxXyYzZ%", outbuf[1]))
518 {
519 PyErr_SetString(PyExc_ValueError, "Invalid format string");
520 return 0;
521 }
522 }
Amaury Forgeot d'Arcb5be6d42009-03-02 23:52:57 +0000523#endif
524
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000525 fmtlen = time_strlen(fmt);
Guido van Rossumc222ec21999-02-23 00:00:10 +0000526
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000527 /* I hate these functions that presume you know how big the output
528 * will be ahead of time...
529 */
530 for (i = 1024; ; i += i) {
531 outbuf = (time_char *)PyMem_Malloc(i*sizeof(time_char));
532 if (outbuf == NULL) {
Victor Stinnerb2904782010-09-29 10:34:19 +0000533 PyErr_NoMemory();
534 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000535 }
536 buflen = format_time(outbuf, i, fmt, &buf);
537 if (buflen > 0 || i >= 256 * fmtlen) {
538 /* If the buffer is 256 times as long as the format,
539 it's probably not failing for lack of room!
540 More likely, the format yields an empty result,
541 e.g. an empty format, or %Z when the timezone
542 is unknown. */
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000543#ifdef HAVE_WCSFTIME
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000544 ret = PyUnicode_FromWideChar(outbuf, buflen);
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000545#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000546 ret = PyUnicode_Decode(outbuf, buflen,
547 TZNAME_ENCODING, NULL);
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000548#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000549 PyMem_Free(outbuf);
Victor Stinnerb2904782010-09-29 10:34:19 +0000550 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000551 }
552 PyMem_Free(outbuf);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000553#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000554 /* VisualStudio .NET 2005 does this properly */
555 if (buflen == 0 && errno == EINVAL) {
556 PyErr_SetString(PyExc_ValueError, "Invalid format string");
Victor Stinnerb2904782010-09-29 10:34:19 +0000557 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000558 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000559#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000560 }
Victor Stinnerb2904782010-09-29 10:34:19 +0000561#ifdef HAVE_WCSFTIME
562 PyMem_Free(format);
563#else
564 Py_DECREF(format);
565#endif
566 return ret;
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000567}
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000568
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000569#undef time_char
570#undef format_time
571
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000572PyDoc_STRVAR(strftime_doc,
Thomas Woutersfe385252001-01-19 23:16:56 +0000573"strftime(format[, tuple]) -> string\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000574\n\
575Convert a time tuple to a string according to a format specification.\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000576See the library reference manual for formatting codes. When the time tuple\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000577is not present, current time as returned by localtime() is used.");
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000578#endif /* HAVE_STRFTIME */
579
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000580static PyObject *
581time_strptime(PyObject *self, PyObject *args)
582{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000583 PyObject *strptime_module = PyImport_ImportModuleNoBlock("_strptime");
584 PyObject *strptime_result;
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000585
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000586 if (!strptime_module)
587 return NULL;
588 strptime_result = PyObject_CallMethod(strptime_module,
589 "_strptime_time", "O", args);
590 Py_DECREF(strptime_module);
591 return strptime_result;
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000592}
593
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000594
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000595PyDoc_STRVAR(strptime_doc,
Brett Cannon20def8b2003-07-01 05:16:08 +0000596"strptime(string, format) -> struct_time\n\
Martin v. Löwisb3cfc1d2001-12-02 12:27:43 +0000597\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000598Parse a string to a time tuple according to a format specification.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000599See the library reference manual for formatting codes (same as strftime()).");
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000600
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000601static PyObject *
602_asctime(struct tm *timeptr)
603{
604 /* Inspired by Open Group reference implementation available at
605 * http://pubs.opengroup.org/onlinepubs/009695399/functions/asctime.html */
606 static char wday_name[7][3] = {
607 "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
608 };
609 static char mon_name[12][3] = {
610 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
611 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
612 };
613 char buf[20]; /* 'Sun Sep 16 01:03:52\0' */
614 int n;
615
Alexander Belopolskyecbb8dc2011-01-06 16:45:25 +0000616 n = PyOS_snprintf(buf, sizeof(buf), "%.3s %.3s%3d %.2d:%.2d:%.2d",
617 wday_name[timeptr->tm_wday],
618 mon_name[timeptr->tm_mon],
619 timeptr->tm_mday, timeptr->tm_hour,
620 timeptr->tm_min, timeptr->tm_sec);
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000621 /* XXX: since the fields used by snprintf above are validated in checktm,
622 * the following condition should never trigger. We keep the check because
623 * historically fixed size buffer used in asctime was the source of
624 * crashes. */
625 if (n + 1 != sizeof(buf)) {
626 PyErr_SetString(PyExc_ValueError, "unconvertible time");
627 return NULL;
628 }
629
630 return PyUnicode_FromFormat("%s %d", buf, 1900 + timeptr->tm_year);
631}
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000632
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000633static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000634time_asctime(PyObject *self, PyObject *args)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000635{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000636 PyObject *tup = NULL;
637 struct tm buf;
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000638
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000639 if (!PyArg_UnpackTuple(args, "asctime", 0, 1, &tup))
640 return NULL;
641 if (tup == NULL) {
642 time_t tt = time(NULL);
643 buf = *localtime(&tt);
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000644 } else if (!gettmarg(tup, &buf) || !checktm(&buf))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000645 return NULL;
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000646 return _asctime(&buf);
Guido van Rossum9e90a671993-06-24 11:10:19 +0000647}
648
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000649PyDoc_STRVAR(asctime_doc,
Thomas Woutersfe385252001-01-19 23:16:56 +0000650"asctime([tuple]) -> string\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000651\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000652Convert a time tuple to a string, e.g. 'Sat Jun 06 16:26:11 1998'.\n\
653When the time tuple is not present, current time as returned by localtime()\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000654is used.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000655
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000656static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000657time_ctime(PyObject *self, PyObject *args)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000658{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000659 PyObject *ot = NULL;
660 time_t tt;
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000661 struct tm *timeptr;
Guido van Rossum10b164a2001-09-25 13:59:01 +0000662
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000663 if (!PyArg_UnpackTuple(args, "ctime", 0, 1, &ot))
664 return NULL;
665 if (ot == NULL || ot == Py_None)
666 tt = time(NULL);
667 else {
668 double dt = PyFloat_AsDouble(ot);
669 if (PyErr_Occurred())
670 return NULL;
671 tt = _PyTime_DoubleToTimet(dt);
672 if (tt == (time_t)-1 && PyErr_Occurred())
673 return NULL;
674 }
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000675 timeptr = localtime(&tt);
676 if (timeptr == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000677 PyErr_SetString(PyExc_ValueError, "unconvertible time");
Alexander Belopolsky5da468f2011-01-04 17:15:52 +0000678 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000679 }
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000680 return _asctime(timeptr);
Guido van Rossum9e90a671993-06-24 11:10:19 +0000681}
682
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000683PyDoc_STRVAR(ctime_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000684"ctime(seconds) -> string\n\
685\n\
686Convert a time in seconds since the Epoch to a string in local time.\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000687This is equivalent to asctime(localtime(seconds)). When the time tuple is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000688not present, current time as returned by localtime() is used.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000689
Guido van Rossum60cd8131998-03-06 17:16:21 +0000690#ifdef HAVE_MKTIME
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000691static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000692time_mktime(PyObject *self, PyObject *tup)
Guido van Rossum234f9421993-06-17 12:35:49 +0000693{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000694 struct tm buf;
695 time_t tt;
696 if (!gettmarg(tup, &buf))
697 return NULL;
698 tt = mktime(&buf);
699 if (tt == (time_t)(-1)) {
700 PyErr_SetString(PyExc_OverflowError,
701 "mktime argument out of range");
702 return NULL;
703 }
704 return PyFloat_FromDouble((double)tt);
Guido van Rossum234f9421993-06-17 12:35:49 +0000705}
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000706
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000707PyDoc_STRVAR(mktime_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000708"mktime(tuple) -> floating point number\n\
709\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000710Convert a time tuple in local time to seconds since the Epoch.");
Guido van Rossum60cd8131998-03-06 17:16:21 +0000711#endif /* HAVE_MKTIME */
Guido van Rossum234f9421993-06-17 12:35:49 +0000712
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000713#ifdef HAVE_WORKING_TZSET
Martin v. Löwis1a214512008-06-11 05:26:20 +0000714static void PyInit_timezone(PyObject *module);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000715
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000716static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000717time_tzset(PyObject *self, PyObject *unused)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000718{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000719 PyObject* m;
Fred Drake9bb74322002-04-01 14:49:59 +0000720
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000721 m = PyImport_ImportModuleNoBlock("time");
722 if (m == NULL) {
723 return NULL;
724 }
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000725
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000726 tzset();
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000727
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000728 /* Reset timezone, altzone, daylight and tzname */
729 PyInit_timezone(m);
730 Py_DECREF(m);
Tim Peters1b6f7a92004-06-20 02:50:16 +0000731
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000732 Py_INCREF(Py_None);
733 return Py_None;
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000734}
735
736PyDoc_STRVAR(tzset_doc,
R. David Murray4d55bf92010-12-14 00:55:46 +0000737"tzset()\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000738\n\
739Initialize, or reinitialize, the local timezone to the value stored in\n\
740os.environ['TZ']. The TZ environment variable should be specified in\n\
Neal Norwitzdc8e1942004-07-20 22:34:37 +0000741standard Unix timezone format as documented in the tzset man page\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000742(eg. 'US/Eastern', 'Europe/Amsterdam'). Unknown timezones will silently\n\
743fall back to UTC. If the TZ environment variable is not set, the local\n\
744timezone is set to the systems best guess of wallclock time.\n\
745Changing the TZ environment variable without calling tzset *may* change\n\
746the local timezone used by methods such as localtime, but this behaviour\n\
747should not be relied on.");
748#endif /* HAVE_WORKING_TZSET */
749
Martin v. Löwisd218dc12008-04-07 03:17:54 +0000750static void
Martin v. Löwis1a214512008-06-11 05:26:20 +0000751PyInit_timezone(PyObject *m) {
752 /* This code moved from PyInit_time wholesale to allow calling it from
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000753 time_tzset. In the future, some parts of it can be moved back
754 (for platforms that don't HAVE_WORKING_TZSET, when we know what they
755 are), and the extraneous calls to tzset(3) should be removed.
756 I haven't done this yet, as I don't want to change this code as
757 little as possible when introducing the time.tzset and time.tzsetwall
758 methods. This should simply be a method of doing the following once,
759 at the top of this function and removing the call to tzset() from
760 time_tzset():
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000761
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000762 #ifdef HAVE_TZSET
763 tzset()
764 #endif
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000765
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000766 And I'm lazy and hate C so nyer.
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000767 */
Guido van Rossum10b164a2001-09-25 13:59:01 +0000768#if defined(HAVE_TZNAME) && !defined(__GLIBC__) && !defined(__CYGWIN__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000769 PyObject *otz0, *otz1;
770 tzset();
Guido van Rossum26452411998-09-28 22:07:11 +0000771#ifdef PYOS_OS2
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000772 PyModule_AddIntConstant(m, "timezone", _timezone);
Guido van Rossum26452411998-09-28 22:07:11 +0000773#else /* !PYOS_OS2 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000774 PyModule_AddIntConstant(m, "timezone", timezone);
Guido van Rossum26452411998-09-28 22:07:11 +0000775#endif /* PYOS_OS2 */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000776#ifdef HAVE_ALTZONE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000777 PyModule_AddIntConstant(m, "altzone", altzone);
Guido van Rossumb6775db1994-08-01 11:34:53 +0000778#else
Guido van Rossum26452411998-09-28 22:07:11 +0000779#ifdef PYOS_OS2
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000780 PyModule_AddIntConstant(m, "altzone", _timezone-3600);
Guido van Rossum26452411998-09-28 22:07:11 +0000781#else /* !PYOS_OS2 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000782 PyModule_AddIntConstant(m, "altzone", timezone-3600);
Guido van Rossum26452411998-09-28 22:07:11 +0000783#endif /* PYOS_OS2 */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000784#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000785 PyModule_AddIntConstant(m, "daylight", daylight);
786 otz0 = PyUnicode_Decode(tzname[0], strlen(tzname[0]), TZNAME_ENCODING, NULL);
787 otz1 = PyUnicode_Decode(tzname[1], strlen(tzname[1]), TZNAME_ENCODING, NULL);
788 PyModule_AddObject(m, "tzname", Py_BuildValue("(NN)", otz0, otz1));
Guido van Rossum10b164a2001-09-25 13:59:01 +0000789#else /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/
Martin v. Löwis60a5d722002-10-16 20:28:25 +0000790#ifdef HAVE_STRUCT_TM_TM_ZONE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000791 {
Guido van Rossum234f9421993-06-17 12:35:49 +0000792#define YEAR ((time_t)((365 * 24 + 6) * 3600))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000793 time_t t;
794 struct tm *p;
795 long janzone, julyzone;
796 char janname[10], julyname[10];
797 t = (time((time_t *)0) / YEAR) * YEAR;
798 p = localtime(&t);
799 janzone = -p->tm_gmtoff;
800 strncpy(janname, p->tm_zone ? p->tm_zone : " ", 9);
801 janname[9] = '\0';
802 t += YEAR/2;
803 p = localtime(&t);
804 julyzone = -p->tm_gmtoff;
805 strncpy(julyname, p->tm_zone ? p->tm_zone : " ", 9);
806 julyname[9] = '\0';
Guido van Rossum10b164a2001-09-25 13:59:01 +0000807
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000808 if( janzone < julyzone ) {
809 /* DST is reversed in the southern hemisphere */
810 PyModule_AddIntConstant(m, "timezone", julyzone);
811 PyModule_AddIntConstant(m, "altzone", janzone);
812 PyModule_AddIntConstant(m, "daylight",
813 janzone != julyzone);
814 PyModule_AddObject(m, "tzname",
815 Py_BuildValue("(zz)",
816 julyname, janname));
817 } else {
818 PyModule_AddIntConstant(m, "timezone", janzone);
819 PyModule_AddIntConstant(m, "altzone", julyzone);
820 PyModule_AddIntConstant(m, "daylight",
821 janzone != julyzone);
822 PyModule_AddObject(m, "tzname",
823 Py_BuildValue("(zz)",
824 janname, julyname));
825 }
826 }
Guido van Rossume6a4b7b1997-10-08 15:27:56 +0000827#else
Martin v. Löwis60a5d722002-10-16 20:28:25 +0000828#endif /* HAVE_STRUCT_TM_TM_ZONE */
Tim Peters26ae7cd2001-03-20 03:26:49 +0000829#ifdef __CYGWIN__
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000830 tzset();
831 PyModule_AddIntConstant(m, "timezone", _timezone);
832 PyModule_AddIntConstant(m, "altzone", _timezone-3600);
833 PyModule_AddIntConstant(m, "daylight", _daylight);
834 PyModule_AddObject(m, "tzname",
835 Py_BuildValue("(zz)", _tzname[0], _tzname[1]));
Tim Peters26ae7cd2001-03-20 03:26:49 +0000836#endif /* __CYGWIN__ */
Guido van Rossum10b164a2001-09-25 13:59:01 +0000837#endif /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000838}
839
840
841static PyMethodDef time_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000842 {"time", time_time, METH_NOARGS, time_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000843#ifdef HAVE_CLOCK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000844 {"clock", time_clock, METH_NOARGS, clock_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000845#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000846 {"sleep", time_sleep, METH_VARARGS, sleep_doc},
847 {"gmtime", time_gmtime, METH_VARARGS, gmtime_doc},
848 {"localtime", time_localtime, METH_VARARGS, localtime_doc},
849 {"asctime", time_asctime, METH_VARARGS, asctime_doc},
850 {"ctime", time_ctime, METH_VARARGS, ctime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000851#ifdef HAVE_MKTIME
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000852 {"mktime", time_mktime, METH_O, mktime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000853#endif
854#ifdef HAVE_STRFTIME
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000855 {"strftime", time_strftime, METH_VARARGS, strftime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000856#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000857 {"strptime", time_strptime, METH_VARARGS, strptime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000858#ifdef HAVE_WORKING_TZSET
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000859 {"tzset", time_tzset, METH_NOARGS, tzset_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000860#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000861 {NULL, NULL} /* sentinel */
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000862};
863
864
865PyDoc_STRVAR(module_doc,
866"This module provides various functions to manipulate time values.\n\
867\n\
868There are two standard representations of time. One is the number\n\
869of seconds since the Epoch, in UTC (a.k.a. GMT). It may be an integer\n\
870or a floating point number (to represent fractions of seconds).\n\
871The Epoch is system-defined; on Unix, it is generally January 1st, 1970.\n\
872The actual value can be retrieved by calling gmtime(0).\n\
873\n\
874The other representation is a tuple of 9 integers giving local time.\n\
875The tuple items are:\n\
876 year (four digits, e.g. 1998)\n\
877 month (1-12)\n\
878 day (1-31)\n\
879 hours (0-23)\n\
880 minutes (0-59)\n\
881 seconds (0-59)\n\
882 weekday (0-6, Monday is 0)\n\
883 Julian day (day in the year, 1-366)\n\
884 DST (Daylight Savings Time) flag (-1, 0 or 1)\n\
885If the DST flag is 0, the time is given in the regular time zone;\n\
886if it is 1, the time is given in the DST time zone;\n\
887if it is -1, mktime() should guess based on the date and time.\n\
888\n\
889Variables:\n\
890\n\
891timezone -- difference in seconds between UTC and local standard time\n\
892altzone -- difference in seconds between UTC and local DST time\n\
893daylight -- whether local time should reflect DST\n\
894tzname -- tuple of (standard time zone name, DST time zone name)\n\
895\n\
896Functions:\n\
897\n\
898time() -- return current time in seconds since the Epoch as a float\n\
899clock() -- return CPU time since process start as a float\n\
900sleep() -- delay for a number of seconds given as a float\n\
901gmtime() -- convert seconds since Epoch to UTC tuple\n\
902localtime() -- convert seconds since Epoch to local time tuple\n\
903asctime() -- convert time tuple to string\n\
904ctime() -- convert time in seconds to string\n\
905mktime() -- convert local time tuple to seconds since Epoch\n\
906strftime() -- convert time tuple to string according to format specification\n\
907strptime() -- parse string to time tuple according to format specification\n\
908tzset() -- change the local timezone");
909
910
Martin v. Löwis1a214512008-06-11 05:26:20 +0000911
912static struct PyModuleDef timemodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000913 PyModuleDef_HEAD_INIT,
914 "time",
915 module_doc,
916 -1,
917 time_methods,
918 NULL,
919 NULL,
920 NULL,
921 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +0000922};
923
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000924PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +0000925PyInit_time(void)
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000926{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000927 PyObject *m;
928 char *p;
929 m = PyModule_Create(&timemodule);
930 if (m == NULL)
931 return NULL;
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000932
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000933 /* Accept 2-digit dates unless PYTHONY2K is set and non-empty */
934 p = Py_GETENV("PYTHONY2K");
935 PyModule_AddIntConstant(m, "accept2dyear", (long) (!p || !*p));
936 /* Squirrel away the module's dictionary for the y2k check */
937 moddict = PyModule_GetDict(m);
938 Py_INCREF(moddict);
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000939
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000940 /* Set, or reset, module variables like time.timezone */
941 PyInit_timezone(m);
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000942
Mark Hammond975e3922002-07-16 01:29:19 +0000943#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000944 /* Helper to allow interrupts for Windows.
945 If Ctrl+C event delivered while not sleeping
946 it will be ignored.
947 */
948 main_thread = PyThread_get_thread_ident();
949 hInterruptEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
950 SetConsoleCtrlHandler( PyCtrlHandler, TRUE);
Mark Hammond975e3922002-07-16 01:29:19 +0000951#endif /* MS_WINDOWS */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000952 if (!initialized) {
953 PyStructSequence_InitType(&StructTimeType,
954 &struct_time_type_desc);
955 }
956 Py_INCREF(&StructTimeType);
957 PyModule_AddObject(m, "struct_time", (PyObject*) &StructTimeType);
958 initialized = 1;
959 return m;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000960}
961
Guido van Rossumb6775db1994-08-01 11:34:53 +0000962static double
Thomas Woutersf3f33dc2000-07-21 06:00:07 +0000963floattime(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000964{
Alexander Belopolsky6fc4ade2010-08-05 17:34:27 +0000965 _PyTime_timeval t;
966 _PyTime_gettimeofday(&t);
967 return (double)t.tv_sec + t.tv_usec*0.000001;
Guido van Rossum426035c1991-02-19 12:27:35 +0000968}
969
Guido van Rossumb6775db1994-08-01 11:34:53 +0000970
971/* Implement floatsleep() for various platforms.
972 When interrupted (or when another error occurs), return -1 and
973 set an exception; else return 0. */
974
975static int
Guido van Rossuma320fd31995-03-09 12:14:15 +0000976floatsleep(double secs)
Guido van Rossum426035c1991-02-19 12:27:35 +0000977{
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000978/* XXX Should test for MS_WINDOWS first! */
Skip Montanaroeb33e5a2007-08-17 12:57:41 +0000979#if defined(HAVE_SELECT) && !defined(__EMX__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000980 struct timeval t;
981 double frac;
982 frac = fmod(secs, 1.0);
983 secs = floor(secs);
984 t.tv_sec = (long)secs;
985 t.tv_usec = (long)(frac*1000000.0);
986 Py_BEGIN_ALLOW_THREADS
987 if (select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &t) != 0) {
Guido van Rossum09cbb011999-11-08 15:32:27 +0000988#ifdef EINTR
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000989 if (errno != EINTR) {
Guido van Rossum09cbb011999-11-08 15:32:27 +0000990#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000991 if (1) {
Guido van Rossum09cbb011999-11-08 15:32:27 +0000992#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000993 Py_BLOCK_THREADS
994 PyErr_SetFromErrno(PyExc_IOError);
995 return -1;
996 }
997 }
998 Py_END_ALLOW_THREADS
Martin v. Löwis02af9642002-01-16 11:04:06 +0000999#elif defined(__WATCOMC__) && !defined(__QNX__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001000 /* XXX Can't interrupt this sleep */
1001 Py_BEGIN_ALLOW_THREADS
1002 delay((int)(secs * 1000 + 0.5)); /* delay() uses milliseconds */
1003 Py_END_ALLOW_THREADS
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001004#elif defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001005 {
1006 double millisecs = secs * 1000.0;
1007 unsigned long ul_millis;
Tim Peters513a1cd2003-01-19 04:54:58 +00001008
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001009 if (millisecs > (double)ULONG_MAX) {
1010 PyErr_SetString(PyExc_OverflowError,
1011 "sleep length is too large");
1012 return -1;
1013 }
1014 Py_BEGIN_ALLOW_THREADS
1015 /* Allow sleep(0) to maintain win32 semantics, and as decreed
1016 * by Guido, only the main thread can be interrupted.
1017 */
1018 ul_millis = (unsigned long)millisecs;
1019 if (ul_millis == 0 ||
1020 main_thread != PyThread_get_thread_ident())
1021 Sleep(ul_millis);
1022 else {
1023 DWORD rc;
1024 ResetEvent(hInterruptEvent);
1025 rc = WaitForSingleObject(hInterruptEvent, ul_millis);
1026 if (rc == WAIT_OBJECT_0) {
1027 /* Yield to make sure real Python signal
1028 * handler called.
1029 */
1030 Sleep(1);
1031 Py_BLOCK_THREADS
1032 errno = EINTR;
1033 PyErr_SetFromErrno(PyExc_IOError);
1034 return -1;
1035 }
1036 }
1037 Py_END_ALLOW_THREADS
1038 }
Martin v. Löwis02af9642002-01-16 11:04:06 +00001039#elif defined(PYOS_OS2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001040 /* This Sleep *IS* Interruptable by Exceptions */
1041 Py_BEGIN_ALLOW_THREADS
1042 if (DosSleep(secs * 1000) != NO_ERROR) {
1043 Py_BLOCK_THREADS
1044 PyErr_SetFromErrno(PyExc_IOError);
1045 return -1;
1046 }
1047 Py_END_ALLOW_THREADS
Martin v. Löwis02af9642002-01-16 11:04:06 +00001048#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001049 /* XXX Can't interrupt this sleep */
1050 Py_BEGIN_ALLOW_THREADS
1051 sleep((int)secs);
1052 Py_END_ALLOW_THREADS
Martin v. Löwis02af9642002-01-16 11:04:06 +00001053#endif
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001054
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001055 return 0;
Guido van Rossum80c9d881991-04-16 08:47:51 +00001056}