blob: c4b50144bded863ba0b2785ec7f8e78b54ed18d2 [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
Barry Warsaw9a2a8a81996-12-06 23:32:14 +000093static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000094time_time(PyObject *self, PyObject *unused)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000095{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000096 double secs;
97 secs = floattime();
98 if (secs == 0.0) {
99 PyErr_SetFromErrno(PyExc_IOError);
100 return NULL;
101 }
102 return PyFloat_FromDouble(secs);
Guido van Rossumb6775db1994-08-01 11:34:53 +0000103}
104
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000105PyDoc_STRVAR(time_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000106"time() -> floating point number\n\
107\n\
108Return the current time in seconds since the Epoch.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000109Fractions of a second may be present if the system clock provides them.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000110
Guido van Rossumb6775db1994-08-01 11:34:53 +0000111#ifdef HAVE_CLOCK
112
113#ifndef CLOCKS_PER_SEC
Guido van Rossum1b66a4f1996-02-25 04:50:33 +0000114#ifdef CLK_TCK
115#define CLOCKS_PER_SEC CLK_TCK
116#else
Guido van Rossumb6775db1994-08-01 11:34:53 +0000117#define CLOCKS_PER_SEC 1000000
118#endif
Guido van Rossum1b66a4f1996-02-25 04:50:33 +0000119#endif
Guido van Rossumb6775db1994-08-01 11:34:53 +0000120
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000121static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000122time_clock(PyObject *self, PyObject *unused)
Guido van Rossumb6775db1994-08-01 11:34:53 +0000123{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000124 return PyFloat_FromDouble(((double)clock()) / CLOCKS_PER_SEC);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000125}
Guido van Rossumb6775db1994-08-01 11:34:53 +0000126#endif /* HAVE_CLOCK */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000127
Thomas Wouters477c8d52006-05-27 19:21:47 +0000128#if defined(MS_WINDOWS) && !defined(__BORLANDC__)
Mark Hammond7ba5e812002-02-12 04:02:33 +0000129/* Due to Mark Hammond and Tim Peters */
Guido van Rossum3917c221997-04-02 05:35:28 +0000130static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000131time_clock(PyObject *self, PyObject *unused)
Guido van Rossum3917c221997-04-02 05:35:28 +0000132{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000133 static LARGE_INTEGER ctrStart;
134 static double divisor = 0.0;
135 LARGE_INTEGER now;
136 double diff;
Guido van Rossum3917c221997-04-02 05:35:28 +0000137
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000138 if (divisor == 0.0) {
139 LARGE_INTEGER freq;
140 QueryPerformanceCounter(&ctrStart);
141 if (!QueryPerformanceFrequency(&freq) || freq.QuadPart == 0) {
142 /* Unlikely to happen - this works on all intel
143 machines at least! Revert to clock() */
144 return PyFloat_FromDouble(((double)clock()) /
145 CLOCKS_PER_SEC);
146 }
147 divisor = (double)freq.QuadPart;
148 }
149 QueryPerformanceCounter(&now);
150 diff = (double)(now.QuadPart - ctrStart.QuadPart);
151 return PyFloat_FromDouble(diff / divisor);
Guido van Rossum3917c221997-04-02 05:35:28 +0000152}
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000153
Guido van Rossum3917c221997-04-02 05:35:28 +0000154#define HAVE_CLOCK /* So it gets included in the methods */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000155#endif /* MS_WINDOWS && !defined(__BORLANDC__) */
Guido van Rossum3917c221997-04-02 05:35:28 +0000156
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000157#ifdef HAVE_CLOCK
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000158PyDoc_STRVAR(clock_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000159"clock() -> floating point number\n\
160\n\
161Return the CPU time or real time since the start of the process or since\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000162the first call to clock(). This has as much precision as the system\n\
163records.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000164#endif
165
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000166static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000167time_sleep(PyObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000168{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000169 double secs;
170 if (!PyArg_ParseTuple(args, "d:sleep", &secs))
171 return NULL;
172 if (floatsleep(secs) != 0)
173 return NULL;
174 Py_INCREF(Py_None);
175 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000176}
177
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000178PyDoc_STRVAR(sleep_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000179"sleep(seconds)\n\
180\n\
181Delay execution for a given number of seconds. The argument may be\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000182a floating point number for subsecond precision.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000183
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000184static PyStructSequence_Field struct_time_type_fields[] = {
Alexander Belopolsky69f3fd02010-06-05 15:04:51 +0000185 {"tm_year", "year, for example, 1993"},
186 {"tm_mon", "month of year, range [1, 12]"},
187 {"tm_mday", "day of month, range [1, 31]"},
188 {"tm_hour", "hours, range [0, 23]"},
189 {"tm_min", "minutes, range [0, 59]"},
190 {"tm_sec", "seconds, range [0, 61])"},
191 {"tm_wday", "day of week, range [0, 6], Monday is 0"},
192 {"tm_yday", "day of year, range [1, 366]"},
193 {"tm_isdst", "1 if summer time is in effect, 0 if not, and -1 if unknown"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000194 {0}
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000195};
196
197static PyStructSequence_Desc struct_time_type_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000198 "time.struct_time",
Alexander Belopolsky69f3fd02010-06-05 15:04:51 +0000199 "The time value as returned by gmtime(), localtime(), and strptime(), and\n"
200 " accepted by asctime(), mktime() and strftime(). May be considered as a\n"
201 " sequence of 9 integers.\n\n"
202 " Note that several fields' values are not the same as those defined by\n"
203 " the C language standard for struct tm. For example, the value of the\n"
204 " field tm_year is the actual year, not year - 1900. See individual\n"
205 " fields' descriptions for details.",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000206 struct_time_type_fields,
207 9,
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000208};
Tim Peters9ad4b682002-02-13 05:14:18 +0000209
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000210static int initialized;
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000211static PyTypeObject StructTimeType;
212
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000213static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000214tmtotuple(struct tm *p)
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000215{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000216 PyObject *v = PyStructSequence_New(&StructTimeType);
217 if (v == NULL)
218 return NULL;
Tim Peters9ad4b682002-02-13 05:14:18 +0000219
Christian Heimes217cfd12007-12-02 14:31:20 +0000220#define SET(i,val) PyStructSequence_SET_ITEM(v, i, PyLong_FromLong((long) val))
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000221
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000222 SET(0, p->tm_year + 1900);
223 SET(1, p->tm_mon + 1); /* Want January == 1 */
224 SET(2, p->tm_mday);
225 SET(3, p->tm_hour);
226 SET(4, p->tm_min);
227 SET(5, p->tm_sec);
228 SET(6, (p->tm_wday + 6) % 7); /* Want Monday == 0 */
229 SET(7, p->tm_yday + 1); /* Want January, 1 == 1 */
230 SET(8, p->tm_isdst);
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000231#undef SET
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000232 if (PyErr_Occurred()) {
233 Py_XDECREF(v);
234 return NULL;
235 }
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000236
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000237 return v;
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000238}
239
240static PyObject *
Skip Montanaro41cfce92007-08-24 21:11:00 +0000241structtime_totuple(PyObject *t)
242{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000243 PyObject *x = NULL;
244 unsigned int i;
245 PyObject *v = PyTuple_New(9);
246 if (v == NULL)
247 return NULL;
Skip Montanaro41cfce92007-08-24 21:11:00 +0000248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000249 for (i=0; i<9; i++) {
250 x = PyStructSequence_GET_ITEM(t, i);
251 Py_INCREF(x);
252 PyTuple_SET_ITEM(v, i, x);
253 }
Skip Montanaro41cfce92007-08-24 21:11:00 +0000254
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000255 if (PyErr_Occurred()) {
256 Py_XDECREF(v);
257 return NULL;
258 }
Skip Montanaro41cfce92007-08-24 21:11:00 +0000259
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000260 return v;
Skip Montanaro41cfce92007-08-24 21:11:00 +0000261}
262
263static PyObject *
Brett Cannon298c3802004-06-19 20:48:43 +0000264time_convert(double when, struct tm * (*function)(const time_t *))
Guido van Rossum234f9421993-06-17 12:35:49 +0000265{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000266 struct tm *p;
267 time_t whent = _PyTime_DoubleToTimet(when);
Brett Cannon298c3802004-06-19 20:48:43 +0000268
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000269 if (whent == (time_t)-1 && PyErr_Occurred())
270 return NULL;
271 errno = 0;
272 p = function(&whent);
273 if (p == NULL) {
Guido van Rossum6e8583d1996-10-08 14:19:52 +0000274#ifdef EINVAL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000275 if (errno == 0)
276 errno = EINVAL;
Guido van Rossum6e8583d1996-10-08 14:19:52 +0000277#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000278 return PyErr_SetFromErrno(PyExc_ValueError);
279 }
280 return tmtotuple(p);
Guido van Rossum234f9421993-06-17 12:35:49 +0000281}
282
Fred Drakef901abd2004-08-03 17:58:55 +0000283/* Parse arg tuple that can contain an optional float-or-None value;
284 format needs to be "|O:name".
285 Returns non-zero on success (parallels PyArg_ParseTuple).
286*/
287static int
288parse_time_double_args(PyObject *args, char *format, double *pwhen)
289{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000290 PyObject *ot = NULL;
Fred Drakef901abd2004-08-03 17:58:55 +0000291
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000292 if (!PyArg_ParseTuple(args, format, &ot))
293 return 0;
294 if (ot == NULL || ot == Py_None)
295 *pwhen = floattime();
296 else {
297 double when = PyFloat_AsDouble(ot);
298 if (PyErr_Occurred())
299 return 0;
300 *pwhen = when;
301 }
302 return 1;
Fred Drakef901abd2004-08-03 17:58:55 +0000303}
304
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000305static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000306time_gmtime(PyObject *self, PyObject *args)
Guido van Rossum234f9421993-06-17 12:35:49 +0000307{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000308 double when;
309 if (!parse_time_double_args(args, "|O:gmtime", &when))
310 return NULL;
311 return time_convert(when, gmtime);
Guido van Rossum234f9421993-06-17 12:35:49 +0000312}
313
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000314PyDoc_STRVAR(gmtime_doc,
Christian Heimes9a371592007-12-28 14:08:13 +0000315"gmtime([seconds]) -> (tm_year, tm_mon, tm_mday, tm_hour, tm_min,\n\
Fred Drake193a3f62002-03-12 21:38:49 +0000316 tm_sec, tm_wday, tm_yday, tm_isdst)\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000317\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000318Convert seconds since the Epoch to a time tuple expressing UTC (a.k.a.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000319GMT). When 'seconds' is not passed in, convert the current time instead.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000320
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000321static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000322time_localtime(PyObject *self, PyObject *args)
Guido van Rossum234f9421993-06-17 12:35:49 +0000323{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000324 double when;
325 if (!parse_time_double_args(args, "|O:localtime", &when))
326 return NULL;
327 return time_convert(when, localtime);
Guido van Rossum234f9421993-06-17 12:35:49 +0000328}
329
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000330PyDoc_STRVAR(localtime_doc,
Christian Heimes9a371592007-12-28 14:08:13 +0000331"localtime([seconds]) -> (tm_year,tm_mon,tm_mday,tm_hour,tm_min,\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000332 tm_sec,tm_wday,tm_yday,tm_isdst)\n\
Martin v. Löwisb3cfc1d2001-12-02 12:27:43 +0000333\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000334Convert seconds since the Epoch to a time tuple expressing local time.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000335When 'seconds' is not passed in, convert the current time instead.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000336
Guido van Rossum9e90a671993-06-24 11:10:19 +0000337static int
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000338gettmarg(PyObject *args, struct tm *p)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000339{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000340 int y;
341 PyObject *t = NULL;
Guido van Rossumcfbaecc1998-08-25 14:51:12 +0000342
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000343 memset((void *) p, '\0', sizeof(struct tm));
Guido van Rossumb9081262007-08-25 03:14:09 +0000344
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000345 if (PyTuple_Check(args)) {
346 t = args;
347 Py_INCREF(t);
348 }
349 else if (Py_TYPE(args) == &StructTimeType) {
350 t = structtime_totuple(args);
351 }
352 else {
353 PyErr_SetString(PyExc_TypeError,
354 "Tuple or struct_time argument required");
355 return 0;
356 }
Skip Montanaro41cfce92007-08-24 21:11:00 +0000357
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000358 if (t == NULL || !PyArg_ParseTuple(t, "iiiiiiiii",
359 &y,
360 &p->tm_mon,
361 &p->tm_mday,
362 &p->tm_hour,
363 &p->tm_min,
364 &p->tm_sec,
365 &p->tm_wday,
366 &p->tm_yday,
367 &p->tm_isdst)) {
368 Py_XDECREF(t);
369 return 0;
370 }
371 Py_DECREF(t);
Skip Montanaro41cfce92007-08-24 21:11:00 +0000372
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000373 if (y < 1900) {
374 PyObject *accept = PyDict_GetItemString(moddict,
375 "accept2dyear");
376 if (accept == NULL || !PyLong_CheckExact(accept) ||
377 !PyObject_IsTrue(accept)) {
378 PyErr_SetString(PyExc_ValueError,
379 "year >= 1900 required");
380 return 0;
381 }
382 if (69 <= y && y <= 99)
383 y += 1900;
384 else if (0 <= y && y <= 68)
385 y += 2000;
386 else {
387 PyErr_SetString(PyExc_ValueError,
388 "year out of range");
389 return 0;
390 }
391 }
392 p->tm_year = y - 1900;
393 p->tm_mon--;
394 p->tm_wday = (p->tm_wday + 1) % 7;
395 p->tm_yday--;
396 return 1;
Guido van Rossum9e90a671993-06-24 11:10:19 +0000397}
398
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000399#ifdef HAVE_STRFTIME
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000400#ifdef HAVE_WCSFTIME
401#define time_char wchar_t
402#define format_time wcsftime
403#define time_strlen wcslen
404#else
405#define time_char char
406#define format_time strftime
407#define time_strlen strlen
408#endif
409
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000410static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000411time_strftime(PyObject *self, PyObject *args)
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000412{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000413 PyObject *tup = NULL;
414 struct tm buf;
415 const time_char *fmt;
416 PyObject *format, *tmpfmt;
417 size_t fmtlen, buflen;
418 time_char *outbuf = 0;
419 size_t i;
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000420
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000421 memset((void *) &buf, '\0', sizeof(buf));
Guido van Rossum1f41f841998-04-27 19:04:26 +0000422
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000423 /* Will always expect a unicode string to be passed as format.
424 Given that there's no str type anymore in py3k this seems safe.
425 */
426 if (!PyArg_ParseTuple(args, "U|O:strftime", &format, &tup))
427 return NULL;
Thomas Woutersfe385252001-01-19 23:16:56 +0000428
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000429 if (tup == NULL) {
430 time_t tt = time(NULL);
431 buf = *localtime(&tt);
432 } else if (!gettmarg(tup, &buf))
433 return NULL;
Guido van Rossum10b164a2001-09-25 13:59:01 +0000434
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000435 /* Checks added to make sure strftime() does not crash Python by
436 indexing blindly into some array for a textual representation
437 by some bad index (fixes bug #897625).
Tim Peters1b6f7a92004-06-20 02:50:16 +0000438
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000439 Also support values of zero from Python code for arguments in which
440 that is out of range by forcing that value to the lowest value that
441 is valid (fixed bug #1520914).
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000442
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000443 Valid ranges based on what is allowed in struct tm:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000444
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000445 - tm_year: [0, max(int)] (1)
446 - tm_mon: [0, 11] (2)
447 - tm_mday: [1, 31]
448 - tm_hour: [0, 23]
449 - tm_min: [0, 59]
450 - tm_sec: [0, 60]
451 - tm_wday: [0, 6] (1)
452 - tm_yday: [0, 365] (2)
453 - tm_isdst: [-max(int), max(int)]
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000454
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000455 (1) gettmarg() handles bounds-checking.
456 (2) Python's acceptable range is one greater than the range in C,
457 thus need to check against automatic decrement by gettmarg().
458 */
459 if (buf.tm_mon == -1)
460 buf.tm_mon = 0;
461 else if (buf.tm_mon < 0 || buf.tm_mon > 11) {
462 PyErr_SetString(PyExc_ValueError, "month out of range");
463 return NULL;
464 }
465 if (buf.tm_mday == 0)
466 buf.tm_mday = 1;
467 else if (buf.tm_mday < 0 || buf.tm_mday > 31) {
468 PyErr_SetString(PyExc_ValueError, "day of month out of range");
469 return NULL;
470 }
471 if (buf.tm_hour < 0 || buf.tm_hour > 23) {
472 PyErr_SetString(PyExc_ValueError, "hour out of range");
473 return NULL;
474 }
475 if (buf.tm_min < 0 || buf.tm_min > 59) {
476 PyErr_SetString(PyExc_ValueError, "minute out of range");
477 return NULL;
478 }
479 if (buf.tm_sec < 0 || buf.tm_sec > 61) {
480 PyErr_SetString(PyExc_ValueError, "seconds out of range");
481 return NULL;
482 }
483 /* tm_wday does not need checking of its upper-bound since taking
484 ``% 7`` in gettmarg() automatically restricts the range. */
485 if (buf.tm_wday < 0) {
486 PyErr_SetString(PyExc_ValueError, "day of week out of range");
487 return NULL;
488 }
489 if (buf.tm_yday == -1)
490 buf.tm_yday = 0;
491 else if (buf.tm_yday < 0 || buf.tm_yday > 365) {
492 PyErr_SetString(PyExc_ValueError, "day of year out of range");
493 return NULL;
494 }
495 /* Normalize tm_isdst just in case someone foolishly implements %Z
496 based on the assumption that tm_isdst falls within the range of
497 [-1, 1] */
498 if (buf.tm_isdst < -1)
499 buf.tm_isdst = -1;
500 else if (buf.tm_isdst > 1)
501 buf.tm_isdst = 1;
Brett Cannond1080a32004-03-02 04:38:10 +0000502
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000503#ifdef HAVE_WCSFTIME
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000504 tmpfmt = PyBytes_FromStringAndSize(NULL,
505 sizeof(wchar_t) * (PyUnicode_GetSize(format)+1));
506 if (!tmpfmt)
507 return NULL;
508 /* This assumes that PyUnicode_AsWideChar doesn't do any UTF-16
509 expansion. */
510 if (PyUnicode_AsWideChar((PyUnicodeObject*)format,
511 (wchar_t*)PyBytes_AS_STRING(tmpfmt),
512 PyUnicode_GetSize(format)+1) == (size_t)-1)
513 /* This shouldn't fail. */
514 Py_FatalError("PyUnicode_AsWideChar failed");
515 format = tmpfmt;
516 fmt = (wchar_t*)PyBytes_AS_STRING(format);
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000517#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000518 /* Convert the unicode string to an ascii one */
519 format = PyUnicode_AsEncodedString(format, TZNAME_ENCODING, NULL);
520 if (format == NULL)
521 return NULL;
522 fmt = PyBytes_AS_STRING(format);
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000523#endif
Amaury Forgeot d'Arcb5be6d42009-03-02 23:52:57 +0000524
Hirokazu Yamamoto6b0e51a2009-06-03 05:19:18 +0000525#if defined(MS_WINDOWS) && defined(HAVE_WCSFTIME)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000526 /* check that the format string contains only valid directives */
527 for(outbuf = wcschr(fmt, L'%');
528 outbuf != NULL;
529 outbuf = wcschr(outbuf+2, L'%'))
530 {
531 if (outbuf[1]=='#')
532 ++outbuf; /* not documented by python, */
533 if (outbuf[1]=='\0' ||
534 !wcschr(L"aAbBcdfHIjmMpSUwWxXyYzZ%", outbuf[1]))
535 {
536 PyErr_SetString(PyExc_ValueError, "Invalid format string");
537 return 0;
538 }
539 }
Amaury Forgeot d'Arcb5be6d42009-03-02 23:52:57 +0000540#endif
541
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000542 fmtlen = time_strlen(fmt);
Guido van Rossumc222ec21999-02-23 00:00:10 +0000543
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000544 /* I hate these functions that presume you know how big the output
545 * will be ahead of time...
546 */
547 for (i = 1024; ; i += i) {
548 outbuf = (time_char *)PyMem_Malloc(i*sizeof(time_char));
549 if (outbuf == NULL) {
550 Py_DECREF(format);
551 return PyErr_NoMemory();
552 }
553 buflen = format_time(outbuf, i, fmt, &buf);
554 if (buflen > 0 || i >= 256 * fmtlen) {
555 /* If the buffer is 256 times as long as the format,
556 it's probably not failing for lack of room!
557 More likely, the format yields an empty result,
558 e.g. an empty format, or %Z when the timezone
559 is unknown. */
560 PyObject *ret;
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000561#ifdef HAVE_WCSFTIME
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000562 ret = PyUnicode_FromWideChar(outbuf, buflen);
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000563#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000564 ret = PyUnicode_Decode(outbuf, buflen,
565 TZNAME_ENCODING, NULL);
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000566#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000567 PyMem_Free(outbuf);
568 Py_DECREF(format);
569 return ret;
570 }
571 PyMem_Free(outbuf);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000572#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000573 /* VisualStudio .NET 2005 does this properly */
574 if (buflen == 0 && errno == EINVAL) {
575 PyErr_SetString(PyExc_ValueError, "Invalid format string");
576 Py_DECREF(format);
577 return 0;
578 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000579#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000580 }
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000581}
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000582
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000583#undef time_char
584#undef format_time
585
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000586PyDoc_STRVAR(strftime_doc,
Thomas Woutersfe385252001-01-19 23:16:56 +0000587"strftime(format[, tuple]) -> string\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000588\n\
589Convert a time tuple to a string according to a format specification.\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000590See the library reference manual for formatting codes. When the time tuple\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000591is not present, current time as returned by localtime() is used.");
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000592#endif /* HAVE_STRFTIME */
593
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000594static PyObject *
595time_strptime(PyObject *self, PyObject *args)
596{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000597 PyObject *strptime_module = PyImport_ImportModuleNoBlock("_strptime");
598 PyObject *strptime_result;
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000599
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000600 if (!strptime_module)
601 return NULL;
602 strptime_result = PyObject_CallMethod(strptime_module,
603 "_strptime_time", "O", args);
604 Py_DECREF(strptime_module);
605 return strptime_result;
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000606}
607
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000608PyDoc_STRVAR(strptime_doc,
Brett Cannon20def8b2003-07-01 05:16:08 +0000609"strptime(string, format) -> struct_time\n\
Martin v. Löwisb3cfc1d2001-12-02 12:27:43 +0000610\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000611Parse a string to a time tuple according to a format specification.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000612See the library reference manual for formatting codes (same as strftime()).");
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000613
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000614
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000615static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000616time_asctime(PyObject *self, PyObject *args)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000617{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000618 PyObject *tup = NULL;
619 struct tm buf;
620 char *p;
621 if (!PyArg_UnpackTuple(args, "asctime", 0, 1, &tup))
622 return NULL;
623 if (tup == NULL) {
624 time_t tt = time(NULL);
625 buf = *localtime(&tt);
626 } else if (!gettmarg(tup, &buf))
627 return NULL;
628 p = asctime(&buf);
629 if (p[24] == '\n')
630 p[24] = '\0';
631 return PyUnicode_FromString(p);
Guido van Rossum9e90a671993-06-24 11:10:19 +0000632}
633
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000634PyDoc_STRVAR(asctime_doc,
Thomas Woutersfe385252001-01-19 23:16:56 +0000635"asctime([tuple]) -> string\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000636\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000637Convert a time tuple to a string, e.g. 'Sat Jun 06 16:26:11 1998'.\n\
638When the time tuple is not present, current time as returned by localtime()\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000639is used.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000640
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000641static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000642time_ctime(PyObject *self, PyObject *args)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000643{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000644 PyObject *ot = NULL;
645 time_t tt;
646 char *p;
Guido van Rossum10b164a2001-09-25 13:59:01 +0000647
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000648 if (!PyArg_UnpackTuple(args, "ctime", 0, 1, &ot))
649 return NULL;
650 if (ot == NULL || ot == Py_None)
651 tt = time(NULL);
652 else {
653 double dt = PyFloat_AsDouble(ot);
654 if (PyErr_Occurred())
655 return NULL;
656 tt = _PyTime_DoubleToTimet(dt);
657 if (tt == (time_t)-1 && PyErr_Occurred())
658 return NULL;
659 }
660 p = ctime(&tt);
661 if (p == NULL) {
662 PyErr_SetString(PyExc_ValueError, "unconvertible time");
663 return NULL;
664 }
665 if (p[24] == '\n')
666 p[24] = '\0';
667 return PyUnicode_FromString(p);
Guido van Rossum9e90a671993-06-24 11:10:19 +0000668}
669
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000670PyDoc_STRVAR(ctime_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000671"ctime(seconds) -> string\n\
672\n\
673Convert a time in seconds since the Epoch to a string in local time.\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000674This is equivalent to asctime(localtime(seconds)). When the time tuple is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000675not present, current time as returned by localtime() is used.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000676
Guido van Rossum60cd8131998-03-06 17:16:21 +0000677#ifdef HAVE_MKTIME
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000678static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000679time_mktime(PyObject *self, PyObject *tup)
Guido van Rossum234f9421993-06-17 12:35:49 +0000680{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000681 struct tm buf;
682 time_t tt;
683 if (!gettmarg(tup, &buf))
684 return NULL;
685 tt = mktime(&buf);
686 if (tt == (time_t)(-1)) {
687 PyErr_SetString(PyExc_OverflowError,
688 "mktime argument out of range");
689 return NULL;
690 }
691 return PyFloat_FromDouble((double)tt);
Guido van Rossum234f9421993-06-17 12:35:49 +0000692}
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000693
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000694PyDoc_STRVAR(mktime_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000695"mktime(tuple) -> floating point number\n\
696\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000697Convert a time tuple in local time to seconds since the Epoch.");
Guido van Rossum60cd8131998-03-06 17:16:21 +0000698#endif /* HAVE_MKTIME */
Guido van Rossum234f9421993-06-17 12:35:49 +0000699
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000700#ifdef HAVE_WORKING_TZSET
Martin v. Löwis1a214512008-06-11 05:26:20 +0000701static void PyInit_timezone(PyObject *module);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000702
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000703static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000704time_tzset(PyObject *self, PyObject *unused)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000705{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000706 PyObject* m;
Fred Drake9bb74322002-04-01 14:49:59 +0000707
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000708 m = PyImport_ImportModuleNoBlock("time");
709 if (m == NULL) {
710 return NULL;
711 }
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000712
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000713 tzset();
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000714
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000715 /* Reset timezone, altzone, daylight and tzname */
716 PyInit_timezone(m);
717 Py_DECREF(m);
Tim Peters1b6f7a92004-06-20 02:50:16 +0000718
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000719 Py_INCREF(Py_None);
720 return Py_None;
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000721}
722
723PyDoc_STRVAR(tzset_doc,
724"tzset(zone)\n\
725\n\
726Initialize, or reinitialize, the local timezone to the value stored in\n\
727os.environ['TZ']. The TZ environment variable should be specified in\n\
Neal Norwitzdc8e1942004-07-20 22:34:37 +0000728standard Unix timezone format as documented in the tzset man page\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000729(eg. 'US/Eastern', 'Europe/Amsterdam'). Unknown timezones will silently\n\
730fall back to UTC. If the TZ environment variable is not set, the local\n\
731timezone is set to the systems best guess of wallclock time.\n\
732Changing the TZ environment variable without calling tzset *may* change\n\
733the local timezone used by methods such as localtime, but this behaviour\n\
734should not be relied on.");
735#endif /* HAVE_WORKING_TZSET */
736
Martin v. Löwisd218dc12008-04-07 03:17:54 +0000737static void
Martin v. Löwis1a214512008-06-11 05:26:20 +0000738PyInit_timezone(PyObject *m) {
739 /* This code moved from PyInit_time wholesale to allow calling it from
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000740 time_tzset. In the future, some parts of it can be moved back
741 (for platforms that don't HAVE_WORKING_TZSET, when we know what they
742 are), and the extraneous calls to tzset(3) should be removed.
743 I haven't done this yet, as I don't want to change this code as
744 little as possible when introducing the time.tzset and time.tzsetwall
745 methods. This should simply be a method of doing the following once,
746 at the top of this function and removing the call to tzset() from
747 time_tzset():
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000748
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000749 #ifdef HAVE_TZSET
750 tzset()
751 #endif
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000752
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000753 And I'm lazy and hate C so nyer.
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000754 */
Guido van Rossum10b164a2001-09-25 13:59:01 +0000755#if defined(HAVE_TZNAME) && !defined(__GLIBC__) && !defined(__CYGWIN__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000756 PyObject *otz0, *otz1;
757 tzset();
Guido van Rossum26452411998-09-28 22:07:11 +0000758#ifdef PYOS_OS2
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000759 PyModule_AddIntConstant(m, "timezone", _timezone);
Guido van Rossum26452411998-09-28 22:07:11 +0000760#else /* !PYOS_OS2 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000761 PyModule_AddIntConstant(m, "timezone", timezone);
Guido van Rossum26452411998-09-28 22:07:11 +0000762#endif /* PYOS_OS2 */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000763#ifdef HAVE_ALTZONE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000764 PyModule_AddIntConstant(m, "altzone", altzone);
Guido van Rossumb6775db1994-08-01 11:34:53 +0000765#else
Guido van Rossum26452411998-09-28 22:07:11 +0000766#ifdef PYOS_OS2
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000767 PyModule_AddIntConstant(m, "altzone", _timezone-3600);
Guido van Rossum26452411998-09-28 22:07:11 +0000768#else /* !PYOS_OS2 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000769 PyModule_AddIntConstant(m, "altzone", timezone-3600);
Guido van Rossum26452411998-09-28 22:07:11 +0000770#endif /* PYOS_OS2 */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000771#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000772 PyModule_AddIntConstant(m, "daylight", daylight);
773 otz0 = PyUnicode_Decode(tzname[0], strlen(tzname[0]), TZNAME_ENCODING, NULL);
774 otz1 = PyUnicode_Decode(tzname[1], strlen(tzname[1]), TZNAME_ENCODING, NULL);
775 PyModule_AddObject(m, "tzname", Py_BuildValue("(NN)", otz0, otz1));
Guido van Rossum10b164a2001-09-25 13:59:01 +0000776#else /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/
Martin v. Löwis60a5d722002-10-16 20:28:25 +0000777#ifdef HAVE_STRUCT_TM_TM_ZONE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000778 {
Guido van Rossum234f9421993-06-17 12:35:49 +0000779#define YEAR ((time_t)((365 * 24 + 6) * 3600))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000780 time_t t;
781 struct tm *p;
782 long janzone, julyzone;
783 char janname[10], julyname[10];
784 t = (time((time_t *)0) / YEAR) * YEAR;
785 p = localtime(&t);
786 janzone = -p->tm_gmtoff;
787 strncpy(janname, p->tm_zone ? p->tm_zone : " ", 9);
788 janname[9] = '\0';
789 t += YEAR/2;
790 p = localtime(&t);
791 julyzone = -p->tm_gmtoff;
792 strncpy(julyname, p->tm_zone ? p->tm_zone : " ", 9);
793 julyname[9] = '\0';
Guido van Rossum10b164a2001-09-25 13:59:01 +0000794
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000795 if( janzone < julyzone ) {
796 /* DST is reversed in the southern hemisphere */
797 PyModule_AddIntConstant(m, "timezone", julyzone);
798 PyModule_AddIntConstant(m, "altzone", janzone);
799 PyModule_AddIntConstant(m, "daylight",
800 janzone != julyzone);
801 PyModule_AddObject(m, "tzname",
802 Py_BuildValue("(zz)",
803 julyname, janname));
804 } else {
805 PyModule_AddIntConstant(m, "timezone", janzone);
806 PyModule_AddIntConstant(m, "altzone", julyzone);
807 PyModule_AddIntConstant(m, "daylight",
808 janzone != julyzone);
809 PyModule_AddObject(m, "tzname",
810 Py_BuildValue("(zz)",
811 janname, julyname));
812 }
813 }
Guido van Rossume6a4b7b1997-10-08 15:27:56 +0000814#else
Martin v. Löwis60a5d722002-10-16 20:28:25 +0000815#endif /* HAVE_STRUCT_TM_TM_ZONE */
Tim Peters26ae7cd2001-03-20 03:26:49 +0000816#ifdef __CYGWIN__
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000817 tzset();
818 PyModule_AddIntConstant(m, "timezone", _timezone);
819 PyModule_AddIntConstant(m, "altzone", _timezone-3600);
820 PyModule_AddIntConstant(m, "daylight", _daylight);
821 PyModule_AddObject(m, "tzname",
822 Py_BuildValue("(zz)", _tzname[0], _tzname[1]));
Tim Peters26ae7cd2001-03-20 03:26:49 +0000823#endif /* __CYGWIN__ */
Guido van Rossum10b164a2001-09-25 13:59:01 +0000824#endif /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000825}
826
827
828static PyMethodDef time_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000829 {"time", time_time, METH_NOARGS, time_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000830#ifdef HAVE_CLOCK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000831 {"clock", time_clock, METH_NOARGS, clock_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000832#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000833 {"sleep", time_sleep, METH_VARARGS, sleep_doc},
834 {"gmtime", time_gmtime, METH_VARARGS, gmtime_doc},
835 {"localtime", time_localtime, METH_VARARGS, localtime_doc},
836 {"asctime", time_asctime, METH_VARARGS, asctime_doc},
837 {"ctime", time_ctime, METH_VARARGS, ctime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000838#ifdef HAVE_MKTIME
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000839 {"mktime", time_mktime, METH_O, mktime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000840#endif
841#ifdef HAVE_STRFTIME
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000842 {"strftime", time_strftime, METH_VARARGS, strftime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000843#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000844 {"strptime", time_strptime, METH_VARARGS, strptime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000845#ifdef HAVE_WORKING_TZSET
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000846 {"tzset", time_tzset, METH_NOARGS, tzset_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000847#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000848 {NULL, NULL} /* sentinel */
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000849};
850
851
852PyDoc_STRVAR(module_doc,
853"This module provides various functions to manipulate time values.\n\
854\n\
855There are two standard representations of time. One is the number\n\
856of seconds since the Epoch, in UTC (a.k.a. GMT). It may be an integer\n\
857or a floating point number (to represent fractions of seconds).\n\
858The Epoch is system-defined; on Unix, it is generally January 1st, 1970.\n\
859The actual value can be retrieved by calling gmtime(0).\n\
860\n\
861The other representation is a tuple of 9 integers giving local time.\n\
862The tuple items are:\n\
863 year (four digits, e.g. 1998)\n\
864 month (1-12)\n\
865 day (1-31)\n\
866 hours (0-23)\n\
867 minutes (0-59)\n\
868 seconds (0-59)\n\
869 weekday (0-6, Monday is 0)\n\
870 Julian day (day in the year, 1-366)\n\
871 DST (Daylight Savings Time) flag (-1, 0 or 1)\n\
872If the DST flag is 0, the time is given in the regular time zone;\n\
873if it is 1, the time is given in the DST time zone;\n\
874if it is -1, mktime() should guess based on the date and time.\n\
875\n\
876Variables:\n\
877\n\
878timezone -- difference in seconds between UTC and local standard time\n\
879altzone -- difference in seconds between UTC and local DST time\n\
880daylight -- whether local time should reflect DST\n\
881tzname -- tuple of (standard time zone name, DST time zone name)\n\
882\n\
883Functions:\n\
884\n\
885time() -- return current time in seconds since the Epoch as a float\n\
886clock() -- return CPU time since process start as a float\n\
887sleep() -- delay for a number of seconds given as a float\n\
888gmtime() -- convert seconds since Epoch to UTC tuple\n\
889localtime() -- convert seconds since Epoch to local time tuple\n\
890asctime() -- convert time tuple to string\n\
891ctime() -- convert time in seconds to string\n\
892mktime() -- convert local time tuple to seconds since Epoch\n\
893strftime() -- convert time tuple to string according to format specification\n\
894strptime() -- parse string to time tuple according to format specification\n\
895tzset() -- change the local timezone");
896
897
Martin v. Löwis1a214512008-06-11 05:26:20 +0000898
899static struct PyModuleDef timemodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000900 PyModuleDef_HEAD_INIT,
901 "time",
902 module_doc,
903 -1,
904 time_methods,
905 NULL,
906 NULL,
907 NULL,
908 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +0000909};
910
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000911PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +0000912PyInit_time(void)
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000913{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000914 PyObject *m;
915 char *p;
916 m = PyModule_Create(&timemodule);
917 if (m == NULL)
918 return NULL;
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000919
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000920 /* Accept 2-digit dates unless PYTHONY2K is set and non-empty */
921 p = Py_GETENV("PYTHONY2K");
922 PyModule_AddIntConstant(m, "accept2dyear", (long) (!p || !*p));
923 /* Squirrel away the module's dictionary for the y2k check */
924 moddict = PyModule_GetDict(m);
925 Py_INCREF(moddict);
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000926
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000927 /* Set, or reset, module variables like time.timezone */
928 PyInit_timezone(m);
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000929
Mark Hammond975e3922002-07-16 01:29:19 +0000930#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000931 /* Helper to allow interrupts for Windows.
932 If Ctrl+C event delivered while not sleeping
933 it will be ignored.
934 */
935 main_thread = PyThread_get_thread_ident();
936 hInterruptEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
937 SetConsoleCtrlHandler( PyCtrlHandler, TRUE);
Mark Hammond975e3922002-07-16 01:29:19 +0000938#endif /* MS_WINDOWS */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000939 if (!initialized) {
940 PyStructSequence_InitType(&StructTimeType,
941 &struct_time_type_desc);
942 }
943 Py_INCREF(&StructTimeType);
944 PyModule_AddObject(m, "struct_time", (PyObject*) &StructTimeType);
945 initialized = 1;
946 return m;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000947}
948
949
Guido van Rossumb6775db1994-08-01 11:34:53 +0000950/* Implement floattime() for various platforms */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000951
Guido van Rossumb6775db1994-08-01 11:34:53 +0000952static double
Thomas Woutersf3f33dc2000-07-21 06:00:07 +0000953floattime(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000954{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000955 /* There are three ways to get the time:
956 (1) gettimeofday() -- resolution in microseconds
957 (2) ftime() -- resolution in milliseconds
958 (3) time() -- resolution in seconds
959 In all cases the return value is a float in seconds.
960 Since on some systems (e.g. SCO ODT 3.0) gettimeofday() may
961 fail, so we fall back on ftime() or time().
962 Note: clock resolution does not imply clock accuracy! */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000963#ifdef HAVE_GETTIMEOFDAY
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000964 {
965 struct timeval t;
Guido van Rossum3bbc62e1995-01-02 19:30:30 +0000966#ifdef GETTIMEOFDAY_NO_TZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000967 if (gettimeofday(&t) == 0)
968 return (double)t.tv_sec + t.tv_usec*0.000001;
Guido van Rossum3bbc62e1995-01-02 19:30:30 +0000969#else /* !GETTIMEOFDAY_NO_TZ */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000970 if (gettimeofday(&t, (struct timezone *)NULL) == 0)
971 return (double)t.tv_sec + t.tv_usec*0.000001;
Guido van Rossum3bbc62e1995-01-02 19:30:30 +0000972#endif /* !GETTIMEOFDAY_NO_TZ */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000973 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000974
Guido van Rossumb6775db1994-08-01 11:34:53 +0000975#endif /* !HAVE_GETTIMEOFDAY */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000976 {
Guido van Rossumd3eb5771999-03-09 16:07:23 +0000977#if defined(HAVE_FTIME)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000978 struct timeb t;
979 ftime(&t);
980 return (double)t.time + (double)t.millitm * (double)0.001;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000981#else /* !HAVE_FTIME */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000982 time_t secs;
983 time(&secs);
984 return (double)secs;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000985#endif /* !HAVE_FTIME */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000986 }
Guido van Rossum426035c1991-02-19 12:27:35 +0000987}
988
Guido van Rossumb6775db1994-08-01 11:34:53 +0000989
990/* Implement floatsleep() for various platforms.
991 When interrupted (or when another error occurs), return -1 and
992 set an exception; else return 0. */
993
994static int
Guido van Rossuma320fd31995-03-09 12:14:15 +0000995floatsleep(double secs)
Guido van Rossum426035c1991-02-19 12:27:35 +0000996{
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000997/* XXX Should test for MS_WINDOWS first! */
Skip Montanaroeb33e5a2007-08-17 12:57:41 +0000998#if defined(HAVE_SELECT) && !defined(__EMX__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000999 struct timeval t;
1000 double frac;
1001 frac = fmod(secs, 1.0);
1002 secs = floor(secs);
1003 t.tv_sec = (long)secs;
1004 t.tv_usec = (long)(frac*1000000.0);
1005 Py_BEGIN_ALLOW_THREADS
1006 if (select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &t) != 0) {
Guido van Rossum09cbb011999-11-08 15:32:27 +00001007#ifdef EINTR
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001008 if (errno != EINTR) {
Guido van Rossum09cbb011999-11-08 15:32:27 +00001009#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001010 if (1) {
Guido van Rossum09cbb011999-11-08 15:32:27 +00001011#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001012 Py_BLOCK_THREADS
1013 PyErr_SetFromErrno(PyExc_IOError);
1014 return -1;
1015 }
1016 }
1017 Py_END_ALLOW_THREADS
Martin v. Löwis02af9642002-01-16 11:04:06 +00001018#elif defined(__WATCOMC__) && !defined(__QNX__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001019 /* XXX Can't interrupt this sleep */
1020 Py_BEGIN_ALLOW_THREADS
1021 delay((int)(secs * 1000 + 0.5)); /* delay() uses milliseconds */
1022 Py_END_ALLOW_THREADS
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001023#elif defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001024 {
1025 double millisecs = secs * 1000.0;
1026 unsigned long ul_millis;
Tim Peters513a1cd2003-01-19 04:54:58 +00001027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 if (millisecs > (double)ULONG_MAX) {
1029 PyErr_SetString(PyExc_OverflowError,
1030 "sleep length is too large");
1031 return -1;
1032 }
1033 Py_BEGIN_ALLOW_THREADS
1034 /* Allow sleep(0) to maintain win32 semantics, and as decreed
1035 * by Guido, only the main thread can be interrupted.
1036 */
1037 ul_millis = (unsigned long)millisecs;
1038 if (ul_millis == 0 ||
1039 main_thread != PyThread_get_thread_ident())
1040 Sleep(ul_millis);
1041 else {
1042 DWORD rc;
1043 ResetEvent(hInterruptEvent);
1044 rc = WaitForSingleObject(hInterruptEvent, ul_millis);
1045 if (rc == WAIT_OBJECT_0) {
1046 /* Yield to make sure real Python signal
1047 * handler called.
1048 */
1049 Sleep(1);
1050 Py_BLOCK_THREADS
1051 errno = EINTR;
1052 PyErr_SetFromErrno(PyExc_IOError);
1053 return -1;
1054 }
1055 }
1056 Py_END_ALLOW_THREADS
1057 }
Martin v. Löwis02af9642002-01-16 11:04:06 +00001058#elif defined(PYOS_OS2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001059 /* This Sleep *IS* Interruptable by Exceptions */
1060 Py_BEGIN_ALLOW_THREADS
1061 if (DosSleep(secs * 1000) != NO_ERROR) {
1062 Py_BLOCK_THREADS
1063 PyErr_SetFromErrno(PyExc_IOError);
1064 return -1;
1065 }
1066 Py_END_ALLOW_THREADS
Martin v. Löwis02af9642002-01-16 11:04:06 +00001067#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001068 /* XXX Can't interrupt this sleep */
1069 Py_BEGIN_ALLOW_THREADS
1070 sleep((int)secs);
1071 Py_END_ALLOW_THREADS
Martin v. Löwis02af9642002-01-16 11:04:06 +00001072#endif
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001073
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001074 return 0;
Guido van Rossum80c9d881991-04-16 08:47:51 +00001075}