blob: 18fe13f2ef8208bd14af408bd8489c321459d4dd [file] [log] [blame]
Guido van Rossumf70e43a1991-02-19 12:39:46 +00001
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002/* Time module */
3
Barry Warsaw9a2a8a81996-12-06 23:32:14 +00004#include "Python.h"
Guido van Rossum98bf58f2001-10-18 20:34:25 +00005#include "structseq.h"
Tim Peters1b6f7a92004-06-20 02:50:16 +00006#include "timefuncs.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +00007
Martin v. Löwis8a7c8662007-08-30 15:40:24 +00008#define TZNAME_ENCODING "utf-8"
9
Thomas Wouters477c8d52006-05-27 19:21:47 +000010#ifdef __APPLE__
11#if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_FTIME)
12 /*
13 * floattime falls back to ftime when getttimeofday fails because the latter
14 * might fail on some platforms. This fallback is unwanted on MacOSX because
15 * that makes it impossible to use a binary build on OSX 10.4 on earlier
16 * releases of the OS. Therefore claim we don't support ftime.
17 */
18# undef HAVE_FTIME
19#endif
20#endif
21
Guido van Rossum87ce7bb1998-06-09 16:30:31 +000022#include <ctype.h>
23
Thomas Wouters0e3f5912006-08-11 14:57:12 +000024#ifdef HAVE_SYS_TYPES_H
Guido van Rossumb6775db1994-08-01 11:34:53 +000025#include <sys/types.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +000026#endif /* HAVE_SYS_TYPES_H */
Guido van Rossum6d946f91992-08-14 13:49:30 +000027
Guido van Rossumb6775db1994-08-01 11:34:53 +000028#ifdef QUICKWIN
29#include <io.h>
30#endif
31
Guido van Rossumb6775db1994-08-01 11:34:53 +000032#ifdef HAVE_FTIME
33#include <sys/timeb.h>
Guido van Rossum8e9ebfd1997-11-22 21:53:48 +000034#if !defined(MS_WINDOWS) && !defined(PYOS_OS2)
Thomas Woutersbd4bc4e2000-07-22 23:57:55 +000035extern int ftime(struct timeb *);
Guido van Rossum52174571996-12-09 18:38:52 +000036#endif /* MS_WINDOWS */
37#endif /* HAVE_FTIME */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000038
Guido van Rossum7bf22de1997-12-02 20:34:19 +000039#if defined(__WATCOMC__) && !defined(__QNX__)
Guido van Rossumbceeac81996-05-23 22:53:47 +000040#include <i86.h>
41#else
Guido van Rossumcac6c721996-09-06 13:34:02 +000042#ifdef MS_WINDOWS
Mark Hammond975e3922002-07-16 01:29:19 +000043#define WIN32_LEAN_AND_MEAN
Guido van Rossum258ccd42001-03-02 06:53:29 +000044#include <windows.h>
Mark Hammond975e3922002-07-16 01:29:19 +000045#include "pythread.h"
46
47/* helper to allow us to interrupt sleep() on Windows*/
48static HANDLE hInterruptEvent = NULL;
49static BOOL WINAPI PyCtrlHandler(DWORD dwCtrlType)
50{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000051 SetEvent(hInterruptEvent);
52 /* allow other default handlers to be called.
53 Default Python handler will setup the
54 KeyboardInterrupt exception.
55 */
56 return FALSE;
Mark Hammond975e3922002-07-16 01:29:19 +000057}
58static long main_thread;
59
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000060#if defined(__BORLANDC__)
Guido van Rossumb2fb3641996-09-07 00:47:35 +000061/* These overrides not needed for Win32 */
Guido van Rossumb6775db1994-08-01 11:34:53 +000062#define timezone _timezone
Guido van Rossumcc081121995-03-14 15:05:41 +000063#define tzname _tzname
64#define daylight _daylight
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000065#endif /* __BORLANDC__ */
Guido van Rossumcac6c721996-09-06 13:34:02 +000066#endif /* MS_WINDOWS */
Guido van Rossum7bf22de1997-12-02 20:34:19 +000067#endif /* !__WATCOMC__ || __QNX__ */
Guido van Rossum234f9421993-06-17 12:35:49 +000068
Thomas Wouters477c8d52006-05-27 19:21:47 +000069#if defined(MS_WINDOWS) && !defined(__BORLANDC__)
70/* Win32 has better clock replacement; we have our own version below. */
71#undef HAVE_CLOCK
Martin v. Löwis3bb00702007-08-30 14:37:48 +000072#undef TZNAME_ENCODING
73#define TZNAME_ENCODING "mbcs"
Thomas Wouters477c8d52006-05-27 19:21:47 +000074#endif /* MS_WINDOWS && !defined(__BORLANDC__) */
Guido van Rossum3917c221997-04-02 05:35:28 +000075
Andrew MacIntyre7bf68332002-03-03 02:59:16 +000076#if defined(PYOS_OS2)
77#define INCL_DOS
78#define INCL_ERRORS
79#include <os2.h>
80#endif
81
Guido van Rossum8e9ebfd1997-11-22 21:53:48 +000082#if defined(PYCC_VACPP)
Guido van Rossum26452411998-09-28 22:07:11 +000083#include <sys/time.h>
Guido van Rossum8e9ebfd1997-11-22 21:53:48 +000084#endif
85
Guido van Rossum234f9421993-06-17 12:35:49 +000086/* Forward declarations */
Tim Petersdbd9ba62000-07-09 03:09:57 +000087static int floatsleep(double);
Thomas Woutersed77bac2000-07-24 15:26:39 +000088static double floattime(void);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000089
Guido van Rossumcfbaecc1998-08-25 14:51:12 +000090/* For Y2K check */
91static PyObject *moddict;
92
Tim Peters1b6f7a92004-06-20 02:50:16 +000093/* Exposed in timefuncs.h. */
94time_t
Brett Cannon298c3802004-06-19 20:48:43 +000095_PyTime_DoubleToTimet(double x)
96{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000097 time_t result;
98 double diff;
Brett Cannon298c3802004-06-19 20:48:43 +000099
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000100 result = (time_t)x;
101 /* How much info did we lose? time_t may be an integral or
102 * floating type, and we don't know which. If it's integral,
103 * we don't know whether C truncates, rounds, returns the floor,
104 * etc. If we lost a second or more, the C rounding is
105 * unreasonable, or the input just doesn't fit in a time_t;
106 * call it an error regardless. Note that the original cast to
107 * time_t can cause a C error too, but nothing we can do to
108 * worm around that.
109 */
110 diff = x - (double)result;
111 if (diff <= -1.0 || diff >= 1.0) {
112 PyErr_SetString(PyExc_ValueError,
113 "timestamp out of range for platform time_t");
114 result = (time_t)-1;
115 }
116 return result;
Brett Cannon298c3802004-06-19 20:48:43 +0000117}
118
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000119static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000120time_time(PyObject *self, PyObject *unused)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000121{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000122 double secs;
123 secs = floattime();
124 if (secs == 0.0) {
125 PyErr_SetFromErrno(PyExc_IOError);
126 return NULL;
127 }
128 return PyFloat_FromDouble(secs);
Guido van Rossumb6775db1994-08-01 11:34:53 +0000129}
130
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000131PyDoc_STRVAR(time_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000132"time() -> floating point number\n\
133\n\
134Return the current time in seconds since the Epoch.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000135Fractions of a second may be present if the system clock provides them.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000136
Guido van Rossumb6775db1994-08-01 11:34:53 +0000137#ifdef HAVE_CLOCK
138
139#ifndef CLOCKS_PER_SEC
Guido van Rossum1b66a4f1996-02-25 04:50:33 +0000140#ifdef CLK_TCK
141#define CLOCKS_PER_SEC CLK_TCK
142#else
Guido van Rossumb6775db1994-08-01 11:34:53 +0000143#define CLOCKS_PER_SEC 1000000
144#endif
Guido van Rossum1b66a4f1996-02-25 04:50:33 +0000145#endif
Guido van Rossumb6775db1994-08-01 11:34:53 +0000146
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000147static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000148time_clock(PyObject *self, PyObject *unused)
Guido van Rossumb6775db1994-08-01 11:34:53 +0000149{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000150 return PyFloat_FromDouble(((double)clock()) / CLOCKS_PER_SEC);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000151}
Guido van Rossumb6775db1994-08-01 11:34:53 +0000152#endif /* HAVE_CLOCK */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000153
Thomas Wouters477c8d52006-05-27 19:21:47 +0000154#if defined(MS_WINDOWS) && !defined(__BORLANDC__)
Mark Hammond7ba5e812002-02-12 04:02:33 +0000155/* Due to Mark Hammond and Tim Peters */
Guido van Rossum3917c221997-04-02 05:35:28 +0000156static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000157time_clock(PyObject *self, PyObject *unused)
Guido van Rossum3917c221997-04-02 05:35:28 +0000158{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000159 static LARGE_INTEGER ctrStart;
160 static double divisor = 0.0;
161 LARGE_INTEGER now;
162 double diff;
Guido van Rossum3917c221997-04-02 05:35:28 +0000163
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000164 if (divisor == 0.0) {
165 LARGE_INTEGER freq;
166 QueryPerformanceCounter(&ctrStart);
167 if (!QueryPerformanceFrequency(&freq) || freq.QuadPart == 0) {
168 /* Unlikely to happen - this works on all intel
169 machines at least! Revert to clock() */
170 return PyFloat_FromDouble(((double)clock()) /
171 CLOCKS_PER_SEC);
172 }
173 divisor = (double)freq.QuadPart;
174 }
175 QueryPerformanceCounter(&now);
176 diff = (double)(now.QuadPart - ctrStart.QuadPart);
177 return PyFloat_FromDouble(diff / divisor);
Guido van Rossum3917c221997-04-02 05:35:28 +0000178}
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000179
Guido van Rossum3917c221997-04-02 05:35:28 +0000180#define HAVE_CLOCK /* So it gets included in the methods */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000181#endif /* MS_WINDOWS && !defined(__BORLANDC__) */
Guido van Rossum3917c221997-04-02 05:35:28 +0000182
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000183#ifdef HAVE_CLOCK
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000184PyDoc_STRVAR(clock_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000185"clock() -> floating point number\n\
186\n\
187Return the CPU time or real time since the start of the process or since\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000188the first call to clock(). This has as much precision as the system\n\
189records.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000190#endif
191
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000192static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000193time_sleep(PyObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000194{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000195 double secs;
196 if (!PyArg_ParseTuple(args, "d:sleep", &secs))
197 return NULL;
198 if (floatsleep(secs) != 0)
199 return NULL;
200 Py_INCREF(Py_None);
201 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000202}
203
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000204PyDoc_STRVAR(sleep_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000205"sleep(seconds)\n\
206\n\
207Delay execution for a given number of seconds. The argument may be\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000208a floating point number for subsecond precision.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000209
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000210static PyStructSequence_Field struct_time_type_fields[] = {
Alexander Belopolsky69f3fd02010-06-05 15:04:51 +0000211 {"tm_year", "year, for example, 1993"},
212 {"tm_mon", "month of year, range [1, 12]"},
213 {"tm_mday", "day of month, range [1, 31]"},
214 {"tm_hour", "hours, range [0, 23]"},
215 {"tm_min", "minutes, range [0, 59]"},
216 {"tm_sec", "seconds, range [0, 61])"},
217 {"tm_wday", "day of week, range [0, 6], Monday is 0"},
218 {"tm_yday", "day of year, range [1, 366]"},
219 {"tm_isdst", "1 if summer time is in effect, 0 if not, and -1 if unknown"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000220 {0}
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000221};
222
223static PyStructSequence_Desc struct_time_type_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000224 "time.struct_time",
Alexander Belopolsky69f3fd02010-06-05 15:04:51 +0000225 "The time value as returned by gmtime(), localtime(), and strptime(), and\n"
226 " accepted by asctime(), mktime() and strftime(). May be considered as a\n"
227 " sequence of 9 integers.\n\n"
228 " Note that several fields' values are not the same as those defined by\n"
229 " the C language standard for struct tm. For example, the value of the\n"
230 " field tm_year is the actual year, not year - 1900. See individual\n"
231 " fields' descriptions for details.",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000232 struct_time_type_fields,
233 9,
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000234};
Tim Peters9ad4b682002-02-13 05:14:18 +0000235
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000236static int initialized;
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000237static PyTypeObject StructTimeType;
238
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000239static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000240tmtotuple(struct tm *p)
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000241{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000242 PyObject *v = PyStructSequence_New(&StructTimeType);
243 if (v == NULL)
244 return NULL;
Tim Peters9ad4b682002-02-13 05:14:18 +0000245
Christian Heimes217cfd12007-12-02 14:31:20 +0000246#define SET(i,val) PyStructSequence_SET_ITEM(v, i, PyLong_FromLong((long) val))
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000247
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000248 SET(0, p->tm_year + 1900);
249 SET(1, p->tm_mon + 1); /* Want January == 1 */
250 SET(2, p->tm_mday);
251 SET(3, p->tm_hour);
252 SET(4, p->tm_min);
253 SET(5, p->tm_sec);
254 SET(6, (p->tm_wday + 6) % 7); /* Want Monday == 0 */
255 SET(7, p->tm_yday + 1); /* Want January, 1 == 1 */
256 SET(8, p->tm_isdst);
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000257#undef SET
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000258 if (PyErr_Occurred()) {
259 Py_XDECREF(v);
260 return NULL;
261 }
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000262
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000263 return v;
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000264}
265
266static PyObject *
Skip Montanaro41cfce92007-08-24 21:11:00 +0000267structtime_totuple(PyObject *t)
268{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000269 PyObject *x = NULL;
270 unsigned int i;
271 PyObject *v = PyTuple_New(9);
272 if (v == NULL)
273 return NULL;
Skip Montanaro41cfce92007-08-24 21:11:00 +0000274
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000275 for (i=0; i<9; i++) {
276 x = PyStructSequence_GET_ITEM(t, i);
277 Py_INCREF(x);
278 PyTuple_SET_ITEM(v, i, x);
279 }
Skip Montanaro41cfce92007-08-24 21:11:00 +0000280
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000281 if (PyErr_Occurred()) {
282 Py_XDECREF(v);
283 return NULL;
284 }
Skip Montanaro41cfce92007-08-24 21:11:00 +0000285
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000286 return v;
Skip Montanaro41cfce92007-08-24 21:11:00 +0000287}
288
289static PyObject *
Brett Cannon298c3802004-06-19 20:48:43 +0000290time_convert(double when, struct tm * (*function)(const time_t *))
Guido van Rossum234f9421993-06-17 12:35:49 +0000291{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000292 struct tm *p;
293 time_t whent = _PyTime_DoubleToTimet(when);
Brett Cannon298c3802004-06-19 20:48:43 +0000294
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000295 if (whent == (time_t)-1 && PyErr_Occurred())
296 return NULL;
297 errno = 0;
298 p = function(&whent);
299 if (p == NULL) {
Guido van Rossum6e8583d1996-10-08 14:19:52 +0000300#ifdef EINVAL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000301 if (errno == 0)
302 errno = EINVAL;
Guido van Rossum6e8583d1996-10-08 14:19:52 +0000303#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000304 return PyErr_SetFromErrno(PyExc_ValueError);
305 }
306 return tmtotuple(p);
Guido van Rossum234f9421993-06-17 12:35:49 +0000307}
308
Fred Drakef901abd2004-08-03 17:58:55 +0000309/* Parse arg tuple that can contain an optional float-or-None value;
310 format needs to be "|O:name".
311 Returns non-zero on success (parallels PyArg_ParseTuple).
312*/
313static int
314parse_time_double_args(PyObject *args, char *format, double *pwhen)
315{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000316 PyObject *ot = NULL;
Fred Drakef901abd2004-08-03 17:58:55 +0000317
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000318 if (!PyArg_ParseTuple(args, format, &ot))
319 return 0;
320 if (ot == NULL || ot == Py_None)
321 *pwhen = floattime();
322 else {
323 double when = PyFloat_AsDouble(ot);
324 if (PyErr_Occurred())
325 return 0;
326 *pwhen = when;
327 }
328 return 1;
Fred Drakef901abd2004-08-03 17:58:55 +0000329}
330
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000331static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000332time_gmtime(PyObject *self, PyObject *args)
Guido van Rossum234f9421993-06-17 12:35:49 +0000333{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000334 double when;
335 if (!parse_time_double_args(args, "|O:gmtime", &when))
336 return NULL;
337 return time_convert(when, gmtime);
Guido van Rossum234f9421993-06-17 12:35:49 +0000338}
339
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000340PyDoc_STRVAR(gmtime_doc,
Christian Heimes9a371592007-12-28 14:08:13 +0000341"gmtime([seconds]) -> (tm_year, tm_mon, tm_mday, tm_hour, tm_min,\n\
Fred Drake193a3f62002-03-12 21:38:49 +0000342 tm_sec, tm_wday, tm_yday, tm_isdst)\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000343\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000344Convert seconds since the Epoch to a time tuple expressing UTC (a.k.a.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000345GMT). When 'seconds' is not passed in, convert the current time instead.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000346
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000347static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000348time_localtime(PyObject *self, PyObject *args)
Guido van Rossum234f9421993-06-17 12:35:49 +0000349{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000350 double when;
351 if (!parse_time_double_args(args, "|O:localtime", &when))
352 return NULL;
353 return time_convert(when, localtime);
Guido van Rossum234f9421993-06-17 12:35:49 +0000354}
355
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000356PyDoc_STRVAR(localtime_doc,
Christian Heimes9a371592007-12-28 14:08:13 +0000357"localtime([seconds]) -> (tm_year,tm_mon,tm_mday,tm_hour,tm_min,\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000358 tm_sec,tm_wday,tm_yday,tm_isdst)\n\
Martin v. Löwisb3cfc1d2001-12-02 12:27:43 +0000359\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000360Convert seconds since the Epoch to a time tuple expressing local time.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000361When 'seconds' is not passed in, convert the current time instead.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000362
Guido van Rossum9e90a671993-06-24 11:10:19 +0000363static int
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000364gettmarg(PyObject *args, struct tm *p)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000365{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000366 int y;
367 PyObject *t = NULL;
Guido van Rossumcfbaecc1998-08-25 14:51:12 +0000368
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000369 memset((void *) p, '\0', sizeof(struct tm));
Guido van Rossumb9081262007-08-25 03:14:09 +0000370
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000371 if (PyTuple_Check(args)) {
372 t = args;
373 Py_INCREF(t);
374 }
375 else if (Py_TYPE(args) == &StructTimeType) {
376 t = structtime_totuple(args);
377 }
378 else {
379 PyErr_SetString(PyExc_TypeError,
380 "Tuple or struct_time argument required");
381 return 0;
382 }
Skip Montanaro41cfce92007-08-24 21:11:00 +0000383
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000384 if (t == NULL || !PyArg_ParseTuple(t, "iiiiiiiii",
385 &y,
386 &p->tm_mon,
387 &p->tm_mday,
388 &p->tm_hour,
389 &p->tm_min,
390 &p->tm_sec,
391 &p->tm_wday,
392 &p->tm_yday,
393 &p->tm_isdst)) {
394 Py_XDECREF(t);
395 return 0;
396 }
397 Py_DECREF(t);
Skip Montanaro41cfce92007-08-24 21:11:00 +0000398
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000399 if (y < 1900) {
400 PyObject *accept = PyDict_GetItemString(moddict,
401 "accept2dyear");
402 if (accept == NULL || !PyLong_CheckExact(accept) ||
403 !PyObject_IsTrue(accept)) {
404 PyErr_SetString(PyExc_ValueError,
405 "year >= 1900 required");
406 return 0;
407 }
408 if (69 <= y && y <= 99)
409 y += 1900;
410 else if (0 <= y && y <= 68)
411 y += 2000;
412 else {
413 PyErr_SetString(PyExc_ValueError,
414 "year out of range");
415 return 0;
416 }
417 }
418 p->tm_year = y - 1900;
419 p->tm_mon--;
420 p->tm_wday = (p->tm_wday + 1) % 7;
421 p->tm_yday--;
422 return 1;
Guido van Rossum9e90a671993-06-24 11:10:19 +0000423}
424
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000425#ifdef HAVE_STRFTIME
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000426#ifdef HAVE_WCSFTIME
427#define time_char wchar_t
428#define format_time wcsftime
429#define time_strlen wcslen
430#else
431#define time_char char
432#define format_time strftime
433#define time_strlen strlen
434#endif
435
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000436static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000437time_strftime(PyObject *self, PyObject *args)
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000438{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000439 PyObject *tup = NULL;
440 struct tm buf;
441 const time_char *fmt;
442 PyObject *format, *tmpfmt;
443 size_t fmtlen, buflen;
444 time_char *outbuf = 0;
445 size_t i;
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000446
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000447 memset((void *) &buf, '\0', sizeof(buf));
Guido van Rossum1f41f841998-04-27 19:04:26 +0000448
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000449 /* Will always expect a unicode string to be passed as format.
450 Given that there's no str type anymore in py3k this seems safe.
451 */
452 if (!PyArg_ParseTuple(args, "U|O:strftime", &format, &tup))
453 return NULL;
Thomas Woutersfe385252001-01-19 23:16:56 +0000454
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000455 if (tup == NULL) {
456 time_t tt = time(NULL);
457 buf = *localtime(&tt);
458 } else if (!gettmarg(tup, &buf))
459 return NULL;
Guido van Rossum10b164a2001-09-25 13:59:01 +0000460
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000461 /* Checks added to make sure strftime() does not crash Python by
462 indexing blindly into some array for a textual representation
463 by some bad index (fixes bug #897625).
Tim Peters1b6f7a92004-06-20 02:50:16 +0000464
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000465 Also support values of zero from Python code for arguments in which
466 that is out of range by forcing that value to the lowest value that
467 is valid (fixed bug #1520914).
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000468
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000469 Valid ranges based on what is allowed in struct tm:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000470
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000471 - tm_year: [0, max(int)] (1)
472 - tm_mon: [0, 11] (2)
473 - tm_mday: [1, 31]
474 - tm_hour: [0, 23]
475 - tm_min: [0, 59]
476 - tm_sec: [0, 60]
477 - tm_wday: [0, 6] (1)
478 - tm_yday: [0, 365] (2)
479 - tm_isdst: [-max(int), max(int)]
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000480
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000481 (1) gettmarg() handles bounds-checking.
482 (2) Python's acceptable range is one greater than the range in C,
483 thus need to check against automatic decrement by gettmarg().
484 */
485 if (buf.tm_mon == -1)
486 buf.tm_mon = 0;
487 else if (buf.tm_mon < 0 || buf.tm_mon > 11) {
488 PyErr_SetString(PyExc_ValueError, "month out of range");
489 return NULL;
490 }
491 if (buf.tm_mday == 0)
492 buf.tm_mday = 1;
493 else if (buf.tm_mday < 0 || buf.tm_mday > 31) {
494 PyErr_SetString(PyExc_ValueError, "day of month out of range");
495 return NULL;
496 }
497 if (buf.tm_hour < 0 || buf.tm_hour > 23) {
498 PyErr_SetString(PyExc_ValueError, "hour out of range");
499 return NULL;
500 }
501 if (buf.tm_min < 0 || buf.tm_min > 59) {
502 PyErr_SetString(PyExc_ValueError, "minute out of range");
503 return NULL;
504 }
505 if (buf.tm_sec < 0 || buf.tm_sec > 61) {
506 PyErr_SetString(PyExc_ValueError, "seconds out of range");
507 return NULL;
508 }
509 /* tm_wday does not need checking of its upper-bound since taking
510 ``% 7`` in gettmarg() automatically restricts the range. */
511 if (buf.tm_wday < 0) {
512 PyErr_SetString(PyExc_ValueError, "day of week out of range");
513 return NULL;
514 }
515 if (buf.tm_yday == -1)
516 buf.tm_yday = 0;
517 else if (buf.tm_yday < 0 || buf.tm_yday > 365) {
518 PyErr_SetString(PyExc_ValueError, "day of year out of range");
519 return NULL;
520 }
521 /* Normalize tm_isdst just in case someone foolishly implements %Z
522 based on the assumption that tm_isdst falls within the range of
523 [-1, 1] */
524 if (buf.tm_isdst < -1)
525 buf.tm_isdst = -1;
526 else if (buf.tm_isdst > 1)
527 buf.tm_isdst = 1;
Brett Cannond1080a32004-03-02 04:38:10 +0000528
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000529#ifdef HAVE_WCSFTIME
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000530 tmpfmt = PyBytes_FromStringAndSize(NULL,
531 sizeof(wchar_t) * (PyUnicode_GetSize(format)+1));
532 if (!tmpfmt)
533 return NULL;
534 /* This assumes that PyUnicode_AsWideChar doesn't do any UTF-16
535 expansion. */
536 if (PyUnicode_AsWideChar((PyUnicodeObject*)format,
537 (wchar_t*)PyBytes_AS_STRING(tmpfmt),
538 PyUnicode_GetSize(format)+1) == (size_t)-1)
539 /* This shouldn't fail. */
540 Py_FatalError("PyUnicode_AsWideChar failed");
541 format = tmpfmt;
542 fmt = (wchar_t*)PyBytes_AS_STRING(format);
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000543#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000544 /* Convert the unicode string to an ascii one */
545 format = PyUnicode_AsEncodedString(format, TZNAME_ENCODING, NULL);
546 if (format == NULL)
547 return NULL;
548 fmt = PyBytes_AS_STRING(format);
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000549#endif
Amaury Forgeot d'Arcb5be6d42009-03-02 23:52:57 +0000550
Hirokazu Yamamoto6b0e51a2009-06-03 05:19:18 +0000551#if defined(MS_WINDOWS) && defined(HAVE_WCSFTIME)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000552 /* check that the format string contains only valid directives */
553 for(outbuf = wcschr(fmt, L'%');
554 outbuf != NULL;
555 outbuf = wcschr(outbuf+2, L'%'))
556 {
557 if (outbuf[1]=='#')
558 ++outbuf; /* not documented by python, */
559 if (outbuf[1]=='\0' ||
560 !wcschr(L"aAbBcdfHIjmMpSUwWxXyYzZ%", outbuf[1]))
561 {
562 PyErr_SetString(PyExc_ValueError, "Invalid format string");
563 return 0;
564 }
565 }
Amaury Forgeot d'Arcb5be6d42009-03-02 23:52:57 +0000566#endif
567
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000568 fmtlen = time_strlen(fmt);
Guido van Rossumc222ec21999-02-23 00:00:10 +0000569
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000570 /* I hate these functions that presume you know how big the output
571 * will be ahead of time...
572 */
573 for (i = 1024; ; i += i) {
574 outbuf = (time_char *)PyMem_Malloc(i*sizeof(time_char));
575 if (outbuf == NULL) {
576 Py_DECREF(format);
577 return PyErr_NoMemory();
578 }
579 buflen = format_time(outbuf, i, fmt, &buf);
580 if (buflen > 0 || i >= 256 * fmtlen) {
581 /* If the buffer is 256 times as long as the format,
582 it's probably not failing for lack of room!
583 More likely, the format yields an empty result,
584 e.g. an empty format, or %Z when the timezone
585 is unknown. */
586 PyObject *ret;
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000587#ifdef HAVE_WCSFTIME
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000588 ret = PyUnicode_FromWideChar(outbuf, buflen);
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000589#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000590 ret = PyUnicode_Decode(outbuf, buflen,
591 TZNAME_ENCODING, NULL);
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000592#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000593 PyMem_Free(outbuf);
594 Py_DECREF(format);
595 return ret;
596 }
597 PyMem_Free(outbuf);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000598#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000599 /* VisualStudio .NET 2005 does this properly */
600 if (buflen == 0 && errno == EINVAL) {
601 PyErr_SetString(PyExc_ValueError, "Invalid format string");
602 Py_DECREF(format);
603 return 0;
604 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000605#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000606 }
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000607}
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000608
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000609#undef time_char
610#undef format_time
611
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000612PyDoc_STRVAR(strftime_doc,
Thomas Woutersfe385252001-01-19 23:16:56 +0000613"strftime(format[, tuple]) -> string\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000614\n\
615Convert a time tuple to a string according to a format specification.\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000616See the library reference manual for formatting codes. When the time tuple\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000617is not present, current time as returned by localtime() is used.");
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000618#endif /* HAVE_STRFTIME */
619
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000620static PyObject *
621time_strptime(PyObject *self, PyObject *args)
622{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000623 PyObject *strptime_module = PyImport_ImportModuleNoBlock("_strptime");
624 PyObject *strptime_result;
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000625
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000626 if (!strptime_module)
627 return NULL;
628 strptime_result = PyObject_CallMethod(strptime_module,
629 "_strptime_time", "O", args);
630 Py_DECREF(strptime_module);
631 return strptime_result;
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000632}
633
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000634PyDoc_STRVAR(strptime_doc,
Brett Cannon20def8b2003-07-01 05:16:08 +0000635"strptime(string, format) -> struct_time\n\
Martin v. Löwisb3cfc1d2001-12-02 12:27:43 +0000636\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000637Parse a string to a time tuple according to a format specification.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000638See the library reference manual for formatting codes (same as strftime()).");
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000639
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000640
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000641static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000642time_asctime(PyObject *self, PyObject *args)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000643{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000644 PyObject *tup = NULL;
645 struct tm buf;
646 char *p;
647 if (!PyArg_UnpackTuple(args, "asctime", 0, 1, &tup))
648 return NULL;
649 if (tup == NULL) {
650 time_t tt = time(NULL);
651 buf = *localtime(&tt);
652 } else if (!gettmarg(tup, &buf))
653 return NULL;
654 p = asctime(&buf);
655 if (p[24] == '\n')
656 p[24] = '\0';
657 return PyUnicode_FromString(p);
Guido van Rossum9e90a671993-06-24 11:10:19 +0000658}
659
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000660PyDoc_STRVAR(asctime_doc,
Thomas Woutersfe385252001-01-19 23:16:56 +0000661"asctime([tuple]) -> string\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000662\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000663Convert a time tuple to a string, e.g. 'Sat Jun 06 16:26:11 1998'.\n\
664When the time tuple is not present, current time as returned by localtime()\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000665is used.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000666
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000667static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000668time_ctime(PyObject *self, PyObject *args)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000669{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000670 PyObject *ot = NULL;
671 time_t tt;
672 char *p;
Guido van Rossum10b164a2001-09-25 13:59:01 +0000673
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000674 if (!PyArg_UnpackTuple(args, "ctime", 0, 1, &ot))
675 return NULL;
676 if (ot == NULL || ot == Py_None)
677 tt = time(NULL);
678 else {
679 double dt = PyFloat_AsDouble(ot);
680 if (PyErr_Occurred())
681 return NULL;
682 tt = _PyTime_DoubleToTimet(dt);
683 if (tt == (time_t)-1 && PyErr_Occurred())
684 return NULL;
685 }
686 p = ctime(&tt);
687 if (p == NULL) {
688 PyErr_SetString(PyExc_ValueError, "unconvertible time");
689 return NULL;
690 }
691 if (p[24] == '\n')
692 p[24] = '\0';
693 return PyUnicode_FromString(p);
Guido van Rossum9e90a671993-06-24 11:10:19 +0000694}
695
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000696PyDoc_STRVAR(ctime_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000697"ctime(seconds) -> string\n\
698\n\
699Convert a time in seconds since the Epoch to a string in local time.\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000700This is equivalent to asctime(localtime(seconds)). When the time tuple is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000701not present, current time as returned by localtime() is used.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000702
Guido van Rossum60cd8131998-03-06 17:16:21 +0000703#ifdef HAVE_MKTIME
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000704static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000705time_mktime(PyObject *self, PyObject *tup)
Guido van Rossum234f9421993-06-17 12:35:49 +0000706{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000707 struct tm buf;
708 time_t tt;
709 if (!gettmarg(tup, &buf))
710 return NULL;
711 tt = mktime(&buf);
712 if (tt == (time_t)(-1)) {
713 PyErr_SetString(PyExc_OverflowError,
714 "mktime argument out of range");
715 return NULL;
716 }
717 return PyFloat_FromDouble((double)tt);
Guido van Rossum234f9421993-06-17 12:35:49 +0000718}
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000719
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000720PyDoc_STRVAR(mktime_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000721"mktime(tuple) -> floating point number\n\
722\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000723Convert a time tuple in local time to seconds since the Epoch.");
Guido van Rossum60cd8131998-03-06 17:16:21 +0000724#endif /* HAVE_MKTIME */
Guido van Rossum234f9421993-06-17 12:35:49 +0000725
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000726#ifdef HAVE_WORKING_TZSET
Martin v. Löwis1a214512008-06-11 05:26:20 +0000727static void PyInit_timezone(PyObject *module);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000728
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000729static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000730time_tzset(PyObject *self, PyObject *unused)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000731{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000732 PyObject* m;
Fred Drake9bb74322002-04-01 14:49:59 +0000733
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000734 m = PyImport_ImportModuleNoBlock("time");
735 if (m == NULL) {
736 return NULL;
737 }
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000738
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000739 tzset();
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000740
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000741 /* Reset timezone, altzone, daylight and tzname */
742 PyInit_timezone(m);
743 Py_DECREF(m);
Tim Peters1b6f7a92004-06-20 02:50:16 +0000744
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000745 Py_INCREF(Py_None);
746 return Py_None;
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000747}
748
749PyDoc_STRVAR(tzset_doc,
750"tzset(zone)\n\
751\n\
752Initialize, or reinitialize, the local timezone to the value stored in\n\
753os.environ['TZ']. The TZ environment variable should be specified in\n\
Neal Norwitzdc8e1942004-07-20 22:34:37 +0000754standard Unix timezone format as documented in the tzset man page\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000755(eg. 'US/Eastern', 'Europe/Amsterdam'). Unknown timezones will silently\n\
756fall back to UTC. If the TZ environment variable is not set, the local\n\
757timezone is set to the systems best guess of wallclock time.\n\
758Changing the TZ environment variable without calling tzset *may* change\n\
759the local timezone used by methods such as localtime, but this behaviour\n\
760should not be relied on.");
761#endif /* HAVE_WORKING_TZSET */
762
Martin v. Löwisd218dc12008-04-07 03:17:54 +0000763static void
Martin v. Löwis1a214512008-06-11 05:26:20 +0000764PyInit_timezone(PyObject *m) {
765 /* This code moved from PyInit_time wholesale to allow calling it from
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000766 time_tzset. In the future, some parts of it can be moved back
767 (for platforms that don't HAVE_WORKING_TZSET, when we know what they
768 are), and the extraneous calls to tzset(3) should be removed.
769 I haven't done this yet, as I don't want to change this code as
770 little as possible when introducing the time.tzset and time.tzsetwall
771 methods. This should simply be a method of doing the following once,
772 at the top of this function and removing the call to tzset() from
773 time_tzset():
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000774
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000775 #ifdef HAVE_TZSET
776 tzset()
777 #endif
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000778
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000779 And I'm lazy and hate C so nyer.
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000780 */
Guido van Rossum10b164a2001-09-25 13:59:01 +0000781#if defined(HAVE_TZNAME) && !defined(__GLIBC__) && !defined(__CYGWIN__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000782 PyObject *otz0, *otz1;
783 tzset();
Guido van Rossum26452411998-09-28 22:07:11 +0000784#ifdef PYOS_OS2
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000785 PyModule_AddIntConstant(m, "timezone", _timezone);
Guido van Rossum26452411998-09-28 22:07:11 +0000786#else /* !PYOS_OS2 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000787 PyModule_AddIntConstant(m, "timezone", timezone);
Guido van Rossum26452411998-09-28 22:07:11 +0000788#endif /* PYOS_OS2 */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000789#ifdef HAVE_ALTZONE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000790 PyModule_AddIntConstant(m, "altzone", altzone);
Guido van Rossumb6775db1994-08-01 11:34:53 +0000791#else
Guido van Rossum26452411998-09-28 22:07:11 +0000792#ifdef PYOS_OS2
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000793 PyModule_AddIntConstant(m, "altzone", _timezone-3600);
Guido van Rossum26452411998-09-28 22:07:11 +0000794#else /* !PYOS_OS2 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000795 PyModule_AddIntConstant(m, "altzone", timezone-3600);
Guido van Rossum26452411998-09-28 22:07:11 +0000796#endif /* PYOS_OS2 */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000797#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000798 PyModule_AddIntConstant(m, "daylight", daylight);
799 otz0 = PyUnicode_Decode(tzname[0], strlen(tzname[0]), TZNAME_ENCODING, NULL);
800 otz1 = PyUnicode_Decode(tzname[1], strlen(tzname[1]), TZNAME_ENCODING, NULL);
801 PyModule_AddObject(m, "tzname", Py_BuildValue("(NN)", otz0, otz1));
Guido van Rossum10b164a2001-09-25 13:59:01 +0000802#else /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/
Martin v. Löwis60a5d722002-10-16 20:28:25 +0000803#ifdef HAVE_STRUCT_TM_TM_ZONE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000804 {
Guido van Rossum234f9421993-06-17 12:35:49 +0000805#define YEAR ((time_t)((365 * 24 + 6) * 3600))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000806 time_t t;
807 struct tm *p;
808 long janzone, julyzone;
809 char janname[10], julyname[10];
810 t = (time((time_t *)0) / YEAR) * YEAR;
811 p = localtime(&t);
812 janzone = -p->tm_gmtoff;
813 strncpy(janname, p->tm_zone ? p->tm_zone : " ", 9);
814 janname[9] = '\0';
815 t += YEAR/2;
816 p = localtime(&t);
817 julyzone = -p->tm_gmtoff;
818 strncpy(julyname, p->tm_zone ? p->tm_zone : " ", 9);
819 julyname[9] = '\0';
Guido van Rossum10b164a2001-09-25 13:59:01 +0000820
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000821 if( janzone < julyzone ) {
822 /* DST is reversed in the southern hemisphere */
823 PyModule_AddIntConstant(m, "timezone", julyzone);
824 PyModule_AddIntConstant(m, "altzone", janzone);
825 PyModule_AddIntConstant(m, "daylight",
826 janzone != julyzone);
827 PyModule_AddObject(m, "tzname",
828 Py_BuildValue("(zz)",
829 julyname, janname));
830 } else {
831 PyModule_AddIntConstant(m, "timezone", janzone);
832 PyModule_AddIntConstant(m, "altzone", julyzone);
833 PyModule_AddIntConstant(m, "daylight",
834 janzone != julyzone);
835 PyModule_AddObject(m, "tzname",
836 Py_BuildValue("(zz)",
837 janname, julyname));
838 }
839 }
Guido van Rossume6a4b7b1997-10-08 15:27:56 +0000840#else
Martin v. Löwis60a5d722002-10-16 20:28:25 +0000841#endif /* HAVE_STRUCT_TM_TM_ZONE */
Tim Peters26ae7cd2001-03-20 03:26:49 +0000842#ifdef __CYGWIN__
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000843 tzset();
844 PyModule_AddIntConstant(m, "timezone", _timezone);
845 PyModule_AddIntConstant(m, "altzone", _timezone-3600);
846 PyModule_AddIntConstant(m, "daylight", _daylight);
847 PyModule_AddObject(m, "tzname",
848 Py_BuildValue("(zz)", _tzname[0], _tzname[1]));
Tim Peters26ae7cd2001-03-20 03:26:49 +0000849#endif /* __CYGWIN__ */
Guido van Rossum10b164a2001-09-25 13:59:01 +0000850#endif /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000851}
852
853
854static PyMethodDef time_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000855 {"time", time_time, METH_NOARGS, time_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000856#ifdef HAVE_CLOCK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000857 {"clock", time_clock, METH_NOARGS, clock_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000858#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000859 {"sleep", time_sleep, METH_VARARGS, sleep_doc},
860 {"gmtime", time_gmtime, METH_VARARGS, gmtime_doc},
861 {"localtime", time_localtime, METH_VARARGS, localtime_doc},
862 {"asctime", time_asctime, METH_VARARGS, asctime_doc},
863 {"ctime", time_ctime, METH_VARARGS, ctime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000864#ifdef HAVE_MKTIME
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000865 {"mktime", time_mktime, METH_O, mktime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000866#endif
867#ifdef HAVE_STRFTIME
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000868 {"strftime", time_strftime, METH_VARARGS, strftime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000869#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000870 {"strptime", time_strptime, METH_VARARGS, strptime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000871#ifdef HAVE_WORKING_TZSET
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000872 {"tzset", time_tzset, METH_NOARGS, tzset_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000873#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000874 {NULL, NULL} /* sentinel */
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000875};
876
877
878PyDoc_STRVAR(module_doc,
879"This module provides various functions to manipulate time values.\n\
880\n\
881There are two standard representations of time. One is the number\n\
882of seconds since the Epoch, in UTC (a.k.a. GMT). It may be an integer\n\
883or a floating point number (to represent fractions of seconds).\n\
884The Epoch is system-defined; on Unix, it is generally January 1st, 1970.\n\
885The actual value can be retrieved by calling gmtime(0).\n\
886\n\
887The other representation is a tuple of 9 integers giving local time.\n\
888The tuple items are:\n\
889 year (four digits, e.g. 1998)\n\
890 month (1-12)\n\
891 day (1-31)\n\
892 hours (0-23)\n\
893 minutes (0-59)\n\
894 seconds (0-59)\n\
895 weekday (0-6, Monday is 0)\n\
896 Julian day (day in the year, 1-366)\n\
897 DST (Daylight Savings Time) flag (-1, 0 or 1)\n\
898If the DST flag is 0, the time is given in the regular time zone;\n\
899if it is 1, the time is given in the DST time zone;\n\
900if it is -1, mktime() should guess based on the date and time.\n\
901\n\
902Variables:\n\
903\n\
904timezone -- difference in seconds between UTC and local standard time\n\
905altzone -- difference in seconds between UTC and local DST time\n\
906daylight -- whether local time should reflect DST\n\
907tzname -- tuple of (standard time zone name, DST time zone name)\n\
908\n\
909Functions:\n\
910\n\
911time() -- return current time in seconds since the Epoch as a float\n\
912clock() -- return CPU time since process start as a float\n\
913sleep() -- delay for a number of seconds given as a float\n\
914gmtime() -- convert seconds since Epoch to UTC tuple\n\
915localtime() -- convert seconds since Epoch to local time tuple\n\
916asctime() -- convert time tuple to string\n\
917ctime() -- convert time in seconds to string\n\
918mktime() -- convert local time tuple to seconds since Epoch\n\
919strftime() -- convert time tuple to string according to format specification\n\
920strptime() -- parse string to time tuple according to format specification\n\
921tzset() -- change the local timezone");
922
923
Martin v. Löwis1a214512008-06-11 05:26:20 +0000924
925static struct PyModuleDef timemodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000926 PyModuleDef_HEAD_INIT,
927 "time",
928 module_doc,
929 -1,
930 time_methods,
931 NULL,
932 NULL,
933 NULL,
934 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +0000935};
936
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000937PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +0000938PyInit_time(void)
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000939{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000940 PyObject *m;
941 char *p;
942 m = PyModule_Create(&timemodule);
943 if (m == NULL)
944 return NULL;
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000945
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000946 /* Accept 2-digit dates unless PYTHONY2K is set and non-empty */
947 p = Py_GETENV("PYTHONY2K");
948 PyModule_AddIntConstant(m, "accept2dyear", (long) (!p || !*p));
949 /* 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
975
Guido van Rossumb6775db1994-08-01 11:34:53 +0000976/* Implement floattime() for various platforms */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000977
Guido van Rossumb6775db1994-08-01 11:34:53 +0000978static double
Thomas Woutersf3f33dc2000-07-21 06:00:07 +0000979floattime(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000980{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000981 /* There are three ways to get the time:
982 (1) gettimeofday() -- resolution in microseconds
983 (2) ftime() -- resolution in milliseconds
984 (3) time() -- resolution in seconds
985 In all cases the return value is a float in seconds.
986 Since on some systems (e.g. SCO ODT 3.0) gettimeofday() may
987 fail, so we fall back on ftime() or time().
988 Note: clock resolution does not imply clock accuracy! */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000989#ifdef HAVE_GETTIMEOFDAY
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000990 {
991 struct timeval t;
Guido van Rossum3bbc62e1995-01-02 19:30:30 +0000992#ifdef GETTIMEOFDAY_NO_TZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000993 if (gettimeofday(&t) == 0)
994 return (double)t.tv_sec + t.tv_usec*0.000001;
Guido van Rossum3bbc62e1995-01-02 19:30:30 +0000995#else /* !GETTIMEOFDAY_NO_TZ */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000996 if (gettimeofday(&t, (struct timezone *)NULL) == 0)
997 return (double)t.tv_sec + t.tv_usec*0.000001;
Guido van Rossum3bbc62e1995-01-02 19:30:30 +0000998#endif /* !GETTIMEOFDAY_NO_TZ */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000999 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001000
Guido van Rossumb6775db1994-08-01 11:34:53 +00001001#endif /* !HAVE_GETTIMEOFDAY */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001002 {
Guido van Rossumd3eb5771999-03-09 16:07:23 +00001003#if defined(HAVE_FTIME)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001004 struct timeb t;
1005 ftime(&t);
1006 return (double)t.time + (double)t.millitm * (double)0.001;
Guido van Rossumb6775db1994-08-01 11:34:53 +00001007#else /* !HAVE_FTIME */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001008 time_t secs;
1009 time(&secs);
1010 return (double)secs;
Guido van Rossumb6775db1994-08-01 11:34:53 +00001011#endif /* !HAVE_FTIME */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001012 }
Guido van Rossum426035c1991-02-19 12:27:35 +00001013}
1014
Guido van Rossumb6775db1994-08-01 11:34:53 +00001015
1016/* Implement floatsleep() for various platforms.
1017 When interrupted (or when another error occurs), return -1 and
1018 set an exception; else return 0. */
1019
1020static int
Guido van Rossuma320fd31995-03-09 12:14:15 +00001021floatsleep(double secs)
Guido van Rossum426035c1991-02-19 12:27:35 +00001022{
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001023/* XXX Should test for MS_WINDOWS first! */
Skip Montanaroeb33e5a2007-08-17 12:57:41 +00001024#if defined(HAVE_SELECT) && !defined(__EMX__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001025 struct timeval t;
1026 double frac;
1027 frac = fmod(secs, 1.0);
1028 secs = floor(secs);
1029 t.tv_sec = (long)secs;
1030 t.tv_usec = (long)(frac*1000000.0);
1031 Py_BEGIN_ALLOW_THREADS
1032 if (select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &t) != 0) {
Guido van Rossum09cbb011999-11-08 15:32:27 +00001033#ifdef EINTR
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001034 if (errno != EINTR) {
Guido van Rossum09cbb011999-11-08 15:32:27 +00001035#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001036 if (1) {
Guido van Rossum09cbb011999-11-08 15:32:27 +00001037#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001038 Py_BLOCK_THREADS
1039 PyErr_SetFromErrno(PyExc_IOError);
1040 return -1;
1041 }
1042 }
1043 Py_END_ALLOW_THREADS
Martin v. Löwis02af9642002-01-16 11:04:06 +00001044#elif defined(__WATCOMC__) && !defined(__QNX__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001045 /* XXX Can't interrupt this sleep */
1046 Py_BEGIN_ALLOW_THREADS
1047 delay((int)(secs * 1000 + 0.5)); /* delay() uses milliseconds */
1048 Py_END_ALLOW_THREADS
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001049#elif defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001050 {
1051 double millisecs = secs * 1000.0;
1052 unsigned long ul_millis;
Tim Peters513a1cd2003-01-19 04:54:58 +00001053
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001054 if (millisecs > (double)ULONG_MAX) {
1055 PyErr_SetString(PyExc_OverflowError,
1056 "sleep length is too large");
1057 return -1;
1058 }
1059 Py_BEGIN_ALLOW_THREADS
1060 /* Allow sleep(0) to maintain win32 semantics, and as decreed
1061 * by Guido, only the main thread can be interrupted.
1062 */
1063 ul_millis = (unsigned long)millisecs;
1064 if (ul_millis == 0 ||
1065 main_thread != PyThread_get_thread_ident())
1066 Sleep(ul_millis);
1067 else {
1068 DWORD rc;
1069 ResetEvent(hInterruptEvent);
1070 rc = WaitForSingleObject(hInterruptEvent, ul_millis);
1071 if (rc == WAIT_OBJECT_0) {
1072 /* Yield to make sure real Python signal
1073 * handler called.
1074 */
1075 Sleep(1);
1076 Py_BLOCK_THREADS
1077 errno = EINTR;
1078 PyErr_SetFromErrno(PyExc_IOError);
1079 return -1;
1080 }
1081 }
1082 Py_END_ALLOW_THREADS
1083 }
Martin v. Löwis02af9642002-01-16 11:04:06 +00001084#elif defined(PYOS_OS2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001085 /* This Sleep *IS* Interruptable by Exceptions */
1086 Py_BEGIN_ALLOW_THREADS
1087 if (DosSleep(secs * 1000) != NO_ERROR) {
1088 Py_BLOCK_THREADS
1089 PyErr_SetFromErrno(PyExc_IOError);
1090 return -1;
1091 }
1092 Py_END_ALLOW_THREADS
Martin v. Löwis02af9642002-01-16 11:04:06 +00001093#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001094 /* XXX Can't interrupt this sleep */
1095 Py_BEGIN_ALLOW_THREADS
1096 sleep((int)secs);
1097 Py_END_ALLOW_THREADS
Martin v. Löwis02af9642002-01-16 11:04:06 +00001098#endif
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001099
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001100 return 0;
Guido van Rossum80c9d881991-04-16 08:47:51 +00001101}