blob: 35162ff1331f4dbb6601e25b5a722dfac7cf4618 [file] [log] [blame]
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001/* Time module */
2
Barry Warsaw9a2a8a81996-12-06 23:32:14 +00003#include "Python.h"
Alexander Belopolsky6fc4ade2010-08-05 17:34:27 +00004#include "_time.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +00005
Guido van Rossum87ce7bb1998-06-09 16:30:31 +00006#include <ctype.h>
7
Thomas Wouters0e3f5912006-08-11 14:57:12 +00008#ifdef HAVE_SYS_TYPES_H
Guido van Rossumb6775db1994-08-01 11:34:53 +00009#include <sys/types.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +000010#endif /* HAVE_SYS_TYPES_H */
Guido van Rossum6d946f91992-08-14 13:49:30 +000011
Guido van Rossumb6775db1994-08-01 11:34:53 +000012#ifdef QUICKWIN
13#include <io.h>
14#endif
15
Guido van Rossum7bf22de1997-12-02 20:34:19 +000016#if defined(__WATCOMC__) && !defined(__QNX__)
Guido van Rossumbceeac81996-05-23 22:53:47 +000017#include <i86.h>
18#else
Guido van Rossumcac6c721996-09-06 13:34:02 +000019#ifdef MS_WINDOWS
Mark Hammond975e3922002-07-16 01:29:19 +000020#define WIN32_LEAN_AND_MEAN
Guido van Rossum258ccd42001-03-02 06:53:29 +000021#include <windows.h>
Mark Hammond975e3922002-07-16 01:29:19 +000022#include "pythread.h"
23
24/* helper to allow us to interrupt sleep() on Windows*/
25static HANDLE hInterruptEvent = NULL;
26static BOOL WINAPI PyCtrlHandler(DWORD dwCtrlType)
27{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000028 SetEvent(hInterruptEvent);
29 /* allow other default handlers to be called.
30 Default Python handler will setup the
31 KeyboardInterrupt exception.
32 */
33 return FALSE;
Mark Hammond975e3922002-07-16 01:29:19 +000034}
35static long main_thread;
36
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000037#if defined(__BORLANDC__)
Guido van Rossumb2fb3641996-09-07 00:47:35 +000038/* These overrides not needed for Win32 */
Guido van Rossumb6775db1994-08-01 11:34:53 +000039#define timezone _timezone
Guido van Rossumcc081121995-03-14 15:05:41 +000040#define tzname _tzname
41#define daylight _daylight
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000042#endif /* __BORLANDC__ */
Guido van Rossumcac6c721996-09-06 13:34:02 +000043#endif /* MS_WINDOWS */
Guido van Rossum7bf22de1997-12-02 20:34:19 +000044#endif /* !__WATCOMC__ || __QNX__ */
Guido van Rossum234f9421993-06-17 12:35:49 +000045
Thomas Wouters477c8d52006-05-27 19:21:47 +000046#if defined(MS_WINDOWS) && !defined(__BORLANDC__)
47/* Win32 has better clock replacement; we have our own version below. */
48#undef HAVE_CLOCK
49#endif /* MS_WINDOWS && !defined(__BORLANDC__) */
Guido van Rossum3917c221997-04-02 05:35:28 +000050
Andrew MacIntyre7bf68332002-03-03 02:59:16 +000051#if defined(PYOS_OS2)
52#define INCL_DOS
53#define INCL_ERRORS
54#include <os2.h>
55#endif
56
Guido van Rossum8e9ebfd1997-11-22 21:53:48 +000057#if defined(PYCC_VACPP)
Guido van Rossum26452411998-09-28 22:07:11 +000058#include <sys/time.h>
Guido van Rossum8e9ebfd1997-11-22 21:53:48 +000059#endif
60
Guido van Rossum234f9421993-06-17 12:35:49 +000061/* Forward declarations */
Tim Petersdbd9ba62000-07-09 03:09:57 +000062static int floatsleep(double);
Thomas Woutersed77bac2000-07-24 15:26:39 +000063static double floattime(void);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000064
Guido van Rossumcfbaecc1998-08-25 14:51:12 +000065/* For Y2K check */
Gregory P. Smith14b04cd2012-11-27 10:16:55 -080066static PyObject *moddict = NULL;
Guido van Rossumcfbaecc1998-08-25 14:51:12 +000067
Barry Warsaw9a2a8a81996-12-06 23:32:14 +000068static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000069time_time(PyObject *self, PyObject *unused)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000070{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000071 double secs;
72 secs = floattime();
73 if (secs == 0.0) {
74 PyErr_SetFromErrno(PyExc_IOError);
75 return NULL;
76 }
77 return PyFloat_FromDouble(secs);
Guido van Rossumb6775db1994-08-01 11:34:53 +000078}
79
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000080PyDoc_STRVAR(time_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +000081"time() -> floating point number\n\
82\n\
83Return the current time in seconds since the Epoch.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000084Fractions of a second may be present if the system clock provides them.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +000085
Guido van Rossumb6775db1994-08-01 11:34:53 +000086#ifdef HAVE_CLOCK
87
88#ifndef CLOCKS_PER_SEC
Guido van Rossum1b66a4f1996-02-25 04:50:33 +000089#ifdef CLK_TCK
90#define CLOCKS_PER_SEC CLK_TCK
91#else
Guido van Rossumb6775db1994-08-01 11:34:53 +000092#define CLOCKS_PER_SEC 1000000
93#endif
Guido van Rossum1b66a4f1996-02-25 04:50:33 +000094#endif
Guido van Rossumb6775db1994-08-01 11:34:53 +000095
Barry Warsaw9a2a8a81996-12-06 23:32:14 +000096static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000097time_clock(PyObject *self, PyObject *unused)
Guido van Rossumb6775db1994-08-01 11:34:53 +000098{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000099 return PyFloat_FromDouble(((double)clock()) / CLOCKS_PER_SEC);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000100}
Guido van Rossumb6775db1994-08-01 11:34:53 +0000101#endif /* HAVE_CLOCK */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000102
Thomas Wouters477c8d52006-05-27 19:21:47 +0000103#if defined(MS_WINDOWS) && !defined(__BORLANDC__)
Mark Hammond7ba5e812002-02-12 04:02:33 +0000104/* Due to Mark Hammond and Tim Peters */
Guido van Rossum3917c221997-04-02 05:35:28 +0000105static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000106time_clock(PyObject *self, PyObject *unused)
Guido van Rossum3917c221997-04-02 05:35:28 +0000107{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000108 static LARGE_INTEGER ctrStart;
109 static double divisor = 0.0;
110 LARGE_INTEGER now;
111 double diff;
Guido van Rossum3917c221997-04-02 05:35:28 +0000112
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000113 if (divisor == 0.0) {
114 LARGE_INTEGER freq;
115 QueryPerformanceCounter(&ctrStart);
116 if (!QueryPerformanceFrequency(&freq) || freq.QuadPart == 0) {
117 /* Unlikely to happen - this works on all intel
118 machines at least! Revert to clock() */
119 return PyFloat_FromDouble(((double)clock()) /
120 CLOCKS_PER_SEC);
121 }
122 divisor = (double)freq.QuadPart;
123 }
124 QueryPerformanceCounter(&now);
125 diff = (double)(now.QuadPart - ctrStart.QuadPart);
126 return PyFloat_FromDouble(diff / divisor);
Guido van Rossum3917c221997-04-02 05:35:28 +0000127}
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000128
Guido van Rossum3917c221997-04-02 05:35:28 +0000129#define HAVE_CLOCK /* So it gets included in the methods */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000130#endif /* MS_WINDOWS && !defined(__BORLANDC__) */
Guido van Rossum3917c221997-04-02 05:35:28 +0000131
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000132#ifdef HAVE_CLOCK
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000133PyDoc_STRVAR(clock_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000134"clock() -> floating point number\n\
135\n\
136Return the CPU time or real time since the start of the process or since\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000137the first call to clock(). This has as much precision as the system\n\
138records.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000139#endif
140
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000141static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000142time_sleep(PyObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000143{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000144 double secs;
145 if (!PyArg_ParseTuple(args, "d:sleep", &secs))
146 return NULL;
147 if (floatsleep(secs) != 0)
148 return NULL;
149 Py_INCREF(Py_None);
150 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000151}
152
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000153PyDoc_STRVAR(sleep_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000154"sleep(seconds)\n\
155\n\
156Delay execution for a given number of seconds. The argument may be\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000157a floating point number for subsecond precision.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000158
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000159static PyStructSequence_Field struct_time_type_fields[] = {
Alexander Belopolsky69f3fd02010-06-05 15:04:51 +0000160 {"tm_year", "year, for example, 1993"},
161 {"tm_mon", "month of year, range [1, 12]"},
162 {"tm_mday", "day of month, range [1, 31]"},
163 {"tm_hour", "hours, range [0, 23]"},
164 {"tm_min", "minutes, range [0, 59]"},
165 {"tm_sec", "seconds, range [0, 61])"},
166 {"tm_wday", "day of week, range [0, 6], Monday is 0"},
167 {"tm_yday", "day of year, range [1, 366]"},
168 {"tm_isdst", "1 if summer time is in effect, 0 if not, and -1 if unknown"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000169 {0}
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000170};
171
172static PyStructSequence_Desc struct_time_type_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000173 "time.struct_time",
Alexander Belopolsky69f3fd02010-06-05 15:04:51 +0000174 "The time value as returned by gmtime(), localtime(), and strptime(), and\n"
175 " accepted by asctime(), mktime() and strftime(). May be considered as a\n"
176 " sequence of 9 integers.\n\n"
177 " Note that several fields' values are not the same as those defined by\n"
178 " the C language standard for struct tm. For example, the value of the\n"
179 " field tm_year is the actual year, not year - 1900. See individual\n"
180 " fields' descriptions for details.",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000181 struct_time_type_fields,
182 9,
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000183};
Tim Peters9ad4b682002-02-13 05:14:18 +0000184
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000185static int initialized;
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000186static PyTypeObject StructTimeType;
187
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000188static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000189tmtotuple(struct tm *p)
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000190{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000191 PyObject *v = PyStructSequence_New(&StructTimeType);
192 if (v == NULL)
193 return NULL;
Tim Peters9ad4b682002-02-13 05:14:18 +0000194
Christian Heimes217cfd12007-12-02 14:31:20 +0000195#define SET(i,val) PyStructSequence_SET_ITEM(v, i, PyLong_FromLong((long) val))
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000196
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000197 SET(0, p->tm_year + 1900);
198 SET(1, p->tm_mon + 1); /* Want January == 1 */
199 SET(2, p->tm_mday);
200 SET(3, p->tm_hour);
201 SET(4, p->tm_min);
202 SET(5, p->tm_sec);
203 SET(6, (p->tm_wday + 6) % 7); /* Want Monday == 0 */
204 SET(7, p->tm_yday + 1); /* Want January, 1 == 1 */
205 SET(8, p->tm_isdst);
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000206#undef SET
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000207 if (PyErr_Occurred()) {
208 Py_XDECREF(v);
209 return NULL;
210 }
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000211
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000212 return v;
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000213}
214
215static PyObject *
Brett Cannon298c3802004-06-19 20:48:43 +0000216time_convert(double when, struct tm * (*function)(const time_t *))
Guido van Rossum234f9421993-06-17 12:35:49 +0000217{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000218 struct tm *p;
219 time_t whent = _PyTime_DoubleToTimet(when);
Brett Cannon298c3802004-06-19 20:48:43 +0000220
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000221 if (whent == (time_t)-1 && PyErr_Occurred())
222 return NULL;
223 errno = 0;
224 p = function(&whent);
225 if (p == NULL) {
Guido van Rossum6e8583d1996-10-08 14:19:52 +0000226#ifdef EINVAL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000227 if (errno == 0)
228 errno = EINVAL;
Guido van Rossum6e8583d1996-10-08 14:19:52 +0000229#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000230 return PyErr_SetFromErrno(PyExc_ValueError);
231 }
232 return tmtotuple(p);
Guido van Rossum234f9421993-06-17 12:35:49 +0000233}
234
Fred Drakef901abd2004-08-03 17:58:55 +0000235/* Parse arg tuple that can contain an optional float-or-None value;
236 format needs to be "|O:name".
237 Returns non-zero on success (parallels PyArg_ParseTuple).
238*/
239static int
240parse_time_double_args(PyObject *args, char *format, double *pwhen)
241{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000242 PyObject *ot = NULL;
Fred Drakef901abd2004-08-03 17:58:55 +0000243
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000244 if (!PyArg_ParseTuple(args, format, &ot))
245 return 0;
246 if (ot == NULL || ot == Py_None)
247 *pwhen = floattime();
248 else {
249 double when = PyFloat_AsDouble(ot);
250 if (PyErr_Occurred())
251 return 0;
252 *pwhen = when;
253 }
254 return 1;
Fred Drakef901abd2004-08-03 17:58:55 +0000255}
256
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000257static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000258time_gmtime(PyObject *self, PyObject *args)
Guido van Rossum234f9421993-06-17 12:35:49 +0000259{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000260 double when;
261 if (!parse_time_double_args(args, "|O:gmtime", &when))
262 return NULL;
263 return time_convert(when, gmtime);
Guido van Rossum234f9421993-06-17 12:35:49 +0000264}
265
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000266PyDoc_STRVAR(gmtime_doc,
Christian Heimes9a371592007-12-28 14:08:13 +0000267"gmtime([seconds]) -> (tm_year, tm_mon, tm_mday, tm_hour, tm_min,\n\
Fred Drake193a3f62002-03-12 21:38:49 +0000268 tm_sec, tm_wday, tm_yday, tm_isdst)\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000269\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000270Convert seconds since the Epoch to a time tuple expressing UTC (a.k.a.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000271GMT). When 'seconds' is not passed in, convert the current time instead.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000272
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000273static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000274time_localtime(PyObject *self, PyObject *args)
Guido van Rossum234f9421993-06-17 12:35:49 +0000275{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000276 double when;
277 if (!parse_time_double_args(args, "|O:localtime", &when))
278 return NULL;
279 return time_convert(when, localtime);
Guido van Rossum234f9421993-06-17 12:35:49 +0000280}
281
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000282PyDoc_STRVAR(localtime_doc,
Christian Heimes9a371592007-12-28 14:08:13 +0000283"localtime([seconds]) -> (tm_year,tm_mon,tm_mday,tm_hour,tm_min,\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000284 tm_sec,tm_wday,tm_yday,tm_isdst)\n\
Martin v. Löwisb3cfc1d2001-12-02 12:27:43 +0000285\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000286Convert seconds since the Epoch to a time tuple expressing local time.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000287When 'seconds' is not passed in, convert the current time instead.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000288
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000289/* Convert 9-item tuple to tm structure. Return 1 on success, set
290 * an exception and return 0 on error.
291 */
Guido van Rossum9e90a671993-06-24 11:10:19 +0000292static int
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000293gettmarg(PyObject *args, struct tm *p)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000294{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000295 int y;
Guido van Rossumcfbaecc1998-08-25 14:51:12 +0000296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000297 memset((void *) p, '\0', sizeof(struct tm));
Guido van Rossumb9081262007-08-25 03:14:09 +0000298
Alexander Belopolsky610e5442011-01-06 21:57:06 +0000299 if (!PyTuple_Check(args)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000300 PyErr_SetString(PyExc_TypeError,
301 "Tuple or struct_time argument required");
302 return 0;
303 }
Skip Montanaro41cfce92007-08-24 21:11:00 +0000304
Alexander Belopolsky610e5442011-01-06 21:57:06 +0000305 if (!PyArg_ParseTuple(args, "iiiiiiiii",
306 &y, &p->tm_mon, &p->tm_mday,
307 &p->tm_hour, &p->tm_min, &p->tm_sec,
308 &p->tm_wday, &p->tm_yday, &p->tm_isdst))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000309 return 0;
Skip Montanaro41cfce92007-08-24 21:11:00 +0000310
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000311 /* If year is specified with less than 4 digits, its interpretation
312 * depends on the accept2dyear value.
313 *
314 * If accept2dyear is true (default), a backward compatibility behavior is
315 * invoked as follows:
316 *
317 * - for 2-digit year, century is guessed according to POSIX rules for
318 * %y strptime format: 21st century for y < 69, 20th century
319 * otherwise. A deprecation warning is issued when century
320 * information is guessed in this way.
321 *
322 * - for 3-digit or negative year, a ValueError exception is raised.
323 *
324 * If accept2dyear is false (set by the program or as a result of a
325 * non-empty value assigned to PYTHONY2K environment variable) all year
326 * values are interpreted as given.
Alexander Belopolskya6867252011-01-05 23:00:47 +0000327 */
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000328 if (y < 1000) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000329 PyObject *accept = PyDict_GetItemString(moddict,
330 "accept2dyear");
Victor Stinner301f1212011-01-08 03:06:52 +0000331 if (accept != NULL) {
Alexander Belopolsky0dd06f42011-01-08 01:23:02 +0000332 int acceptval = PyObject_IsTrue(accept);
333 if (acceptval == -1)
Alexander Belopolskya6867252011-01-05 23:00:47 +0000334 return 0;
Alexander Belopolsky0dd06f42011-01-08 01:23:02 +0000335 if (acceptval) {
336 if (0 <= y && y < 69)
337 y += 2000;
338 else if (69 <= y && y < 100)
339 y += 1900;
340 else {
341 PyErr_SetString(PyExc_ValueError,
342 "year out of range");
343 return 0;
344 }
345 if (PyErr_WarnEx(PyExc_DeprecationWarning,
346 "Century info guessed for a 2-digit year.", 1) != 0)
347 return 0;
Alexander Belopolskya6867252011-01-05 23:00:47 +0000348 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000349 }
Alexander Belopolsky0dd06f42011-01-08 01:23:02 +0000350 else
351 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000352 }
353 p->tm_year = y - 1900;
354 p->tm_mon--;
355 p->tm_wday = (p->tm_wday + 1) % 7;
356 p->tm_yday--;
357 return 1;
Guido van Rossum9e90a671993-06-24 11:10:19 +0000358}
359
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000360/* Check values of the struct tm fields before it is passed to strftime() and
361 * asctime(). Return 1 if all values are valid, otherwise set an exception
362 * and returns 0.
363 */
Victor Stinneref128102010-10-07 01:00:52 +0000364static int
365checktm(struct tm* buf)
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000366{
Victor Stinneref128102010-10-07 01:00:52 +0000367 /* Checks added to make sure strftime() and asctime() does not crash Python by
368 indexing blindly into some array for a textual representation
369 by some bad index (fixes bug #897625 and #6608).
370
371 Also support values of zero from Python code for arguments in which
372 that is out of range by forcing that value to the lowest value that
373 is valid (fixed bug #1520914).
374
375 Valid ranges based on what is allowed in struct tm:
376
377 - tm_year: [0, max(int)] (1)
378 - tm_mon: [0, 11] (2)
379 - tm_mday: [1, 31]
380 - tm_hour: [0, 23]
381 - tm_min: [0, 59]
382 - tm_sec: [0, 60]
383 - tm_wday: [0, 6] (1)
384 - tm_yday: [0, 365] (2)
385 - tm_isdst: [-max(int), max(int)]
386
387 (1) gettmarg() handles bounds-checking.
388 (2) Python's acceptable range is one greater than the range in C,
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000389 thus need to check against automatic decrement by gettmarg().
390 */
391 if (buf->tm_mon == -1)
392 buf->tm_mon = 0;
393 else if (buf->tm_mon < 0 || buf->tm_mon > 11) {
394 PyErr_SetString(PyExc_ValueError, "month out of range");
395 return 0;
396 }
397 if (buf->tm_mday == 0)
398 buf->tm_mday = 1;
399 else if (buf->tm_mday < 0 || buf->tm_mday > 31) {
400 PyErr_SetString(PyExc_ValueError, "day of month out of range");
401 return 0;
402 }
403 if (buf->tm_hour < 0 || buf->tm_hour > 23) {
404 PyErr_SetString(PyExc_ValueError, "hour out of range");
405 return 0;
406 }
407 if (buf->tm_min < 0 || buf->tm_min > 59) {
408 PyErr_SetString(PyExc_ValueError, "minute out of range");
409 return 0;
410 }
411 if (buf->tm_sec < 0 || buf->tm_sec > 61) {
412 PyErr_SetString(PyExc_ValueError, "seconds out of range");
413 return 0;
414 }
415 /* tm_wday does not need checking of its upper-bound since taking
416 ``% 7`` in gettmarg() automatically restricts the range. */
417 if (buf->tm_wday < 0) {
418 PyErr_SetString(PyExc_ValueError, "day of week out of range");
419 return 0;
420 }
421 if (buf->tm_yday == -1)
422 buf->tm_yday = 0;
423 else if (buf->tm_yday < 0 || buf->tm_yday > 365) {
424 PyErr_SetString(PyExc_ValueError, "day of year out of range");
425 return 0;
426 }
427 return 1;
428}
429
Victor Stinnerc1f32ca2011-10-14 02:36:13 +0200430#ifdef MS_WINDOWS
431 /* wcsftime() doesn't format correctly time zones, see issue #10653 */
432# undef HAVE_WCSFTIME
433#endif
434
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000435#ifdef HAVE_STRFTIME
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000436#ifdef HAVE_WCSFTIME
437#define time_char wchar_t
438#define format_time wcsftime
439#define time_strlen wcslen
440#else
441#define time_char char
442#define format_time strftime
443#define time_strlen strlen
444#endif
445
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000446static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000447time_strftime(PyObject *self, PyObject *args)
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000448{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000449 PyObject *tup = NULL;
450 struct tm buf;
451 const time_char *fmt;
Victor Stinnerb2904782010-09-29 10:34:19 +0000452#ifdef HAVE_WCSFTIME
453 wchar_t *format;
454#else
455 PyObject *format;
456#endif
Victor Stinneref128102010-10-07 01:00:52 +0000457 PyObject *format_arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000458 size_t fmtlen, buflen;
Victor Stinnerb2904782010-09-29 10:34:19 +0000459 time_char *outbuf = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000460 size_t i;
Victor Stinnerb2904782010-09-29 10:34:19 +0000461 PyObject *ret = NULL;
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000462
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000463 memset((void *) &buf, '\0', sizeof(buf));
Guido van Rossum1f41f841998-04-27 19:04:26 +0000464
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000465 /* Will always expect a unicode string to be passed as format.
466 Given that there's no str type anymore in py3k this seems safe.
467 */
Victor Stinneref128102010-10-07 01:00:52 +0000468 if (!PyArg_ParseTuple(args, "U|O:strftime", &format_arg, &tup))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000469 return NULL;
Thomas Woutersfe385252001-01-19 23:16:56 +0000470
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000471 if (tup == NULL) {
472 time_t tt = time(NULL);
473 buf = *localtime(&tt);
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000474 }
475 else if (!gettmarg(tup, &buf) || !checktm(&buf))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000476 return NULL;
Guido van Rossum10b164a2001-09-25 13:59:01 +0000477
Victor Stinner06ec45e2011-01-08 03:35:36 +0000478#if defined(_MSC_VER) || defined(sun)
Victor Stinner73ea29c2011-01-08 01:56:31 +0000479 if (buf.tm_year + 1900 < 1 || 9999 < buf.tm_year + 1900) {
Victor Stinner6f0e4f92011-03-21 02:14:53 +0100480 PyErr_SetString(PyExc_ValueError,
481 "strftime() requires year in [1; 9999]");
Alexander Belopolsky0dd06f42011-01-08 01:23:02 +0000482 return NULL;
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000483 }
Victor Stinner73ea29c2011-01-08 01:56:31 +0000484#endif
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000485
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000486 /* Normalize tm_isdst just in case someone foolishly implements %Z
487 based on the assumption that tm_isdst falls within the range of
488 [-1, 1] */
489 if (buf.tm_isdst < -1)
490 buf.tm_isdst = -1;
491 else if (buf.tm_isdst > 1)
492 buf.tm_isdst = 1;
Brett Cannond1080a32004-03-02 04:38:10 +0000493
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000494#ifdef HAVE_WCSFTIME
Victor Stinnerbeb4135b2010-10-07 01:02:42 +0000495 format = PyUnicode_AsWideCharString(format_arg, NULL);
Victor Stinnerb2904782010-09-29 10:34:19 +0000496 if (format == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000497 return NULL;
Victor Stinnerb2904782010-09-29 10:34:19 +0000498 fmt = format;
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000499#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000500 /* Convert the unicode string to an ascii one */
Victor Stinner720f34a2011-12-09 20:19:24 +0100501 format = PyUnicode_EncodeFSDefault(format_arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000502 if (format == NULL)
503 return NULL;
504 fmt = PyBytes_AS_STRING(format);
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000505#endif
Amaury Forgeot d'Arcb5be6d42009-03-02 23:52:57 +0000506
Stefan Krah2201ecb2012-02-27 17:34:17 +0100507#if defined(MS_WINDOWS) && !defined(HAVE_WCSFTIME)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000508 /* check that the format string contains only valid directives */
Victor Stinner8d91d452011-10-16 23:45:39 +0200509 for(outbuf = strchr(fmt, '%');
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000510 outbuf != NULL;
Victor Stinner8d91d452011-10-16 23:45:39 +0200511 outbuf = strchr(outbuf+2, '%'))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000512 {
513 if (outbuf[1]=='#')
514 ++outbuf; /* not documented by python, */
515 if (outbuf[1]=='\0' ||
Victor Stinner8d91d452011-10-16 23:45:39 +0200516 !strchr("aAbBcdHIjmMpSUwWxXyYzZ%", outbuf[1]))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000517 {
518 PyErr_SetString(PyExc_ValueError, "Invalid format string");
Stefan Krah2201ecb2012-02-27 17:34:17 +0100519 Py_DECREF(format);
520 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000521 }
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) {
Victor Stinner136ea492011-12-17 22:37:18 +0100531#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100532 int err;
Victor Stinner136ea492011-12-17 22:37:18 +0100533#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000534 outbuf = (time_char *)PyMem_Malloc(i*sizeof(time_char));
535 if (outbuf == NULL) {
Victor Stinnerb2904782010-09-29 10:34:19 +0000536 PyErr_NoMemory();
537 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000538 }
539 buflen = format_time(outbuf, i, fmt, &buf);
Victor Stinner136ea492011-12-17 22:37:18 +0100540#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100541 err = errno;
Victor Stinner136ea492011-12-17 22:37:18 +0100542#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000543 if (buflen > 0 || i >= 256 * fmtlen) {
544 /* If the buffer is 256 times as long as the format,
545 it's probably not failing for lack of room!
546 More likely, the format yields an empty result,
547 e.g. an empty format, or %Z when the timezone
548 is unknown. */
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000549#ifdef HAVE_WCSFTIME
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000550 ret = PyUnicode_FromWideChar(outbuf, buflen);
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000551#else
Victor Stinner720f34a2011-12-09 20:19:24 +0100552 ret = PyUnicode_DecodeFSDefaultAndSize(outbuf, buflen);
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000553#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000554 PyMem_Free(outbuf);
Victor Stinnerb2904782010-09-29 10:34:19 +0000555 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000556 }
557 PyMem_Free(outbuf);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000558#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000559 /* VisualStudio .NET 2005 does this properly */
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100560 if (buflen == 0 && err == EINVAL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000561 PyErr_SetString(PyExc_ValueError, "Invalid format string");
Victor Stinnerb2904782010-09-29 10:34:19 +0000562 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000563 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000564#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000565 }
Victor Stinnerb2904782010-09-29 10:34:19 +0000566#ifdef HAVE_WCSFTIME
567 PyMem_Free(format);
568#else
569 Py_DECREF(format);
570#endif
571 return ret;
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000572}
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000573
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000574#undef time_char
575#undef format_time
576
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000577PyDoc_STRVAR(strftime_doc,
Thomas Woutersfe385252001-01-19 23:16:56 +0000578"strftime(format[, tuple]) -> string\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000579\n\
580Convert a time tuple to a string according to a format specification.\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000581See the library reference manual for formatting codes. When the time tuple\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000582is not present, current time as returned by localtime() is used.");
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000583#endif /* HAVE_STRFTIME */
584
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000585static PyObject *
586time_strptime(PyObject *self, PyObject *args)
587{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000588 PyObject *strptime_module = PyImport_ImportModuleNoBlock("_strptime");
589 PyObject *strptime_result;
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000590
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000591 if (!strptime_module)
592 return NULL;
593 strptime_result = PyObject_CallMethod(strptime_module,
594 "_strptime_time", "O", args);
595 Py_DECREF(strptime_module);
596 return strptime_result;
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000597}
598
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000599
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000600PyDoc_STRVAR(strptime_doc,
Brett Cannon20def8b2003-07-01 05:16:08 +0000601"strptime(string, format) -> struct_time\n\
Martin v. Löwisb3cfc1d2001-12-02 12:27:43 +0000602\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000603Parse a string to a time tuple according to a format specification.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000604See the library reference manual for formatting codes (same as strftime()).");
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000605
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000606static PyObject *
607_asctime(struct tm *timeptr)
608{
609 /* Inspired by Open Group reference implementation available at
610 * http://pubs.opengroup.org/onlinepubs/009695399/functions/asctime.html */
611 static char wday_name[7][3] = {
612 "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
613 };
614 static char mon_name[12][3] = {
615 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
616 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
617 };
618 char buf[20]; /* 'Sun Sep 16 01:03:52\0' */
619 int n;
620
Alexander Belopolskyecbb8dc2011-01-06 16:45:25 +0000621 n = PyOS_snprintf(buf, sizeof(buf), "%.3s %.3s%3d %.2d:%.2d:%.2d",
622 wday_name[timeptr->tm_wday],
623 mon_name[timeptr->tm_mon],
624 timeptr->tm_mday, timeptr->tm_hour,
625 timeptr->tm_min, timeptr->tm_sec);
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000626 /* XXX: since the fields used by snprintf above are validated in checktm,
627 * the following condition should never trigger. We keep the check because
628 * historically fixed size buffer used in asctime was the source of
629 * crashes. */
630 if (n + 1 != sizeof(buf)) {
631 PyErr_SetString(PyExc_ValueError, "unconvertible time");
632 return NULL;
633 }
634
635 return PyUnicode_FromFormat("%s %d", buf, 1900 + timeptr->tm_year);
636}
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000637
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000638static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000639time_asctime(PyObject *self, PyObject *args)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000640{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000641 PyObject *tup = NULL;
642 struct tm buf;
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000643
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000644 if (!PyArg_UnpackTuple(args, "asctime", 0, 1, &tup))
645 return NULL;
646 if (tup == NULL) {
647 time_t tt = time(NULL);
648 buf = *localtime(&tt);
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000649 } else if (!gettmarg(tup, &buf) || !checktm(&buf))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000650 return NULL;
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000651 return _asctime(&buf);
Guido van Rossum9e90a671993-06-24 11:10:19 +0000652}
653
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000654PyDoc_STRVAR(asctime_doc,
Thomas Woutersfe385252001-01-19 23:16:56 +0000655"asctime([tuple]) -> string\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000656\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000657Convert a time tuple to a string, e.g. 'Sat Jun 06 16:26:11 1998'.\n\
658When the time tuple is not present, current time as returned by localtime()\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000659is used.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000660
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000661static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000662time_ctime(PyObject *self, PyObject *args)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000663{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000664 PyObject *ot = NULL;
665 time_t tt;
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000666 struct tm *timeptr;
Guido van Rossum10b164a2001-09-25 13:59:01 +0000667
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000668 if (!PyArg_UnpackTuple(args, "ctime", 0, 1, &ot))
669 return NULL;
670 if (ot == NULL || ot == Py_None)
671 tt = time(NULL);
672 else {
673 double dt = PyFloat_AsDouble(ot);
674 if (PyErr_Occurred())
675 return NULL;
676 tt = _PyTime_DoubleToTimet(dt);
677 if (tt == (time_t)-1 && PyErr_Occurred())
678 return NULL;
679 }
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000680 timeptr = localtime(&tt);
681 if (timeptr == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000682 PyErr_SetString(PyExc_ValueError, "unconvertible time");
Alexander Belopolsky5da468f2011-01-04 17:15:52 +0000683 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000684 }
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000685 return _asctime(timeptr);
Guido van Rossum9e90a671993-06-24 11:10:19 +0000686}
687
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000688PyDoc_STRVAR(ctime_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000689"ctime(seconds) -> string\n\
690\n\
691Convert a time in seconds since the Epoch to a string in local time.\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000692This is equivalent to asctime(localtime(seconds)). When the time tuple is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000693not present, current time as returned by localtime() is used.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000694
Guido van Rossum60cd8131998-03-06 17:16:21 +0000695#ifdef HAVE_MKTIME
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000696static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000697time_mktime(PyObject *self, PyObject *tup)
Guido van Rossum234f9421993-06-17 12:35:49 +0000698{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000699 struct tm buf;
700 time_t tt;
701 if (!gettmarg(tup, &buf))
702 return NULL;
Alexander Belopolskyb7d40d12011-01-11 01:21:25 +0000703 buf.tm_wday = -1; /* sentinel; original value ignored */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000704 tt = mktime(&buf);
Alexander Belopolskyb7d40d12011-01-11 01:21:25 +0000705 /* Return value of -1 does not necessarily mean an error, but tm_wday
Ezio Melotti13925002011-03-16 11:05:33 +0200706 * cannot remain set to -1 if mktime succeeded. */
Alexander Belopolskyb7d40d12011-01-11 01:21:25 +0000707 if (tt == (time_t)(-1) && buf.tm_wday == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000708 PyErr_SetString(PyExc_OverflowError,
709 "mktime argument out of range");
710 return NULL;
711 }
712 return PyFloat_FromDouble((double)tt);
Guido van Rossum234f9421993-06-17 12:35:49 +0000713}
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000714
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000715PyDoc_STRVAR(mktime_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000716"mktime(tuple) -> floating point number\n\
717\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000718Convert a time tuple in local time to seconds since the Epoch.");
Guido van Rossum60cd8131998-03-06 17:16:21 +0000719#endif /* HAVE_MKTIME */
Guido van Rossum234f9421993-06-17 12:35:49 +0000720
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000721#ifdef HAVE_WORKING_TZSET
Martin v. Löwis1a214512008-06-11 05:26:20 +0000722static void PyInit_timezone(PyObject *module);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000723
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000724static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000725time_tzset(PyObject *self, PyObject *unused)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000726{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000727 PyObject* m;
Fred Drake9bb74322002-04-01 14:49:59 +0000728
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000729 m = PyImport_ImportModuleNoBlock("time");
730 if (m == NULL) {
731 return NULL;
732 }
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000733
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000734 tzset();
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000735
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000736 /* Reset timezone, altzone, daylight and tzname */
737 PyInit_timezone(m);
738 Py_DECREF(m);
Tim Peters1b6f7a92004-06-20 02:50:16 +0000739
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000740 Py_INCREF(Py_None);
741 return Py_None;
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000742}
743
744PyDoc_STRVAR(tzset_doc,
R. David Murray4d55bf92010-12-14 00:55:46 +0000745"tzset()\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000746\n\
747Initialize, or reinitialize, the local timezone to the value stored in\n\
748os.environ['TZ']. The TZ environment variable should be specified in\n\
Neal Norwitzdc8e1942004-07-20 22:34:37 +0000749standard Unix timezone format as documented in the tzset man page\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000750(eg. 'US/Eastern', 'Europe/Amsterdam'). Unknown timezones will silently\n\
751fall back to UTC. If the TZ environment variable is not set, the local\n\
752timezone is set to the systems best guess of wallclock time.\n\
753Changing the TZ environment variable without calling tzset *may* change\n\
754the local timezone used by methods such as localtime, but this behaviour\n\
755should not be relied on.");
756#endif /* HAVE_WORKING_TZSET */
757
Martin v. Löwisd218dc12008-04-07 03:17:54 +0000758static void
Martin v. Löwis1a214512008-06-11 05:26:20 +0000759PyInit_timezone(PyObject *m) {
760 /* This code moved from PyInit_time wholesale to allow calling it from
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000761 time_tzset. In the future, some parts of it can be moved back
762 (for platforms that don't HAVE_WORKING_TZSET, when we know what they
763 are), and the extraneous calls to tzset(3) should be removed.
764 I haven't done this yet, as I don't want to change this code as
765 little as possible when introducing the time.tzset and time.tzsetwall
766 methods. This should simply be a method of doing the following once,
767 at the top of this function and removing the call to tzset() from
768 time_tzset():
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000769
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000770 #ifdef HAVE_TZSET
771 tzset()
772 #endif
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000773
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000774 And I'm lazy and hate C so nyer.
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000775 */
Guido van Rossum10b164a2001-09-25 13:59:01 +0000776#if defined(HAVE_TZNAME) && !defined(__GLIBC__) && !defined(__CYGWIN__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000777 PyObject *otz0, *otz1;
778 tzset();
Guido van Rossum26452411998-09-28 22:07:11 +0000779#ifdef PYOS_OS2
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000780 PyModule_AddIntConstant(m, "timezone", _timezone);
Guido van Rossum26452411998-09-28 22:07:11 +0000781#else /* !PYOS_OS2 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000782 PyModule_AddIntConstant(m, "timezone", timezone);
Guido van Rossum26452411998-09-28 22:07:11 +0000783#endif /* PYOS_OS2 */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000784#ifdef HAVE_ALTZONE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000785 PyModule_AddIntConstant(m, "altzone", altzone);
Guido van Rossumb6775db1994-08-01 11:34:53 +0000786#else
Guido van Rossum26452411998-09-28 22:07:11 +0000787#ifdef PYOS_OS2
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000788 PyModule_AddIntConstant(m, "altzone", _timezone-3600);
Guido van Rossum26452411998-09-28 22:07:11 +0000789#else /* !PYOS_OS2 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000790 PyModule_AddIntConstant(m, "altzone", timezone-3600);
Guido van Rossum26452411998-09-28 22:07:11 +0000791#endif /* PYOS_OS2 */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000792#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000793 PyModule_AddIntConstant(m, "daylight", daylight);
Victor Stinner720f34a2011-12-09 20:19:24 +0100794 otz0 = PyUnicode_DecodeFSDefaultAndSize(tzname[0], strlen(tzname[0]));
795 otz1 = PyUnicode_DecodeFSDefaultAndSize(tzname[1], strlen(tzname[1]));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000796 PyModule_AddObject(m, "tzname", Py_BuildValue("(NN)", otz0, otz1));
Guido van Rossum10b164a2001-09-25 13:59:01 +0000797#else /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/
Martin v. Löwis60a5d722002-10-16 20:28:25 +0000798#ifdef HAVE_STRUCT_TM_TM_ZONE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000799 {
Guido van Rossum234f9421993-06-17 12:35:49 +0000800#define YEAR ((time_t)((365 * 24 + 6) * 3600))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000801 time_t t;
802 struct tm *p;
803 long janzone, julyzone;
804 char janname[10], julyname[10];
805 t = (time((time_t *)0) / YEAR) * YEAR;
806 p = localtime(&t);
807 janzone = -p->tm_gmtoff;
808 strncpy(janname, p->tm_zone ? p->tm_zone : " ", 9);
809 janname[9] = '\0';
810 t += YEAR/2;
811 p = localtime(&t);
812 julyzone = -p->tm_gmtoff;
813 strncpy(julyname, p->tm_zone ? p->tm_zone : " ", 9);
814 julyname[9] = '\0';
Guido van Rossum10b164a2001-09-25 13:59:01 +0000815
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000816 if( janzone < julyzone ) {
817 /* DST is reversed in the southern hemisphere */
818 PyModule_AddIntConstant(m, "timezone", julyzone);
819 PyModule_AddIntConstant(m, "altzone", janzone);
820 PyModule_AddIntConstant(m, "daylight",
821 janzone != julyzone);
822 PyModule_AddObject(m, "tzname",
823 Py_BuildValue("(zz)",
824 julyname, janname));
825 } else {
826 PyModule_AddIntConstant(m, "timezone", janzone);
827 PyModule_AddIntConstant(m, "altzone", julyzone);
828 PyModule_AddIntConstant(m, "daylight",
829 janzone != julyzone);
830 PyModule_AddObject(m, "tzname",
831 Py_BuildValue("(zz)",
832 janname, julyname));
833 }
834 }
Guido van Rossume6a4b7b1997-10-08 15:27:56 +0000835#else
Martin v. Löwis60a5d722002-10-16 20:28:25 +0000836#endif /* HAVE_STRUCT_TM_TM_ZONE */
Tim Peters26ae7cd2001-03-20 03:26:49 +0000837#ifdef __CYGWIN__
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000838 tzset();
839 PyModule_AddIntConstant(m, "timezone", _timezone);
840 PyModule_AddIntConstant(m, "altzone", _timezone-3600);
841 PyModule_AddIntConstant(m, "daylight", _daylight);
842 PyModule_AddObject(m, "tzname",
843 Py_BuildValue("(zz)", _tzname[0], _tzname[1]));
Tim Peters26ae7cd2001-03-20 03:26:49 +0000844#endif /* __CYGWIN__ */
Guido van Rossum10b164a2001-09-25 13:59:01 +0000845#endif /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000846}
847
848
849static PyMethodDef time_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000850 {"time", time_time, METH_NOARGS, time_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000851#ifdef HAVE_CLOCK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000852 {"clock", time_clock, METH_NOARGS, clock_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000853#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000854 {"sleep", time_sleep, METH_VARARGS, sleep_doc},
855 {"gmtime", time_gmtime, METH_VARARGS, gmtime_doc},
856 {"localtime", time_localtime, METH_VARARGS, localtime_doc},
857 {"asctime", time_asctime, METH_VARARGS, asctime_doc},
858 {"ctime", time_ctime, METH_VARARGS, ctime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000859#ifdef HAVE_MKTIME
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000860 {"mktime", time_mktime, METH_O, mktime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000861#endif
862#ifdef HAVE_STRFTIME
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000863 {"strftime", time_strftime, METH_VARARGS, strftime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000864#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000865 {"strptime", time_strptime, METH_VARARGS, strptime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000866#ifdef HAVE_WORKING_TZSET
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000867 {"tzset", time_tzset, METH_NOARGS, tzset_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000868#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000869 {NULL, NULL} /* sentinel */
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000870};
871
872
873PyDoc_STRVAR(module_doc,
874"This module provides various functions to manipulate time values.\n\
875\n\
876There are two standard representations of time. One is the number\n\
877of seconds since the Epoch, in UTC (a.k.a. GMT). It may be an integer\n\
878or a floating point number (to represent fractions of seconds).\n\
879The Epoch is system-defined; on Unix, it is generally January 1st, 1970.\n\
880The actual value can be retrieved by calling gmtime(0).\n\
881\n\
882The other representation is a tuple of 9 integers giving local time.\n\
883The tuple items are:\n\
884 year (four digits, e.g. 1998)\n\
885 month (1-12)\n\
886 day (1-31)\n\
887 hours (0-23)\n\
888 minutes (0-59)\n\
889 seconds (0-59)\n\
890 weekday (0-6, Monday is 0)\n\
891 Julian day (day in the year, 1-366)\n\
892 DST (Daylight Savings Time) flag (-1, 0 or 1)\n\
893If the DST flag is 0, the time is given in the regular time zone;\n\
894if it is 1, the time is given in the DST time zone;\n\
895if it is -1, mktime() should guess based on the date and time.\n\
896\n\
897Variables:\n\
898\n\
899timezone -- difference in seconds between UTC and local standard time\n\
900altzone -- difference in seconds between UTC and local DST time\n\
901daylight -- whether local time should reflect DST\n\
902tzname -- tuple of (standard time zone name, DST time zone name)\n\
903\n\
904Functions:\n\
905\n\
906time() -- return current time in seconds since the Epoch as a float\n\
907clock() -- return CPU time since process start as a float\n\
908sleep() -- delay for a number of seconds given as a float\n\
909gmtime() -- convert seconds since Epoch to UTC tuple\n\
910localtime() -- convert seconds since Epoch to local time tuple\n\
911asctime() -- convert time tuple to string\n\
912ctime() -- convert time in seconds to string\n\
913mktime() -- convert local time tuple to seconds since Epoch\n\
914strftime() -- convert time tuple to string according to format specification\n\
915strptime() -- parse string to time tuple according to format specification\n\
916tzset() -- change the local timezone");
917
918
Martin v. Löwis1a214512008-06-11 05:26:20 +0000919
920static struct PyModuleDef timemodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000921 PyModuleDef_HEAD_INIT,
922 "time",
923 module_doc,
924 -1,
925 time_methods,
926 NULL,
927 NULL,
928 NULL,
929 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +0000930};
931
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000932PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +0000933PyInit_time(void)
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000934{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000935 PyObject *m;
936 char *p;
937 m = PyModule_Create(&timemodule);
938 if (m == NULL)
939 return NULL;
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000940
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000941 /* Accept 2-digit dates unless PYTHONY2K is set and non-empty */
942 p = Py_GETENV("PYTHONY2K");
943 PyModule_AddIntConstant(m, "accept2dyear", (long) (!p || !*p));
Gregory P. Smith14b04cd2012-11-27 10:16:55 -0800944 /* If an embedded interpreter is shutdown and reinitialized the old
945 moddict was not decrefed on shutdown and the next import of this
946 module leads to a leak. Conditionally decref here to prevent that.
947 */
948 Py_XDECREF(moddict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000949 /* Squirrel away the module's dictionary for the y2k check */
950 moddict = PyModule_GetDict(m);
951 Py_INCREF(moddict);
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000952
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000953 /* Set, or reset, module variables like time.timezone */
954 PyInit_timezone(m);
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000955
Mark Hammond975e3922002-07-16 01:29:19 +0000956#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000957 /* Helper to allow interrupts for Windows.
958 If Ctrl+C event delivered while not sleeping
959 it will be ignored.
960 */
961 main_thread = PyThread_get_thread_ident();
962 hInterruptEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
963 SetConsoleCtrlHandler( PyCtrlHandler, TRUE);
Mark Hammond975e3922002-07-16 01:29:19 +0000964#endif /* MS_WINDOWS */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000965 if (!initialized) {
966 PyStructSequence_InitType(&StructTimeType,
967 &struct_time_type_desc);
968 }
969 Py_INCREF(&StructTimeType);
970 PyModule_AddObject(m, "struct_time", (PyObject*) &StructTimeType);
971 initialized = 1;
972 return m;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000973}
974
Guido van Rossumb6775db1994-08-01 11:34:53 +0000975static double
Thomas Woutersf3f33dc2000-07-21 06:00:07 +0000976floattime(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000977{
Alexander Belopolsky6fc4ade2010-08-05 17:34:27 +0000978 _PyTime_timeval t;
979 _PyTime_gettimeofday(&t);
980 return (double)t.tv_sec + t.tv_usec*0.000001;
Guido van Rossum426035c1991-02-19 12:27:35 +0000981}
982
Guido van Rossumb6775db1994-08-01 11:34:53 +0000983
984/* Implement floatsleep() for various platforms.
985 When interrupted (or when another error occurs), return -1 and
986 set an exception; else return 0. */
987
988static int
Guido van Rossuma320fd31995-03-09 12:14:15 +0000989floatsleep(double secs)
Guido van Rossum426035c1991-02-19 12:27:35 +0000990{
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000991/* XXX Should test for MS_WINDOWS first! */
Skip Montanaroeb33e5a2007-08-17 12:57:41 +0000992#if defined(HAVE_SELECT) && !defined(__EMX__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000993 struct timeval t;
994 double frac;
995 frac = fmod(secs, 1.0);
996 secs = floor(secs);
997 t.tv_sec = (long)secs;
998 t.tv_usec = (long)(frac*1000000.0);
999 Py_BEGIN_ALLOW_THREADS
1000 if (select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &t) != 0) {
Guido van Rossum09cbb011999-11-08 15:32:27 +00001001#ifdef EINTR
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001002 if (errno != EINTR) {
Guido van Rossum09cbb011999-11-08 15:32:27 +00001003#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001004 if (1) {
Guido van Rossum09cbb011999-11-08 15:32:27 +00001005#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001006 Py_BLOCK_THREADS
1007 PyErr_SetFromErrno(PyExc_IOError);
1008 return -1;
1009 }
1010 }
1011 Py_END_ALLOW_THREADS
Martin v. Löwis02af9642002-01-16 11:04:06 +00001012#elif defined(__WATCOMC__) && !defined(__QNX__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001013 /* XXX Can't interrupt this sleep */
1014 Py_BEGIN_ALLOW_THREADS
1015 delay((int)(secs * 1000 + 0.5)); /* delay() uses milliseconds */
1016 Py_END_ALLOW_THREADS
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001017#elif defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001018 {
1019 double millisecs = secs * 1000.0;
1020 unsigned long ul_millis;
Tim Peters513a1cd2003-01-19 04:54:58 +00001021
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001022 if (millisecs > (double)ULONG_MAX) {
1023 PyErr_SetString(PyExc_OverflowError,
1024 "sleep length is too large");
1025 return -1;
1026 }
1027 Py_BEGIN_ALLOW_THREADS
1028 /* Allow sleep(0) to maintain win32 semantics, and as decreed
1029 * by Guido, only the main thread can be interrupted.
1030 */
1031 ul_millis = (unsigned long)millisecs;
1032 if (ul_millis == 0 ||
1033 main_thread != PyThread_get_thread_ident())
1034 Sleep(ul_millis);
1035 else {
1036 DWORD rc;
1037 ResetEvent(hInterruptEvent);
1038 rc = WaitForSingleObject(hInterruptEvent, ul_millis);
1039 if (rc == WAIT_OBJECT_0) {
1040 /* Yield to make sure real Python signal
1041 * handler called.
1042 */
1043 Sleep(1);
1044 Py_BLOCK_THREADS
1045 errno = EINTR;
1046 PyErr_SetFromErrno(PyExc_IOError);
1047 return -1;
1048 }
1049 }
1050 Py_END_ALLOW_THREADS
1051 }
Martin v. Löwis02af9642002-01-16 11:04:06 +00001052#elif defined(PYOS_OS2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001053 /* This Sleep *IS* Interruptable by Exceptions */
1054 Py_BEGIN_ALLOW_THREADS
1055 if (DosSleep(secs * 1000) != NO_ERROR) {
1056 Py_BLOCK_THREADS
1057 PyErr_SetFromErrno(PyExc_IOError);
1058 return -1;
1059 }
1060 Py_END_ALLOW_THREADS
Martin v. Löwis02af9642002-01-16 11:04:06 +00001061#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001062 /* XXX Can't interrupt this sleep */
1063 Py_BEGIN_ALLOW_THREADS
1064 sleep((int)secs);
1065 Py_END_ALLOW_THREADS
Martin v. Löwis02af9642002-01-16 11:04:06 +00001066#endif
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001067
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001068 return 0;
Guido van Rossum80c9d881991-04-16 08:47:51 +00001069}