blob: 12c43b08fe4a814dfb3388cc8d950afed310da9a [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
Ronald Oussorend06b6f22006-04-23 11:59:25 +00008#ifdef __APPLE__
9#if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_FTIME)
10 /*
11 * floattime falls back to ftime when getttimeofday fails because the latter
12 * might fail on some platforms. This fallback is unwanted on MacOSX because
13 * that makes it impossible to use a binary build on OSX 10.4 on earlier
14 * releases of the OS. Therefore claim we don't support ftime.
15 */
16# undef HAVE_FTIME
17#endif
18#endif
19
Guido van Rossum87ce7bb1998-06-09 16:30:31 +000020#include <ctype.h>
21
Martin v. Löwis0e8bd7e2006-06-10 12:23:46 +000022#ifdef HAVE_SYS_TYPES_H
Guido van Rossumb6775db1994-08-01 11:34:53 +000023#include <sys/types.h>
Martin v. Löwis0e8bd7e2006-06-10 12:23:46 +000024#endif /* HAVE_SYS_TYPES_H */
Guido van Rossum6d946f91992-08-14 13:49:30 +000025
Guido van Rossumb6775db1994-08-01 11:34:53 +000026#ifdef QUICKWIN
27#include <io.h>
28#endif
29
Guido van Rossumb6775db1994-08-01 11:34:53 +000030#ifdef HAVE_FTIME
31#include <sys/timeb.h>
Guido van Rossum8e9ebfd1997-11-22 21:53:48 +000032#if !defined(MS_WINDOWS) && !defined(PYOS_OS2)
Thomas Woutersbd4bc4e2000-07-22 23:57:55 +000033extern int ftime(struct timeb *);
Guido van Rossum52174571996-12-09 18:38:52 +000034#endif /* MS_WINDOWS */
35#endif /* HAVE_FTIME */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000036
Guido van Rossum7bf22de1997-12-02 20:34:19 +000037#if defined(__WATCOMC__) && !defined(__QNX__)
Guido van Rossumbceeac81996-05-23 22:53:47 +000038#include <i86.h>
39#else
Guido van Rossumcac6c721996-09-06 13:34:02 +000040#ifdef MS_WINDOWS
Mark Hammond975e3922002-07-16 01:29:19 +000041#define WIN32_LEAN_AND_MEAN
Guido van Rossum258ccd42001-03-02 06:53:29 +000042#include <windows.h>
Mark Hammond975e3922002-07-16 01:29:19 +000043#include "pythread.h"
44
45/* helper to allow us to interrupt sleep() on Windows*/
46static HANDLE hInterruptEvent = NULL;
47static BOOL WINAPI PyCtrlHandler(DWORD dwCtrlType)
48{
Antoine Pitrouc83ea132010-05-09 14:46:46 +000049 SetEvent(hInterruptEvent);
50 /* allow other default handlers to be called.
51 Default Python handler will setup the
52 KeyboardInterrupt exception.
53 */
54 return FALSE;
Mark Hammond975e3922002-07-16 01:29:19 +000055}
56static long main_thread;
57
58
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000059#if defined(__BORLANDC__)
Guido van Rossumb2fb3641996-09-07 00:47:35 +000060/* These overrides not needed for Win32 */
Guido van Rossumb6775db1994-08-01 11:34:53 +000061#define timezone _timezone
Guido van Rossumcc081121995-03-14 15:05:41 +000062#define tzname _tzname
63#define daylight _daylight
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000064#endif /* __BORLANDC__ */
Guido van Rossumcac6c721996-09-06 13:34:02 +000065#endif /* MS_WINDOWS */
Guido van Rossum7bf22de1997-12-02 20:34:19 +000066#endif /* !__WATCOMC__ || __QNX__ */
Guido van Rossum234f9421993-06-17 12:35:49 +000067
Tim Peters7a822da2006-05-25 21:50:17 +000068#if defined(MS_WINDOWS) && !defined(__BORLANDC__)
Tim Petersc285e622006-05-25 22:25:25 +000069/* Win32 has better clock replacement; we have our own version below. */
70#undef HAVE_CLOCK
Tim Peters7a822da2006-05-25 21:50:17 +000071#endif /* MS_WINDOWS && !defined(__BORLANDC__) */
Guido van Rossum3917c221997-04-02 05:35:28 +000072
Andrew MacIntyre7bf68332002-03-03 02:59:16 +000073#if defined(PYOS_OS2)
74#define INCL_DOS
75#define INCL_ERRORS
76#include <os2.h>
77#endif
78
Guido van Rossum8e9ebfd1997-11-22 21:53:48 +000079#if defined(PYCC_VACPP)
Guido van Rossum26452411998-09-28 22:07:11 +000080#include <sys/time.h>
Guido van Rossum8e9ebfd1997-11-22 21:53:48 +000081#endif
82
Guido van Rossumbcc20741998-08-04 22:53:56 +000083#ifdef __BEOS__
Fred Drake56221a72000-08-15 18:52:33 +000084#include <time.h>
Guido van Rossumbcc20741998-08-04 22:53:56 +000085/* For bigtime_t, snooze(). - [cjh] */
86#include <support/SupportDefs.h>
87#include <kernel/OS.h>
88#endif
89
Martin v. Löwisa94568a2003-05-10 07:36:56 +000090#ifdef RISCOS
91extern int riscos_sleep(double);
92#endif
93
Guido van Rossum234f9421993-06-17 12:35:49 +000094/* Forward declarations */
Tim Petersdbd9ba62000-07-09 03:09:57 +000095static int floatsleep(double);
Thomas Woutersed77bac2000-07-24 15:26:39 +000096static double floattime(void);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000097
Guido van Rossumcfbaecc1998-08-25 14:51:12 +000098/* For Y2K check */
Gregory P. Smith0d68ab32012-11-27 10:19:29 -080099static PyObject *moddict = NULL;
Guido van Rossumcfbaecc1998-08-25 14:51:12 +0000100
Tim Peters1b6f7a92004-06-20 02:50:16 +0000101/* Exposed in timefuncs.h. */
102time_t
Brett Cannon298c3802004-06-19 20:48:43 +0000103_PyTime_DoubleToTimet(double x)
104{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000105 time_t result;
106 double diff;
Brett Cannon298c3802004-06-19 20:48:43 +0000107
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000108 result = (time_t)x;
109 /* How much info did we lose? time_t may be an integral or
110 * floating type, and we don't know which. If it's integral,
111 * we don't know whether C truncates, rounds, returns the floor,
112 * etc. If we lost a second or more, the C rounding is
113 * unreasonable, or the input just doesn't fit in a time_t;
114 * call it an error regardless. Note that the original cast to
115 * time_t can cause a C error too, but nothing we can do to
116 * worm around that.
117 */
118 diff = x - (double)result;
119 if (diff <= -1.0 || diff >= 1.0) {
120 PyErr_SetString(PyExc_ValueError,
121 "timestamp out of range for platform time_t");
122 result = (time_t)-1;
123 }
124 return result;
Brett Cannon298c3802004-06-19 20:48:43 +0000125}
126
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000127static PyObject *
Georg Brandl96a8c392006-05-29 21:04:52 +0000128time_time(PyObject *self, PyObject *unused)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000129{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000130 double secs;
131 secs = floattime();
132 if (secs == 0.0) {
133 PyErr_SetFromErrno(PyExc_IOError);
134 return NULL;
135 }
136 return PyFloat_FromDouble(secs);
Guido van Rossumb6775db1994-08-01 11:34:53 +0000137}
138
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000139PyDoc_STRVAR(time_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000140"time() -> floating point number\n\
141\n\
142Return the current time in seconds since the Epoch.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000143Fractions of a second may be present if the system clock provides them.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000144
Guido van Rossumb6775db1994-08-01 11:34:53 +0000145#ifdef HAVE_CLOCK
146
147#ifndef CLOCKS_PER_SEC
Guido van Rossum1b66a4f1996-02-25 04:50:33 +0000148#ifdef CLK_TCK
149#define CLOCKS_PER_SEC CLK_TCK
150#else
Guido van Rossumb6775db1994-08-01 11:34:53 +0000151#define CLOCKS_PER_SEC 1000000
152#endif
Guido van Rossum1b66a4f1996-02-25 04:50:33 +0000153#endif
Guido van Rossumb6775db1994-08-01 11:34:53 +0000154
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000155static PyObject *
Georg Brandl96a8c392006-05-29 21:04:52 +0000156time_clock(PyObject *self, PyObject *unused)
Guido van Rossumb6775db1994-08-01 11:34:53 +0000157{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000158 return PyFloat_FromDouble(((double)clock()) / CLOCKS_PER_SEC);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000159}
Guido van Rossumb6775db1994-08-01 11:34:53 +0000160#endif /* HAVE_CLOCK */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000161
Tim Petersc285e622006-05-25 22:25:25 +0000162#if defined(MS_WINDOWS) && !defined(__BORLANDC__)
Mark Hammond7ba5e812002-02-12 04:02:33 +0000163/* Due to Mark Hammond and Tim Peters */
Guido van Rossum3917c221997-04-02 05:35:28 +0000164static PyObject *
Georg Brandl96a8c392006-05-29 21:04:52 +0000165time_clock(PyObject *self, PyObject *unused)
Guido van Rossum3917c221997-04-02 05:35:28 +0000166{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000167 static LARGE_INTEGER ctrStart;
168 static double divisor = 0.0;
169 LARGE_INTEGER now;
170 double diff;
Guido van Rossum3917c221997-04-02 05:35:28 +0000171
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000172 if (divisor == 0.0) {
173 LARGE_INTEGER freq;
174 QueryPerformanceCounter(&ctrStart);
175 if (!QueryPerformanceFrequency(&freq) || freq.QuadPart == 0) {
176 /* Unlikely to happen - this works on all intel
177 machines at least! Revert to clock() */
178 return PyFloat_FromDouble(((double)clock()) /
179 CLOCKS_PER_SEC);
180 }
181 divisor = (double)freq.QuadPart;
182 }
183 QueryPerformanceCounter(&now);
184 diff = (double)(now.QuadPart - ctrStart.QuadPart);
185 return PyFloat_FromDouble(diff / divisor);
Guido van Rossum3917c221997-04-02 05:35:28 +0000186}
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000187
Guido van Rossum3917c221997-04-02 05:35:28 +0000188#define HAVE_CLOCK /* So it gets included in the methods */
Tim Petersc285e622006-05-25 22:25:25 +0000189#endif /* MS_WINDOWS && !defined(__BORLANDC__) */
Guido van Rossum3917c221997-04-02 05:35:28 +0000190
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000191#ifdef HAVE_CLOCK
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000192PyDoc_STRVAR(clock_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000193"clock() -> floating point number\n\
194\n\
195Return the CPU time or real time since the start of the process or since\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000196the first call to clock(). This has as much precision as the system\n\
197records.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000198#endif
199
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000200static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000201time_sleep(PyObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000202{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000203 double secs;
204 if (!PyArg_ParseTuple(args, "d:sleep", &secs))
205 return NULL;
206 if (floatsleep(secs) != 0)
207 return NULL;
208 Py_INCREF(Py_None);
209 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000210}
211
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000212PyDoc_STRVAR(sleep_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000213"sleep(seconds)\n\
214\n\
215Delay execution for a given number of seconds. The argument may be\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000216a floating point number for subsecond precision.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000217
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000218static PyStructSequence_Field struct_time_type_fields[] = {
Alexander Belopolsky3b818bf2010-06-05 14:54:26 +0000219 {"tm_year", "year, for example, 1993"},
220 {"tm_mon", "month of year, range [1, 12]"},
221 {"tm_mday", "day of month, range [1, 31]"},
222 {"tm_hour", "hours, range [0, 23]"},
223 {"tm_min", "minutes, range [0, 59]"},
224 {"tm_sec", "seconds, range [0, 61])"},
225 {"tm_wday", "day of week, range [0, 6], Monday is 0"},
226 {"tm_yday", "day of year, range [1, 366]"},
227 {"tm_isdst", "1 if summer time is in effect, 0 if not, and -1 if unknown"},
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000228 {0}
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000229};
230
231static PyStructSequence_Desc struct_time_type_desc = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000232 "time.struct_time",
Alexander Belopolsky3b818bf2010-06-05 14:54:26 +0000233 "The time value as returned by gmtime(), localtime(), and strptime(), and\n"
234 " accepted by asctime(), mktime() and strftime(). May be considered as a\n"
235 " sequence of 9 integers.\n\n"
236 " Note that several fields' values are not the same as those defined by\n"
237 " the C language standard for struct tm. For example, the value of the\n"
238 " field tm_year is the actual year, not year - 1900. See individual\n"
239 " fields' descriptions for details.",
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000240 struct_time_type_fields,
241 9,
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000242};
Tim Peters9ad4b682002-02-13 05:14:18 +0000243
Martin v. Löwis19ab6c92006-04-16 18:55:50 +0000244static int initialized;
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000245static PyTypeObject StructTimeType;
246
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000247static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000248tmtotuple(struct tm *p)
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000249{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000250 PyObject *v = PyStructSequence_New(&StructTimeType);
251 if (v == NULL)
252 return NULL;
Tim Peters9ad4b682002-02-13 05:14:18 +0000253
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000254#define SET(i,val) PyStructSequence_SET_ITEM(v, i, PyInt_FromLong((long) val))
255
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000256 SET(0, p->tm_year + 1900);
257 SET(1, p->tm_mon + 1); /* Want January == 1 */
258 SET(2, p->tm_mday);
259 SET(3, p->tm_hour);
260 SET(4, p->tm_min);
261 SET(5, p->tm_sec);
262 SET(6, (p->tm_wday + 6) % 7); /* Want Monday == 0 */
263 SET(7, p->tm_yday + 1); /* Want January, 1 == 1 */
264 SET(8, p->tm_isdst);
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000265#undef SET
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000266 if (PyErr_Occurred()) {
267 Py_XDECREF(v);
268 return NULL;
269 }
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000270
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000271 return v;
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000272}
273
274static PyObject *
Brett Cannon298c3802004-06-19 20:48:43 +0000275time_convert(double when, struct tm * (*function)(const time_t *))
Guido van Rossum234f9421993-06-17 12:35:49 +0000276{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000277 struct tm *p;
278 time_t whent = _PyTime_DoubleToTimet(when);
Brett Cannon298c3802004-06-19 20:48:43 +0000279
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000280 if (whent == (time_t)-1 && PyErr_Occurred())
281 return NULL;
282 errno = 0;
283 p = function(&whent);
284 if (p == NULL) {
Guido van Rossum6e8583d1996-10-08 14:19:52 +0000285#ifdef EINVAL
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000286 if (errno == 0)
287 errno = EINVAL;
Guido van Rossum6e8583d1996-10-08 14:19:52 +0000288#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000289 return PyErr_SetFromErrno(PyExc_ValueError);
290 }
291 return tmtotuple(p);
Guido van Rossum234f9421993-06-17 12:35:49 +0000292}
293
Fred Drakef901abd2004-08-03 17:58:55 +0000294/* Parse arg tuple that can contain an optional float-or-None value;
295 format needs to be "|O:name".
296 Returns non-zero on success (parallels PyArg_ParseTuple).
297*/
298static int
299parse_time_double_args(PyObject *args, char *format, double *pwhen)
300{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000301 PyObject *ot = NULL;
Fred Drakef901abd2004-08-03 17:58:55 +0000302
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000303 if (!PyArg_ParseTuple(args, format, &ot))
304 return 0;
305 if (ot == NULL || ot == Py_None)
306 *pwhen = floattime();
307 else {
308 double when = PyFloat_AsDouble(ot);
309 if (PyErr_Occurred())
310 return 0;
311 *pwhen = when;
312 }
313 return 1;
Fred Drakef901abd2004-08-03 17:58:55 +0000314}
315
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000316static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000317time_gmtime(PyObject *self, PyObject *args)
Guido van Rossum234f9421993-06-17 12:35:49 +0000318{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000319 double when;
320 if (!parse_time_double_args(args, "|O:gmtime", &when))
321 return NULL;
322 return time_convert(when, gmtime);
Guido van Rossum234f9421993-06-17 12:35:49 +0000323}
324
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000325PyDoc_STRVAR(gmtime_doc,
Brett Cannon8d993aa2007-12-24 19:58:25 +0000326"gmtime([seconds]) -> (tm_year, tm_mon, tm_mday, tm_hour, tm_min,\n\
Fred Drake193a3f62002-03-12 21:38:49 +0000327 tm_sec, tm_wday, tm_yday, tm_isdst)\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000328\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000329Convert seconds since the Epoch to a time tuple expressing UTC (a.k.a.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000330GMT). When 'seconds' is not passed in, convert the current time instead.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000331
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000332static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000333time_localtime(PyObject *self, PyObject *args)
Guido van Rossum234f9421993-06-17 12:35:49 +0000334{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000335 double when;
336 if (!parse_time_double_args(args, "|O:localtime", &when))
337 return NULL;
338 return time_convert(when, localtime);
Guido van Rossum234f9421993-06-17 12:35:49 +0000339}
340
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000341PyDoc_STRVAR(localtime_doc,
Brett Cannon8d993aa2007-12-24 19:58:25 +0000342"localtime([seconds]) -> (tm_year,tm_mon,tm_mday,tm_hour,tm_min,\n\
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000343 tm_sec,tm_wday,tm_yday,tm_isdst)\n\
Martin v. Löwisb3cfc1d2001-12-02 12:27:43 +0000344\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000345Convert seconds since the Epoch to a time tuple expressing local time.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000346When 'seconds' is not passed in, convert the current time instead.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000347
Guido van Rossum9e90a671993-06-24 11:10:19 +0000348static int
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000349gettmarg(PyObject *args, struct tm *p)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000350{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000351 int y;
352 memset((void *) p, '\0', sizeof(struct tm));
Guido van Rossumcfbaecc1998-08-25 14:51:12 +0000353
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000354 if (!PyArg_Parse(args, "(iiiiiiiii)",
355 &y,
356 &p->tm_mon,
357 &p->tm_mday,
358 &p->tm_hour,
359 &p->tm_min,
360 &p->tm_sec,
361 &p->tm_wday,
362 &p->tm_yday,
363 &p->tm_isdst))
364 return 0;
365 if (y < 1900) {
366 PyObject *accept = PyDict_GetItemString(moddict,
367 "accept2dyear");
368 if (accept == NULL || !PyInt_Check(accept) ||
369 PyInt_AsLong(accept) == 0) {
370 PyErr_SetString(PyExc_ValueError,
371 "year >= 1900 required");
372 return 0;
373 }
374 if (69 <= y && y <= 99)
375 y += 1900;
376 else if (0 <= y && y <= 68)
377 y += 2000;
378 else {
379 PyErr_SetString(PyExc_ValueError,
380 "year out of range");
381 return 0;
382 }
383 }
384 p->tm_year = y - 1900;
385 p->tm_mon--;
386 p->tm_wday = (p->tm_wday + 1) % 7;
387 p->tm_yday--;
388 return 1;
Guido van Rossum9e90a671993-06-24 11:10:19 +0000389}
390
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000391#ifdef HAVE_STRFTIME
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000392static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000393time_strftime(PyObject *self, PyObject *args)
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000394{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000395 PyObject *tup = NULL;
396 struct tm buf;
397 const char *fmt;
398 size_t fmtlen, buflen;
399 char *outbuf = 0;
400 size_t i;
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000401
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000402 memset((void *) &buf, '\0', sizeof(buf));
Guido van Rossum1f41f841998-04-27 19:04:26 +0000403
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000404 if (!PyArg_ParseTuple(args, "s|O:strftime", &fmt, &tup))
405 return NULL;
Thomas Woutersfe385252001-01-19 23:16:56 +0000406
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000407 if (tup == NULL) {
408 time_t tt = time(NULL);
409 buf = *localtime(&tt);
410 } else if (!gettmarg(tup, &buf))
411 return NULL;
Guido van Rossum10b164a2001-09-25 13:59:01 +0000412
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000413 /* Checks added to make sure strftime() does not crash Python by
414 indexing blindly into some array for a textual representation
415 by some bad index (fixes bug #897625).
Tim Peters1b6f7a92004-06-20 02:50:16 +0000416
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000417 Also support values of zero from Python code for arguments in which
418 that is out of range by forcing that value to the lowest value that
419 is valid (fixed bug #1520914).
Brett Cannoncaebe222006-07-18 04:41:36 +0000420
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000421 Valid ranges based on what is allowed in struct tm:
Brett Cannoncaebe222006-07-18 04:41:36 +0000422
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000423 - tm_year: [0, max(int)] (1)
424 - tm_mon: [0, 11] (2)
425 - tm_mday: [1, 31]
426 - tm_hour: [0, 23]
427 - tm_min: [0, 59]
428 - tm_sec: [0, 60]
429 - tm_wday: [0, 6] (1)
430 - tm_yday: [0, 365] (2)
431 - tm_isdst: [-max(int), max(int)]
Brett Cannoncaebe222006-07-18 04:41:36 +0000432
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000433 (1) gettmarg() handles bounds-checking.
434 (2) Python's acceptable range is one greater than the range in C,
435 thus need to check against automatic decrement by gettmarg().
436 */
437 if (buf.tm_mon == -1)
438 buf.tm_mon = 0;
439 else if (buf.tm_mon < 0 || buf.tm_mon > 11) {
440 PyErr_SetString(PyExc_ValueError, "month out of range");
441 return NULL;
442 }
443 if (buf.tm_mday == 0)
444 buf.tm_mday = 1;
445 else if (buf.tm_mday < 0 || buf.tm_mday > 31) {
446 PyErr_SetString(PyExc_ValueError, "day of month out of range");
447 return NULL;
448 }
449 if (buf.tm_hour < 0 || buf.tm_hour > 23) {
450 PyErr_SetString(PyExc_ValueError, "hour out of range");
451 return NULL;
452 }
453 if (buf.tm_min < 0 || buf.tm_min > 59) {
454 PyErr_SetString(PyExc_ValueError, "minute out of range");
455 return NULL;
456 }
457 if (buf.tm_sec < 0 || buf.tm_sec > 61) {
458 PyErr_SetString(PyExc_ValueError, "seconds out of range");
459 return NULL;
460 }
461 /* tm_wday does not need checking of its upper-bound since taking
462 ``% 7`` in gettmarg() automatically restricts the range. */
463 if (buf.tm_wday < 0) {
464 PyErr_SetString(PyExc_ValueError, "day of week out of range");
465 return NULL;
466 }
467 if (buf.tm_yday == -1)
468 buf.tm_yday = 0;
469 else if (buf.tm_yday < 0 || buf.tm_yday > 365) {
470 PyErr_SetString(PyExc_ValueError, "day of year out of range");
471 return NULL;
472 }
473 /* Normalize tm_isdst just in case someone foolishly implements %Z
474 based on the assumption that tm_isdst falls within the range of
475 [-1, 1] */
476 if (buf.tm_isdst < -1)
477 buf.tm_isdst = -1;
478 else if (buf.tm_isdst > 1)
479 buf.tm_isdst = 1;
Brett Cannond1080a32004-03-02 04:38:10 +0000480
Kristján Valur Jónssonfd4c8722009-02-04 10:05:25 +0000481#ifdef MS_WINDOWS
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000482 /* check that the format string contains only valid directives */
483 for(outbuf = strchr(fmt, '%');
484 outbuf != NULL;
485 outbuf = strchr(outbuf+2, '%'))
486 {
487 if (outbuf[1]=='#')
488 ++outbuf; /* not documented by python, */
489 if (outbuf[1]=='\0' ||
Senthil Kumaran792eb5d2011-04-06 14:27:47 +0800490 !strchr("aAbBcdHIjmMpSUwWxXyYzZ%", outbuf[1]))
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000491 {
492 PyErr_SetString(PyExc_ValueError, "Invalid format string");
493 return 0;
494 }
495 }
Kristján Valur Jónssonfd4c8722009-02-04 10:05:25 +0000496#endif
497
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000498 fmtlen = strlen(fmt);
Guido van Rossumc222ec21999-02-23 00:00:10 +0000499
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000500 /* I hate these functions that presume you know how big the output
501 * will be ahead of time...
502 */
503 for (i = 1024; ; i += i) {
504 outbuf = (char *)malloc(i);
505 if (outbuf == NULL) {
506 return PyErr_NoMemory();
507 }
508 buflen = strftime(outbuf, i, fmt, &buf);
509 if (buflen > 0 || i >= 256 * fmtlen) {
510 /* If the buffer is 256 times as long as the format,
511 it's probably not failing for lack of room!
512 More likely, the format yields an empty result,
513 e.g. an empty format, or %Z when the timezone
514 is unknown. */
515 PyObject *ret;
516 ret = PyString_FromStringAndSize(outbuf, buflen);
517 free(outbuf);
518 return ret;
519 }
520 free(outbuf);
Kristján Valur Jónsson74c3ea02006-07-03 14:59:05 +0000521#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000522 /* VisualStudio .NET 2005 does this properly */
523 if (buflen == 0 && errno == EINVAL) {
524 PyErr_SetString(PyExc_ValueError, "Invalid format string");
525 return 0;
526 }
Kristján Valur Jónssonf6083172006-06-12 15:45:12 +0000527#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000528
529 }
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000530}
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000531
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000532PyDoc_STRVAR(strftime_doc,
Thomas Woutersfe385252001-01-19 23:16:56 +0000533"strftime(format[, tuple]) -> string\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000534\n\
535Convert a time tuple to a string according to a format specification.\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000536See the library reference manual for formatting codes. When the time tuple\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000537is not present, current time as returned by localtime() is used.");
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000538#endif /* HAVE_STRFTIME */
539
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000540static PyObject *
541time_strptime(PyObject *self, PyObject *args)
542{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000543 PyObject *strptime_module = PyImport_ImportModuleNoBlock("_strptime");
544 PyObject *strptime_result;
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000545
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000546 if (!strptime_module)
547 return NULL;
548 strptime_result = PyObject_CallMethod(strptime_module,
549 "_strptime_time", "O", args);
550 Py_DECREF(strptime_module);
551 return strptime_result;
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000552}
553
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000554PyDoc_STRVAR(strptime_doc,
Brett Cannon20def8b2003-07-01 05:16:08 +0000555"strptime(string, format) -> struct_time\n\
Martin v. Löwisb3cfc1d2001-12-02 12:27:43 +0000556\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000557Parse a string to a time tuple according to a format specification.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000558See the library reference manual for formatting codes (same as strftime()).");
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000559
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000560
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000561static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000562time_asctime(PyObject *self, PyObject *args)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000563{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000564 PyObject *tup = NULL;
565 struct tm buf;
566 char *p;
567 if (!PyArg_UnpackTuple(args, "asctime", 0, 1, &tup))
568 return NULL;
569 if (tup == NULL) {
570 time_t tt = time(NULL);
571 buf = *localtime(&tt);
572 } else if (!gettmarg(tup, &buf))
573 return NULL;
574 p = asctime(&buf);
Alexander Belopolsky8009e8e2011-01-02 23:23:54 +0000575 if (p == NULL) {
576 PyErr_SetString(PyExc_ValueError, "invalid time");
577 return NULL;
578 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000579 if (p[24] == '\n')
580 p[24] = '\0';
581 return PyString_FromString(p);
Guido van Rossum9e90a671993-06-24 11:10:19 +0000582}
583
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000584PyDoc_STRVAR(asctime_doc,
Thomas Woutersfe385252001-01-19 23:16:56 +0000585"asctime([tuple]) -> string\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000586\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000587Convert a time tuple to a string, e.g. 'Sat Jun 06 16:26:11 1998'.\n\
588When the time tuple is not present, current time as returned by localtime()\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000589is used.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000590
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000591static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000592time_ctime(PyObject *self, PyObject *args)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000593{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000594 PyObject *ot = NULL;
595 time_t tt;
596 char *p;
Guido van Rossum10b164a2001-09-25 13:59:01 +0000597
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000598 if (!PyArg_UnpackTuple(args, "ctime", 0, 1, &ot))
599 return NULL;
600 if (ot == NULL || ot == Py_None)
601 tt = time(NULL);
602 else {
603 double dt = PyFloat_AsDouble(ot);
604 if (PyErr_Occurred())
605 return NULL;
606 tt = _PyTime_DoubleToTimet(dt);
607 if (tt == (time_t)-1 && PyErr_Occurred())
608 return NULL;
609 }
610 p = ctime(&tt);
611 if (p == NULL) {
612 PyErr_SetString(PyExc_ValueError, "unconvertible time");
613 return NULL;
614 }
615 if (p[24] == '\n')
616 p[24] = '\0';
617 return PyString_FromString(p);
Guido van Rossum9e90a671993-06-24 11:10:19 +0000618}
619
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000620PyDoc_STRVAR(ctime_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000621"ctime(seconds) -> string\n\
622\n\
623Convert a time in seconds since the Epoch to a string in local time.\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000624This is equivalent to asctime(localtime(seconds)). When the time tuple is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000625not present, current time as returned by localtime() is used.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000626
Guido van Rossum60cd8131998-03-06 17:16:21 +0000627#ifdef HAVE_MKTIME
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000628static PyObject *
Georg Brandl96a8c392006-05-29 21:04:52 +0000629time_mktime(PyObject *self, PyObject *tup)
Guido van Rossum234f9421993-06-17 12:35:49 +0000630{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000631 struct tm buf;
632 time_t tt;
633 if (!gettmarg(tup, &buf))
634 return NULL;
Alexander Belopolsky6233b362011-02-15 15:51:17 +0000635 buf.tm_wday = -1; /* sentinel; original value ignored */
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000636 tt = mktime(&buf);
Alexander Belopolsky6233b362011-02-15 15:51:17 +0000637 /* Return value of -1 does not necessarily mean an error, but tm_wday
Ezio Melottic2077b02011-03-16 12:34:31 +0200638 * cannot remain set to -1 if mktime succeeded. */
Alexander Belopolsky6233b362011-02-15 15:51:17 +0000639 if (tt == (time_t)(-1) && buf.tm_wday == -1) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000640 PyErr_SetString(PyExc_OverflowError,
641 "mktime argument out of range");
642 return NULL;
643 }
644 return PyFloat_FromDouble((double)tt);
Guido van Rossum234f9421993-06-17 12:35:49 +0000645}
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000646
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000647PyDoc_STRVAR(mktime_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000648"mktime(tuple) -> floating point number\n\
649\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000650Convert a time tuple in local time to seconds since the Epoch.");
Guido van Rossum60cd8131998-03-06 17:16:21 +0000651#endif /* HAVE_MKTIME */
Guido van Rossum234f9421993-06-17 12:35:49 +0000652
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000653#ifdef HAVE_WORKING_TZSET
Skip Montanaro9e0fa7a2008-04-05 19:47:47 +0000654static void inittimezone(PyObject *module);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000655
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000656static PyObject *
Georg Brandl96a8c392006-05-29 21:04:52 +0000657time_tzset(PyObject *self, PyObject *unused)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000658{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000659 PyObject* m;
Fred Drake9bb74322002-04-01 14:49:59 +0000660
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000661 m = PyImport_ImportModuleNoBlock("time");
662 if (m == NULL) {
663 return NULL;
664 }
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000665
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000666 tzset();
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000667
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000668 /* Reset timezone, altzone, daylight and tzname */
669 inittimezone(m);
670 Py_DECREF(m);
Tim Peters1b6f7a92004-06-20 02:50:16 +0000671
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000672 Py_INCREF(Py_None);
673 return Py_None;
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000674}
675
676PyDoc_STRVAR(tzset_doc,
R. David Murray561b96f2011-02-11 17:25:54 +0000677"tzset()\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000678\n\
679Initialize, or reinitialize, the local timezone to the value stored in\n\
680os.environ['TZ']. The TZ environment variable should be specified in\n\
Neal Norwitzdc8e1942004-07-20 22:34:37 +0000681standard Unix timezone format as documented in the tzset man page\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000682(eg. 'US/Eastern', 'Europe/Amsterdam'). Unknown timezones will silently\n\
683fall back to UTC. If the TZ environment variable is not set, the local\n\
684timezone is set to the systems best guess of wallclock time.\n\
685Changing the TZ environment variable without calling tzset *may* change\n\
686the local timezone used by methods such as localtime, but this behaviour\n\
687should not be relied on.");
688#endif /* HAVE_WORKING_TZSET */
689
Skip Montanaro9e0fa7a2008-04-05 19:47:47 +0000690static void
691inittimezone(PyObject *m) {
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000692 /* This code moved from inittime wholesale to allow calling it from
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000693 time_tzset. In the future, some parts of it can be moved back
694 (for platforms that don't HAVE_WORKING_TZSET, when we know what they
695 are), and the extraneous calls to tzset(3) should be removed.
696 I haven't done this yet, as I don't want to change this code as
697 little as possible when introducing the time.tzset and time.tzsetwall
698 methods. This should simply be a method of doing the following once,
699 at the top of this function and removing the call to tzset() from
700 time_tzset():
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000701
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000702 #ifdef HAVE_TZSET
703 tzset()
704 #endif
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000705
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000706 And I'm lazy and hate C so nyer.
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000707 */
Guido van Rossum10b164a2001-09-25 13:59:01 +0000708#if defined(HAVE_TZNAME) && !defined(__GLIBC__) && !defined(__CYGWIN__)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000709 tzset();
Guido van Rossum26452411998-09-28 22:07:11 +0000710#ifdef PYOS_OS2
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000711 PyModule_AddIntConstant(m, "timezone", _timezone);
Guido van Rossum26452411998-09-28 22:07:11 +0000712#else /* !PYOS_OS2 */
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000713 PyModule_AddIntConstant(m, "timezone", timezone);
Guido van Rossum26452411998-09-28 22:07:11 +0000714#endif /* PYOS_OS2 */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000715#ifdef HAVE_ALTZONE
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000716 PyModule_AddIntConstant(m, "altzone", altzone);
Guido van Rossumb6775db1994-08-01 11:34:53 +0000717#else
Guido van Rossum26452411998-09-28 22:07:11 +0000718#ifdef PYOS_OS2
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000719 PyModule_AddIntConstant(m, "altzone", _timezone-3600);
Guido van Rossum26452411998-09-28 22:07:11 +0000720#else /* !PYOS_OS2 */
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000721 PyModule_AddIntConstant(m, "altzone", timezone-3600);
Guido van Rossum26452411998-09-28 22:07:11 +0000722#endif /* PYOS_OS2 */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000723#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000724 PyModule_AddIntConstant(m, "daylight", daylight);
725 PyModule_AddObject(m, "tzname",
726 Py_BuildValue("(zz)", tzname[0], tzname[1]));
Guido van Rossum10b164a2001-09-25 13:59:01 +0000727#else /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/
Martin v. Löwis60a5d722002-10-16 20:28:25 +0000728#ifdef HAVE_STRUCT_TM_TM_ZONE
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000729 {
Guido van Rossum234f9421993-06-17 12:35:49 +0000730#define YEAR ((time_t)((365 * 24 + 6) * 3600))
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000731 time_t t;
732 struct tm *p;
733 long janzone, julyzone;
734 char janname[10], julyname[10];
735 t = (time((time_t *)0) / YEAR) * YEAR;
736 p = localtime(&t);
737 janzone = -p->tm_gmtoff;
738 strncpy(janname, p->tm_zone ? p->tm_zone : " ", 9);
739 janname[9] = '\0';
740 t += YEAR/2;
741 p = localtime(&t);
742 julyzone = -p->tm_gmtoff;
743 strncpy(julyname, p->tm_zone ? p->tm_zone : " ", 9);
744 julyname[9] = '\0';
Guido van Rossum10b164a2001-09-25 13:59:01 +0000745
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000746 if( janzone < julyzone ) {
747 /* DST is reversed in the southern hemisphere */
748 PyModule_AddIntConstant(m, "timezone", julyzone);
749 PyModule_AddIntConstant(m, "altzone", janzone);
750 PyModule_AddIntConstant(m, "daylight",
751 janzone != julyzone);
752 PyModule_AddObject(m, "tzname",
753 Py_BuildValue("(zz)",
754 julyname, janname));
755 } else {
756 PyModule_AddIntConstant(m, "timezone", janzone);
757 PyModule_AddIntConstant(m, "altzone", julyzone);
758 PyModule_AddIntConstant(m, "daylight",
759 janzone != julyzone);
760 PyModule_AddObject(m, "tzname",
761 Py_BuildValue("(zz)",
762 janname, julyname));
763 }
764 }
Guido van Rossume6a4b7b1997-10-08 15:27:56 +0000765#else
Martin v. Löwis60a5d722002-10-16 20:28:25 +0000766#endif /* HAVE_STRUCT_TM_TM_ZONE */
Tim Peters26ae7cd2001-03-20 03:26:49 +0000767#ifdef __CYGWIN__
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000768 tzset();
769 PyModule_AddIntConstant(m, "timezone", _timezone);
770 PyModule_AddIntConstant(m, "altzone", _timezone-3600);
771 PyModule_AddIntConstant(m, "daylight", _daylight);
772 PyModule_AddObject(m, "tzname",
773 Py_BuildValue("(zz)", _tzname[0], _tzname[1]));
Tim Peters26ae7cd2001-03-20 03:26:49 +0000774#endif /* __CYGWIN__ */
Guido van Rossum10b164a2001-09-25 13:59:01 +0000775#endif /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000776}
777
778
779static PyMethodDef time_methods[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000780 {"time", time_time, METH_NOARGS, time_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000781#ifdef HAVE_CLOCK
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000782 {"clock", time_clock, METH_NOARGS, clock_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000783#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000784 {"sleep", time_sleep, METH_VARARGS, sleep_doc},
785 {"gmtime", time_gmtime, METH_VARARGS, gmtime_doc},
786 {"localtime", time_localtime, METH_VARARGS, localtime_doc},
787 {"asctime", time_asctime, METH_VARARGS, asctime_doc},
788 {"ctime", time_ctime, METH_VARARGS, ctime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000789#ifdef HAVE_MKTIME
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000790 {"mktime", time_mktime, METH_O, mktime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000791#endif
792#ifdef HAVE_STRFTIME
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000793 {"strftime", time_strftime, METH_VARARGS, strftime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000794#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000795 {"strptime", time_strptime, METH_VARARGS, strptime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000796#ifdef HAVE_WORKING_TZSET
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000797 {"tzset", time_tzset, METH_NOARGS, tzset_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000798#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000799 {NULL, NULL} /* sentinel */
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000800};
801
802
803PyDoc_STRVAR(module_doc,
804"This module provides various functions to manipulate time values.\n\
805\n\
806There are two standard representations of time. One is the number\n\
807of seconds since the Epoch, in UTC (a.k.a. GMT). It may be an integer\n\
808or a floating point number (to represent fractions of seconds).\n\
809The Epoch is system-defined; on Unix, it is generally January 1st, 1970.\n\
810The actual value can be retrieved by calling gmtime(0).\n\
811\n\
812The other representation is a tuple of 9 integers giving local time.\n\
813The tuple items are:\n\
814 year (four digits, e.g. 1998)\n\
815 month (1-12)\n\
816 day (1-31)\n\
817 hours (0-23)\n\
818 minutes (0-59)\n\
819 seconds (0-59)\n\
820 weekday (0-6, Monday is 0)\n\
821 Julian day (day in the year, 1-366)\n\
822 DST (Daylight Savings Time) flag (-1, 0 or 1)\n\
823If the DST flag is 0, the time is given in the regular time zone;\n\
824if it is 1, the time is given in the DST time zone;\n\
825if it is -1, mktime() should guess based on the date and time.\n\
826\n\
827Variables:\n\
828\n\
829timezone -- difference in seconds between UTC and local standard time\n\
830altzone -- difference in seconds between UTC and local DST time\n\
831daylight -- whether local time should reflect DST\n\
832tzname -- tuple of (standard time zone name, DST time zone name)\n\
833\n\
834Functions:\n\
835\n\
836time() -- return current time in seconds since the Epoch as a float\n\
837clock() -- return CPU time since process start as a float\n\
838sleep() -- delay for a number of seconds given as a float\n\
839gmtime() -- convert seconds since Epoch to UTC tuple\n\
840localtime() -- convert seconds since Epoch to local time tuple\n\
841asctime() -- convert time tuple to string\n\
842ctime() -- convert time in seconds to string\n\
843mktime() -- convert local time tuple to seconds since Epoch\n\
844strftime() -- convert time tuple to string according to format specification\n\
845strptime() -- parse string to time tuple according to format specification\n\
846tzset() -- change the local timezone");
847
848
849PyMODINIT_FUNC
850inittime(void)
851{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000852 PyObject *m;
853 char *p;
854 m = Py_InitModule3("time", time_methods, module_doc);
855 if (m == NULL)
856 return;
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000857
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000858 /* Accept 2-digit dates unless PYTHONY2K is set and non-empty */
859 p = Py_GETENV("PYTHONY2K");
860 PyModule_AddIntConstant(m, "accept2dyear", (long) (!p || !*p));
Gregory P. Smith0d68ab32012-11-27 10:19:29 -0800861 /* If an embedded interpreter is shutdown and reinitialized the old
862 moddict was not decrefed on shutdown and the next import of this
863 module leads to a leak. Conditionally decref here to prevent that.
864 */
865 Py_XDECREF(moddict);
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000866 /* Squirrel away the module's dictionary for the y2k check */
867 moddict = PyModule_GetDict(m);
868 Py_INCREF(moddict);
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000869
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000870 /* Set, or reset, module variables like time.timezone */
871 inittimezone(m);
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000872
Mark Hammond975e3922002-07-16 01:29:19 +0000873#ifdef MS_WINDOWS
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000874 /* Helper to allow interrupts for Windows.
875 If Ctrl+C event delivered while not sleeping
876 it will be ignored.
877 */
878 main_thread = PyThread_get_thread_ident();
879 hInterruptEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
880 SetConsoleCtrlHandler( PyCtrlHandler, TRUE);
Mark Hammond975e3922002-07-16 01:29:19 +0000881#endif /* MS_WINDOWS */
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000882 if (!initialized) {
883 PyStructSequence_InitType(&StructTimeType,
884 &struct_time_type_desc);
885 }
886 Py_INCREF(&StructTimeType);
887 PyModule_AddObject(m, "struct_time", (PyObject*) &StructTimeType);
888 initialized = 1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000889}
890
891
Guido van Rossumb6775db1994-08-01 11:34:53 +0000892/* Implement floattime() for various platforms */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000893
Guido van Rossumb6775db1994-08-01 11:34:53 +0000894static double
Thomas Woutersf3f33dc2000-07-21 06:00:07 +0000895floattime(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000896{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000897 /* There are three ways to get the time:
898 (1) gettimeofday() -- resolution in microseconds
899 (2) ftime() -- resolution in milliseconds
900 (3) time() -- resolution in seconds
901 In all cases the return value is a float in seconds.
902 Since on some systems (e.g. SCO ODT 3.0) gettimeofday() may
903 fail, so we fall back on ftime() or time().
904 Note: clock resolution does not imply clock accuracy! */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000905#ifdef HAVE_GETTIMEOFDAY
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000906 {
907 struct timeval t;
Guido van Rossum3bbc62e1995-01-02 19:30:30 +0000908#ifdef GETTIMEOFDAY_NO_TZ
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000909 if (gettimeofday(&t) == 0)
910 return (double)t.tv_sec + t.tv_usec*0.000001;
Guido van Rossum3bbc62e1995-01-02 19:30:30 +0000911#else /* !GETTIMEOFDAY_NO_TZ */
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000912 if (gettimeofday(&t, (struct timezone *)NULL) == 0)
913 return (double)t.tv_sec + t.tv_usec*0.000001;
Guido van Rossum3bbc62e1995-01-02 19:30:30 +0000914#endif /* !GETTIMEOFDAY_NO_TZ */
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000915 }
Ronald Oussorend06b6f22006-04-23 11:59:25 +0000916
Guido van Rossumb6775db1994-08-01 11:34:53 +0000917#endif /* !HAVE_GETTIMEOFDAY */
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000918 {
Guido van Rossumd3eb5771999-03-09 16:07:23 +0000919#if defined(HAVE_FTIME)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000920 struct timeb t;
921 ftime(&t);
922 return (double)t.time + (double)t.millitm * (double)0.001;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000923#else /* !HAVE_FTIME */
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000924 time_t secs;
925 time(&secs);
926 return (double)secs;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000927#endif /* !HAVE_FTIME */
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000928 }
Guido van Rossum426035c1991-02-19 12:27:35 +0000929}
930
Guido van Rossumb6775db1994-08-01 11:34:53 +0000931
932/* Implement floatsleep() for various platforms.
933 When interrupted (or when another error occurs), return -1 and
934 set an exception; else return 0. */
935
936static int
Guido van Rossuma320fd31995-03-09 12:14:15 +0000937floatsleep(double secs)
Guido van Rossum426035c1991-02-19 12:27:35 +0000938{
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000939/* XXX Should test for MS_WINDOWS first! */
Andrew MacIntyre7bf68332002-03-03 02:59:16 +0000940#if defined(HAVE_SELECT) && !defined(__BEOS__) && !defined(__EMX__)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000941 struct timeval t;
942 double frac;
943 frac = fmod(secs, 1.0);
944 secs = floor(secs);
945 t.tv_sec = (long)secs;
946 t.tv_usec = (long)(frac*1000000.0);
947 Py_BEGIN_ALLOW_THREADS
948 if (select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &t) != 0) {
Guido van Rossum09cbb011999-11-08 15:32:27 +0000949#ifdef EINTR
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000950 if (errno != EINTR) {
Guido van Rossum09cbb011999-11-08 15:32:27 +0000951#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000952 if (1) {
Guido van Rossum09cbb011999-11-08 15:32:27 +0000953#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000954 Py_BLOCK_THREADS
955 PyErr_SetFromErrno(PyExc_IOError);
956 return -1;
957 }
958 }
959 Py_END_ALLOW_THREADS
Martin v. Löwis02af9642002-01-16 11:04:06 +0000960#elif defined(__WATCOMC__) && !defined(__QNX__)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000961 /* XXX Can't interrupt this sleep */
962 Py_BEGIN_ALLOW_THREADS
963 delay((int)(secs * 1000 + 0.5)); /* delay() uses milliseconds */
964 Py_END_ALLOW_THREADS
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000965#elif defined(MS_WINDOWS)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000966 {
967 double millisecs = secs * 1000.0;
968 unsigned long ul_millis;
Tim Peters513a1cd2003-01-19 04:54:58 +0000969
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000970 if (millisecs > (double)ULONG_MAX) {
971 PyErr_SetString(PyExc_OverflowError,
972 "sleep length is too large");
973 return -1;
974 }
975 Py_BEGIN_ALLOW_THREADS
976 /* Allow sleep(0) to maintain win32 semantics, and as decreed
977 * by Guido, only the main thread can be interrupted.
978 */
979 ul_millis = (unsigned long)millisecs;
980 if (ul_millis == 0 ||
981 main_thread != PyThread_get_thread_ident())
982 Sleep(ul_millis);
983 else {
984 DWORD rc;
985 ResetEvent(hInterruptEvent);
986 rc = WaitForSingleObject(hInterruptEvent, ul_millis);
987 if (rc == WAIT_OBJECT_0) {
988 /* Yield to make sure real Python signal
989 * handler called.
990 */
991 Sleep(1);
992 Py_BLOCK_THREADS
993 errno = EINTR;
994 PyErr_SetFromErrno(PyExc_IOError);
995 return -1;
996 }
997 }
998 Py_END_ALLOW_THREADS
999 }
Martin v. Löwis02af9642002-01-16 11:04:06 +00001000#elif defined(PYOS_OS2)
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001001 /* This Sleep *IS* Interruptable by Exceptions */
1002 Py_BEGIN_ALLOW_THREADS
1003 if (DosSleep(secs * 1000) != NO_ERROR) {
1004 Py_BLOCK_THREADS
1005 PyErr_SetFromErrno(PyExc_IOError);
1006 return -1;
1007 }
1008 Py_END_ALLOW_THREADS
Martin v. Löwis02af9642002-01-16 11:04:06 +00001009#elif defined(__BEOS__)
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001010 /* This sleep *CAN BE* interrupted. */
1011 {
1012 if( secs <= 0.0 ) {
1013 return;
1014 }
Guido van Rossum10b164a2001-09-25 13:59:01 +00001015
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001016 Py_BEGIN_ALLOW_THREADS
1017 /* BeOS snooze() is in microseconds... */
1018 if( snooze( (bigtime_t)( secs * 1000.0 * 1000.0 ) ) == B_INTERRUPTED ) {
1019 Py_BLOCK_THREADS
1020 PyErr_SetFromErrno( PyExc_IOError );
1021 return -1;
1022 }
1023 Py_END_ALLOW_THREADS
1024 }
Martin v. Löwis02af9642002-01-16 11:04:06 +00001025#elif defined(RISCOS)
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001026 if (secs <= 0.0)
1027 return 0;
1028 Py_BEGIN_ALLOW_THREADS
1029 /* This sleep *CAN BE* interrupted. */
1030 if ( riscos_sleep(secs) )
1031 return -1;
1032 Py_END_ALLOW_THREADS
Martin v. Löwis02af9642002-01-16 11:04:06 +00001033#elif defined(PLAN9)
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001034 {
1035 double millisecs = secs * 1000.0;
1036 if (millisecs > (double)LONG_MAX) {
1037 PyErr_SetString(PyExc_OverflowError, "sleep length is too large");
1038 return -1;
1039 }
1040 /* This sleep *CAN BE* interrupted. */
1041 Py_BEGIN_ALLOW_THREADS
1042 if(sleep((long)millisecs) < 0){
1043 Py_BLOCK_THREADS
1044 PyErr_SetFromErrno(PyExc_IOError);
1045 return -1;
1046 }
1047 Py_END_ALLOW_THREADS
1048 }
Martin v. Löwis02af9642002-01-16 11:04:06 +00001049#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001050 /* XXX Can't interrupt this sleep */
1051 Py_BEGIN_ALLOW_THREADS
1052 sleep((int)secs);
1053 Py_END_ALLOW_THREADS
Martin v. Löwis02af9642002-01-16 11:04:06 +00001054#endif
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001055
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001056 return 0;
Guido van Rossum80c9d881991-04-16 08:47:51 +00001057}
Kristján Valur Jónsson6ebc8f32013-03-19 10:58:59 -07001058
1059/* export floattime to socketmodule.c */
1060PyAPI_FUNC(double)
Kristján Valur Jónsson868f0aa2013-03-19 13:53:56 -07001061_PyTime_FloatTime(void)
Kristján Valur Jónsson6ebc8f32013-03-19 10:58:59 -07001062{
1063 return floattime();
1064}