blob: 16940fe1f38901c53ffc0cadcaac0470bd6ac3bf [file] [log] [blame]
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001/* Time module */
2
Barry Warsaw9a2a8a81996-12-06 23:32:14 +00003#include "Python.h"
Alexander Belopolsky6fc4ade2010-08-05 17:34:27 +00004#include "_time.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +00005
Guido van Rossum87ce7bb1998-06-09 16:30:31 +00006#include <ctype.h>
7
Thomas Wouters0e3f5912006-08-11 14:57:12 +00008#ifdef HAVE_SYS_TYPES_H
Guido van Rossumb6775db1994-08-01 11:34:53 +00009#include <sys/types.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +000010#endif /* HAVE_SYS_TYPES_H */
Guido van Rossum6d946f91992-08-14 13:49:30 +000011
Guido van Rossumb6775db1994-08-01 11:34:53 +000012#ifdef QUICKWIN
13#include <io.h>
14#endif
15
Guido van Rossum7bf22de1997-12-02 20:34:19 +000016#if defined(__WATCOMC__) && !defined(__QNX__)
Guido van Rossumbceeac81996-05-23 22:53:47 +000017#include <i86.h>
18#else
Guido van Rossumcac6c721996-09-06 13:34:02 +000019#ifdef MS_WINDOWS
Mark Hammond975e3922002-07-16 01:29:19 +000020#define WIN32_LEAN_AND_MEAN
Guido van Rossum258ccd42001-03-02 06:53:29 +000021#include <windows.h>
Mark Hammond975e3922002-07-16 01:29:19 +000022#include "pythread.h"
23
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000024#if defined(__BORLANDC__)
Guido van Rossumb2fb3641996-09-07 00:47:35 +000025/* These overrides not needed for Win32 */
Guido van Rossumb6775db1994-08-01 11:34:53 +000026#define timezone _timezone
Guido van Rossumcc081121995-03-14 15:05:41 +000027#define tzname _tzname
28#define daylight _daylight
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000029#endif /* __BORLANDC__ */
Guido van Rossumcac6c721996-09-06 13:34:02 +000030#endif /* MS_WINDOWS */
Guido van Rossum7bf22de1997-12-02 20:34:19 +000031#endif /* !__WATCOMC__ || __QNX__ */
Guido van Rossum234f9421993-06-17 12:35:49 +000032
Andrew MacIntyre7bf68332002-03-03 02:59:16 +000033#if defined(PYOS_OS2)
34#define INCL_DOS
35#define INCL_ERRORS
36#include <os2.h>
37#endif
38
Guido van Rossum8e9ebfd1997-11-22 21:53:48 +000039#if defined(PYCC_VACPP)
Guido van Rossum26452411998-09-28 22:07:11 +000040#include <sys/time.h>
Guido van Rossum8e9ebfd1997-11-22 21:53:48 +000041#endif
42
Victor Stinnerccd57152012-02-08 14:31:50 +010043#if (defined(MS_WINDOWS) && !defined(__BORLANDC__)) || defined(HAVE_CLOCK)
44# define HAVE_PYCLOCK
45#endif
46
Guido van Rossum234f9421993-06-17 12:35:49 +000047/* Forward declarations */
Tim Petersdbd9ba62000-07-09 03:09:57 +000048static int floatsleep(double);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000049
Barry Warsaw9a2a8a81996-12-06 23:32:14 +000050static PyObject *
Victor Stinnerccd57152012-02-08 14:31:50 +010051time_time(PyObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000052{
Victor Stinnerccd57152012-02-08 14:31:50 +010053 static char *kwlist[] = {"timestamp", NULL};
54 PyObject *timestamp = NULL;
55 _PyTime_t ts;
56
57 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|O:time", kwlist,
58 &timestamp))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000059 return NULL;
Victor Stinnerccd57152012-02-08 14:31:50 +010060
61 _PyTime_get(&ts);
62 return _PyTime_Convert(&ts, timestamp);
Guido van Rossumb6775db1994-08-01 11:34:53 +000063}
64
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000065PyDoc_STRVAR(time_doc,
Victor Stinnerccd57152012-02-08 14:31:50 +010066"time(timestamp=float) -> floating point number\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +000067\n\
68Return the current time in seconds since the Epoch.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000069Fractions of a second may be present if the system clock provides them.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +000070
Victor Stinner85fdfa82012-01-27 00:38:48 +010071#if defined(HAVE_CLOCK)
72
73#ifndef CLOCKS_PER_SEC
74#ifdef CLK_TCK
75#define CLOCKS_PER_SEC CLK_TCK
76#else
77#define CLOCKS_PER_SEC 1000000
78#endif
79#endif
80
Victor Stinnerccd57152012-02-08 14:31:50 +010081static int
82pyclock(_PyTime_t *ts)
Victor Stinner85fdfa82012-01-27 00:38:48 +010083{
Victor Stinnerccd57152012-02-08 14:31:50 +010084 clock_t processor_time;
85 processor_time = clock();
86 if (processor_time == (clock_t)-1) {
Victor Stinner85fdfa82012-01-27 00:38:48 +010087 PyErr_SetString(PyExc_RuntimeError,
88 "the processor time used is not available "
89 "or its value cannot be represented");
Victor Stinnerccd57152012-02-08 14:31:50 +010090 return -1;
Victor Stinner85fdfa82012-01-27 00:38:48 +010091 }
Victor Stinnerccd57152012-02-08 14:31:50 +010092 ts->seconds = 0;
93 assert(sizeof(clock_t) <= sizeof(_PyTime_fraction_t));
94 ts->numerator = Py_SAFE_DOWNCAST(processor_time,
95 clock_t, _PyTime_fraction_t);
96 ts->denominator = CLOCKS_PER_SEC;
97 return 0;
Victor Stinner85fdfa82012-01-27 00:38:48 +010098}
99#endif /* HAVE_CLOCK */
100
Thomas Wouters477c8d52006-05-27 19:21:47 +0000101#if defined(MS_WINDOWS) && !defined(__BORLANDC__)
Victor Stinner9122fdd2011-07-04 13:55:40 +0200102/* Win32 has better clock replacement; we have our own version, due to Mark
103 Hammond and Tim Peters */
Victor Stinnerccd57152012-02-08 14:31:50 +0100104static int
105win32_clock(_PyTime_t *ts, int fallback)
Guido van Rossum3917c221997-04-02 05:35:28 +0000106{
Victor Stinner8b302012012-02-07 23:29:46 +0100107 static LONGLONG cpu_frequency = 0;
Victor Stinnerccd57152012-02-08 14:31:50 +0100108 static LONGLONG start;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000109 LARGE_INTEGER now;
Victor Stinnerccd57152012-02-08 14:31:50 +0100110 LONGLONG dt;
Guido van Rossum3917c221997-04-02 05:35:28 +0000111
Victor Stinner8b302012012-02-07 23:29:46 +0100112 if (cpu_frequency == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000113 LARGE_INTEGER freq;
Victor Stinner8b302012012-02-07 23:29:46 +0100114 QueryPerformanceCounter(&now);
Victor Stinnerccd57152012-02-08 14:31:50 +0100115 start = now.QuadPart;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000116 if (!QueryPerformanceFrequency(&freq) || freq.QuadPart == 0) {
117 /* Unlikely to happen - this works on all intel
118 machines at least! Revert to clock() */
Victor Stinnerccd57152012-02-08 14:31:50 +0100119 if (fallback) {
120 return pyclock(ts);
121 }
122 else {
123 PyErr_SetFromWindowsErr(0);
124 return -1;
125 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000126 }
Victor Stinner8b302012012-02-07 23:29:46 +0100127 cpu_frequency = freq.QuadPart;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000128 }
129 QueryPerformanceCounter(&now);
Victor Stinnerccd57152012-02-08 14:31:50 +0100130 dt = now.QuadPart - start;
131
132 ts->seconds = 0;
133 assert(sizeof(LONGLONG) <= sizeof(_PyTime_fraction_t));
134 ts->numerator = Py_SAFE_DOWNCAST(dt,
135 LONGLONG, _PyTime_fraction_t);
136 ts->denominator = Py_SAFE_DOWNCAST(cpu_frequency,
137 LONGLONG, _PyTime_fraction_t);
138 return 0;
Guido van Rossum3917c221997-04-02 05:35:28 +0000139}
Victor Stinner8b302012012-02-07 23:29:46 +0100140#endif
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000141
Victor Stinner8b302012012-02-07 23:29:46 +0100142#if (defined(MS_WINDOWS) && !defined(__BORLANDC__)) || defined(HAVE_CLOCK)
Victor Stinner9122fdd2011-07-04 13:55:40 +0200143static PyObject *
Victor Stinnerccd57152012-02-08 14:31:50 +0100144time_clock(PyObject *self, PyObject *args, PyObject *kwargs)
Victor Stinner9122fdd2011-07-04 13:55:40 +0200145{
Victor Stinnerccd57152012-02-08 14:31:50 +0100146 static char *kwlist[] = {"timestamp", NULL};
147 _PyTime_t ts;
148 PyObject *timestamp = NULL;
149
150 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|O:clock", kwlist,
151 &timestamp))
152 return NULL;
153
Victor Stinner8b302012012-02-07 23:29:46 +0100154#if defined(MS_WINDOWS) && !defined(__BORLANDC__)
Victor Stinnerccd57152012-02-08 14:31:50 +0100155 if (win32_clock(&ts, 1) == -1)
156 return NULL;
Victor Stinner8b302012012-02-07 23:29:46 +0100157#else
Victor Stinnerccd57152012-02-08 14:31:50 +0100158 if (pyclock(&ts) == -1)
159 return NULL;
Victor Stinner8b302012012-02-07 23:29:46 +0100160#endif
Victor Stinnerccd57152012-02-08 14:31:50 +0100161 return _PyTime_Convert(&ts, timestamp);
Victor Stinner9122fdd2011-07-04 13:55:40 +0200162}
Victor Stinner9122fdd2011-07-04 13:55:40 +0200163
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000164PyDoc_STRVAR(clock_doc,
Victor Stinnerccd57152012-02-08 14:31:50 +0100165"clock(timestamp=float) -> floating point number\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000166\n\
167Return the CPU time or real time since the start of the process or since\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000168the first call to clock(). This has as much precision as the system\n\
169records.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000170#endif
171
Victor Stinnere0be4232011-10-25 13:06:09 +0200172#ifdef HAVE_CLOCK_GETTIME
173static PyObject *
Victor Stinnerccd57152012-02-08 14:31:50 +0100174time_clock_gettime(PyObject *self, PyObject *args, PyObject *kwargs)
Victor Stinnere0be4232011-10-25 13:06:09 +0200175{
Victor Stinnerccd57152012-02-08 14:31:50 +0100176 static char *kwlist[] = {"clk_id", "timestamp", NULL};
177 PyObject *timestamp = NULL;
Victor Stinnere0be4232011-10-25 13:06:09 +0200178 int ret;
179 clockid_t clk_id;
180 struct timespec tp;
Victor Stinnerccd57152012-02-08 14:31:50 +0100181 _PyTime_t ts;
Victor Stinnere0be4232011-10-25 13:06:09 +0200182
Victor Stinnerccd57152012-02-08 14:31:50 +0100183 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "i|O:clock_gettime", kwlist,
184 &clk_id, &timestamp))
Victor Stinnere0be4232011-10-25 13:06:09 +0200185 return NULL;
186
187 ret = clock_gettime((clockid_t)clk_id, &tp);
Antoine Pitrou2c085602012-01-18 01:41:44 +0100188 if (ret != 0) {
Victor Stinnere0be4232011-10-25 13:06:09 +0200189 PyErr_SetFromErrno(PyExc_IOError);
Antoine Pitrou2c085602012-01-18 01:41:44 +0100190 return NULL;
191 }
Victor Stinnerccd57152012-02-08 14:31:50 +0100192 ts.seconds = tp.tv_sec;
193 ts.numerator = tp.tv_nsec;
194 ts.denominator = 1000000000;
195 return _PyTime_Convert(&ts, timestamp);
Victor Stinnere0be4232011-10-25 13:06:09 +0200196}
197
198PyDoc_STRVAR(clock_gettime_doc,
Victor Stinnerccd57152012-02-08 14:31:50 +0100199"clock_gettime(clk_id, timestamp=float) -> floating point number\n\
Victor Stinnere0be4232011-10-25 13:06:09 +0200200\n\
201Return the time of the specified clock clk_id.");
202#endif
203
204#ifdef HAVE_CLOCK_GETRES
205static PyObject *
Victor Stinnerccd57152012-02-08 14:31:50 +0100206time_clock_getres(PyObject *self, PyObject *args, PyObject *kwargs)
Victor Stinnere0be4232011-10-25 13:06:09 +0200207{
Victor Stinnerccd57152012-02-08 14:31:50 +0100208 static char *kwlist[] = {"clk_id", "timestamp", NULL};
209 PyObject *timestamp = NULL;
Victor Stinnere0be4232011-10-25 13:06:09 +0200210 int ret;
211 clockid_t clk_id;
212 struct timespec tp;
Victor Stinnerccd57152012-02-08 14:31:50 +0100213 _PyTime_t ts;
Victor Stinnere0be4232011-10-25 13:06:09 +0200214
Victor Stinnerccd57152012-02-08 14:31:50 +0100215 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "i|O:clock_getres", kwlist,
216 &clk_id, &timestamp))
Victor Stinnere0be4232011-10-25 13:06:09 +0200217 return NULL;
218
219 ret = clock_getres((clockid_t)clk_id, &tp);
Antoine Pitrou2c085602012-01-18 01:41:44 +0100220 if (ret != 0) {
Victor Stinnere0be4232011-10-25 13:06:09 +0200221 PyErr_SetFromErrno(PyExc_IOError);
Antoine Pitrou2c085602012-01-18 01:41:44 +0100222 return NULL;
223 }
Victor Stinnerccd57152012-02-08 14:31:50 +0100224 ts.seconds = tp.tv_sec;
225 ts.numerator = tp.tv_nsec;
226 ts.denominator = 1000000000;
227 return _PyTime_Convert(&ts, timestamp);
Victor Stinnere0be4232011-10-25 13:06:09 +0200228}
229
230PyDoc_STRVAR(clock_getres_doc,
Victor Stinnerccd57152012-02-08 14:31:50 +0100231"clock_getres(clk_id, timestamp=float) -> floating point number\n\
Victor Stinnere0be4232011-10-25 13:06:09 +0200232\n\
233Return the resolution (precision) of the specified clock clk_id.");
234#endif
235
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000236static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000237time_sleep(PyObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000238{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000239 double secs;
240 if (!PyArg_ParseTuple(args, "d:sleep", &secs))
241 return NULL;
Victor Stinner7f53a502011-07-05 22:00:25 +0200242 if (secs < 0) {
243 PyErr_SetString(PyExc_ValueError,
244 "sleep length must be non-negative");
245 return NULL;
246 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000247 if (floatsleep(secs) != 0)
248 return NULL;
249 Py_INCREF(Py_None);
250 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000251}
252
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000253PyDoc_STRVAR(sleep_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000254"sleep(seconds)\n\
255\n\
256Delay execution for a given number of seconds. The argument may be\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000257a floating point number for subsecond precision.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000258
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000259static PyStructSequence_Field struct_time_type_fields[] = {
Alexander Belopolsky69f3fd02010-06-05 15:04:51 +0000260 {"tm_year", "year, for example, 1993"},
261 {"tm_mon", "month of year, range [1, 12]"},
262 {"tm_mday", "day of month, range [1, 31]"},
263 {"tm_hour", "hours, range [0, 23]"},
264 {"tm_min", "minutes, range [0, 59]"},
265 {"tm_sec", "seconds, range [0, 61])"},
266 {"tm_wday", "day of week, range [0, 6], Monday is 0"},
267 {"tm_yday", "day of year, range [1, 366]"},
268 {"tm_isdst", "1 if summer time is in effect, 0 if not, and -1 if unknown"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000269 {0}
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000270};
271
272static PyStructSequence_Desc struct_time_type_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000273 "time.struct_time",
Alexander Belopolsky69f3fd02010-06-05 15:04:51 +0000274 "The time value as returned by gmtime(), localtime(), and strptime(), and\n"
275 " accepted by asctime(), mktime() and strftime(). May be considered as a\n"
276 " sequence of 9 integers.\n\n"
277 " Note that several fields' values are not the same as those defined by\n"
278 " the C language standard for struct tm. For example, the value of the\n"
279 " field tm_year is the actual year, not year - 1900. See individual\n"
280 " fields' descriptions for details.",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000281 struct_time_type_fields,
282 9,
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000283};
Tim Peters9ad4b682002-02-13 05:14:18 +0000284
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000285static int initialized;
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000286static PyTypeObject StructTimeType;
287
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000288static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000289tmtotuple(struct tm *p)
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000290{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000291 PyObject *v = PyStructSequence_New(&StructTimeType);
292 if (v == NULL)
293 return NULL;
Tim Peters9ad4b682002-02-13 05:14:18 +0000294
Christian Heimes217cfd12007-12-02 14:31:20 +0000295#define SET(i,val) PyStructSequence_SET_ITEM(v, i, PyLong_FromLong((long) val))
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000297 SET(0, p->tm_year + 1900);
298 SET(1, p->tm_mon + 1); /* Want January == 1 */
299 SET(2, p->tm_mday);
300 SET(3, p->tm_hour);
301 SET(4, p->tm_min);
302 SET(5, p->tm_sec);
303 SET(6, (p->tm_wday + 6) % 7); /* Want Monday == 0 */
304 SET(7, p->tm_yday + 1); /* Want January, 1 == 1 */
305 SET(8, p->tm_isdst);
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000306#undef SET
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000307 if (PyErr_Occurred()) {
308 Py_XDECREF(v);
309 return NULL;
310 }
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000311
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000312 return v;
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000313}
314
Fred Drakef901abd2004-08-03 17:58:55 +0000315/* Parse arg tuple that can contain an optional float-or-None value;
316 format needs to be "|O:name".
317 Returns non-zero on success (parallels PyArg_ParseTuple).
318*/
319static int
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100320parse_time_t_args(PyObject *args, char *format, time_t *pwhen)
Fred Drakef901abd2004-08-03 17:58:55 +0000321{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000322 PyObject *ot = NULL;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100323 time_t whent;
Fred Drakef901abd2004-08-03 17:58:55 +0000324
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000325 if (!PyArg_ParseTuple(args, format, &ot))
326 return 0;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100327 if (ot == NULL || ot == Py_None) {
328 whent = time(NULL);
329 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000330 else {
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100331 double d = PyFloat_AsDouble(ot);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000332 if (PyErr_Occurred())
333 return 0;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100334 whent = _PyTime_DoubleToTimet(d);
335 if (whent == (time_t)-1 && PyErr_Occurred())
336 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000337 }
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100338 *pwhen = whent;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000339 return 1;
Fred Drakef901abd2004-08-03 17:58:55 +0000340}
341
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000342static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000343time_gmtime(PyObject *self, PyObject *args)
Guido van Rossum234f9421993-06-17 12:35:49 +0000344{
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100345 time_t when;
346 struct tm buf, *local;
347
348 if (!parse_time_t_args(args, "|O:gmtime", &when))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000349 return NULL;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100350
351 errno = 0;
352 local = gmtime(&when);
353 if (local == NULL) {
354#ifdef EINVAL
355 if (errno == 0)
356 errno = EINVAL;
357#endif
358 return PyErr_SetFromErrno(PyExc_OSError);
359 }
360 buf = *local;
361 return tmtotuple(&buf);
Guido van Rossum234f9421993-06-17 12:35:49 +0000362}
363
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000364PyDoc_STRVAR(gmtime_doc,
Christian Heimes9a371592007-12-28 14:08:13 +0000365"gmtime([seconds]) -> (tm_year, tm_mon, tm_mday, tm_hour, tm_min,\n\
Fred Drake193a3f62002-03-12 21:38:49 +0000366 tm_sec, tm_wday, tm_yday, tm_isdst)\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000367\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000368Convert seconds since the Epoch to a time tuple expressing UTC (a.k.a.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000369GMT). When 'seconds' is not passed in, convert the current time instead.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000370
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100371static int
372pylocaltime(time_t *timep, struct tm *result)
373{
374 struct tm *local;
375
376 assert (timep != NULL);
377 local = localtime(timep);
378 if (local == NULL) {
379 /* unconvertible time */
380#ifdef EINVAL
381 if (errno == 0)
382 errno = EINVAL;
383#endif
384 PyErr_SetFromErrno(PyExc_OSError);
385 return -1;
386 }
387 *result = *local;
388 return 0;
389}
390
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000391static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000392time_localtime(PyObject *self, PyObject *args)
Guido van Rossum234f9421993-06-17 12:35:49 +0000393{
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100394 time_t when;
395 struct tm buf;
396
397 if (!parse_time_t_args(args, "|O:localtime", &when))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000398 return NULL;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100399 if (pylocaltime(&when, &buf) == 1)
400 return NULL;
401 return tmtotuple(&buf);
Guido van Rossum234f9421993-06-17 12:35:49 +0000402}
403
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000404PyDoc_STRVAR(localtime_doc,
Christian Heimes9a371592007-12-28 14:08:13 +0000405"localtime([seconds]) -> (tm_year,tm_mon,tm_mday,tm_hour,tm_min,\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000406 tm_sec,tm_wday,tm_yday,tm_isdst)\n\
Martin v. Löwisb3cfc1d2001-12-02 12:27:43 +0000407\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000408Convert seconds since the Epoch to a time tuple expressing local time.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000409When 'seconds' is not passed in, convert the current time instead.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000410
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000411/* Convert 9-item tuple to tm structure. Return 1 on success, set
412 * an exception and return 0 on error.
413 */
Guido van Rossum9e90a671993-06-24 11:10:19 +0000414static int
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000415gettmarg(PyObject *args, struct tm *p)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000416{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000417 int y;
Guido van Rossumcfbaecc1998-08-25 14:51:12 +0000418
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000419 memset((void *) p, '\0', sizeof(struct tm));
Guido van Rossumb9081262007-08-25 03:14:09 +0000420
Alexander Belopolsky610e5442011-01-06 21:57:06 +0000421 if (!PyTuple_Check(args)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000422 PyErr_SetString(PyExc_TypeError,
423 "Tuple or struct_time argument required");
424 return 0;
425 }
Skip Montanaro41cfce92007-08-24 21:11:00 +0000426
Alexander Belopolsky610e5442011-01-06 21:57:06 +0000427 if (!PyArg_ParseTuple(args, "iiiiiiiii",
428 &y, &p->tm_mon, &p->tm_mday,
429 &p->tm_hour, &p->tm_min, &p->tm_sec,
430 &p->tm_wday, &p->tm_yday, &p->tm_isdst))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000431 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000432 p->tm_year = y - 1900;
433 p->tm_mon--;
434 p->tm_wday = (p->tm_wday + 1) % 7;
435 p->tm_yday--;
436 return 1;
Guido van Rossum9e90a671993-06-24 11:10:19 +0000437}
438
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000439/* Check values of the struct tm fields before it is passed to strftime() and
440 * asctime(). Return 1 if all values are valid, otherwise set an exception
441 * and returns 0.
442 */
Victor Stinneref128102010-10-07 01:00:52 +0000443static int
444checktm(struct tm* buf)
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000445{
Victor Stinneref128102010-10-07 01:00:52 +0000446 /* Checks added to make sure strftime() and asctime() does not crash Python by
447 indexing blindly into some array for a textual representation
448 by some bad index (fixes bug #897625 and #6608).
449
450 Also support values of zero from Python code for arguments in which
451 that is out of range by forcing that value to the lowest value that
452 is valid (fixed bug #1520914).
453
454 Valid ranges based on what is allowed in struct tm:
455
456 - tm_year: [0, max(int)] (1)
457 - tm_mon: [0, 11] (2)
458 - tm_mday: [1, 31]
459 - tm_hour: [0, 23]
460 - tm_min: [0, 59]
461 - tm_sec: [0, 60]
462 - tm_wday: [0, 6] (1)
463 - tm_yday: [0, 365] (2)
464 - tm_isdst: [-max(int), max(int)]
465
466 (1) gettmarg() handles bounds-checking.
467 (2) Python's acceptable range is one greater than the range in C,
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000468 thus need to check against automatic decrement by gettmarg().
469 */
470 if (buf->tm_mon == -1)
471 buf->tm_mon = 0;
472 else if (buf->tm_mon < 0 || buf->tm_mon > 11) {
473 PyErr_SetString(PyExc_ValueError, "month out of range");
474 return 0;
475 }
476 if (buf->tm_mday == 0)
477 buf->tm_mday = 1;
478 else if (buf->tm_mday < 0 || buf->tm_mday > 31) {
479 PyErr_SetString(PyExc_ValueError, "day of month out of range");
480 return 0;
481 }
482 if (buf->tm_hour < 0 || buf->tm_hour > 23) {
483 PyErr_SetString(PyExc_ValueError, "hour out of range");
484 return 0;
485 }
486 if (buf->tm_min < 0 || buf->tm_min > 59) {
487 PyErr_SetString(PyExc_ValueError, "minute out of range");
488 return 0;
489 }
490 if (buf->tm_sec < 0 || buf->tm_sec > 61) {
491 PyErr_SetString(PyExc_ValueError, "seconds out of range");
492 return 0;
493 }
494 /* tm_wday does not need checking of its upper-bound since taking
495 ``% 7`` in gettmarg() automatically restricts the range. */
496 if (buf->tm_wday < 0) {
497 PyErr_SetString(PyExc_ValueError, "day of week out of range");
498 return 0;
499 }
500 if (buf->tm_yday == -1)
501 buf->tm_yday = 0;
502 else if (buf->tm_yday < 0 || buf->tm_yday > 365) {
503 PyErr_SetString(PyExc_ValueError, "day of year out of range");
504 return 0;
505 }
506 return 1;
507}
508
Victor Stinnerc1f32ca2011-10-14 02:36:13 +0200509#ifdef MS_WINDOWS
510 /* wcsftime() doesn't format correctly time zones, see issue #10653 */
511# undef HAVE_WCSFTIME
512#endif
513
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000514#ifdef HAVE_STRFTIME
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000515#ifdef HAVE_WCSFTIME
516#define time_char wchar_t
517#define format_time wcsftime
518#define time_strlen wcslen
519#else
520#define time_char char
521#define format_time strftime
522#define time_strlen strlen
523#endif
524
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000525static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000526time_strftime(PyObject *self, PyObject *args)
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000527{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000528 PyObject *tup = NULL;
529 struct tm buf;
530 const time_char *fmt;
Victor Stinnerb2904782010-09-29 10:34:19 +0000531#ifdef HAVE_WCSFTIME
532 wchar_t *format;
533#else
534 PyObject *format;
535#endif
Victor Stinneref128102010-10-07 01:00:52 +0000536 PyObject *format_arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000537 size_t fmtlen, buflen;
Victor Stinnerb2904782010-09-29 10:34:19 +0000538 time_char *outbuf = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000539 size_t i;
Victor Stinnerb2904782010-09-29 10:34:19 +0000540 PyObject *ret = NULL;
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000541
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000542 memset((void *) &buf, '\0', sizeof(buf));
Guido van Rossum1f41f841998-04-27 19:04:26 +0000543
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000544 /* Will always expect a unicode string to be passed as format.
545 Given that there's no str type anymore in py3k this seems safe.
546 */
Victor Stinneref128102010-10-07 01:00:52 +0000547 if (!PyArg_ParseTuple(args, "U|O:strftime", &format_arg, &tup))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000548 return NULL;
Thomas Woutersfe385252001-01-19 23:16:56 +0000549
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000550 if (tup == NULL) {
551 time_t tt = time(NULL);
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100552 if (pylocaltime(&tt, &buf) == -1)
553 return NULL;
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000554 }
555 else if (!gettmarg(tup, &buf) || !checktm(&buf))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000556 return NULL;
Guido van Rossum10b164a2001-09-25 13:59:01 +0000557
Victor Stinner06ec45e2011-01-08 03:35:36 +0000558#if defined(_MSC_VER) || defined(sun)
Victor Stinner73ea29c2011-01-08 01:56:31 +0000559 if (buf.tm_year + 1900 < 1 || 9999 < buf.tm_year + 1900) {
Victor Stinner6f0e4f92011-03-21 02:14:53 +0100560 PyErr_SetString(PyExc_ValueError,
561 "strftime() requires year in [1; 9999]");
Alexander Belopolsky0dd06f42011-01-08 01:23:02 +0000562 return NULL;
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000563 }
Victor Stinner73ea29c2011-01-08 01:56:31 +0000564#endif
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000565
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000566 /* Normalize tm_isdst just in case someone foolishly implements %Z
567 based on the assumption that tm_isdst falls within the range of
568 [-1, 1] */
569 if (buf.tm_isdst < -1)
570 buf.tm_isdst = -1;
571 else if (buf.tm_isdst > 1)
572 buf.tm_isdst = 1;
Brett Cannond1080a32004-03-02 04:38:10 +0000573
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000574#ifdef HAVE_WCSFTIME
Victor Stinnerbeb4135b2010-10-07 01:02:42 +0000575 format = PyUnicode_AsWideCharString(format_arg, NULL);
Victor Stinnerb2904782010-09-29 10:34:19 +0000576 if (format == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000577 return NULL;
Victor Stinnerb2904782010-09-29 10:34:19 +0000578 fmt = format;
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000579#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000580 /* Convert the unicode string to an ascii one */
Victor Stinner1b579672011-12-17 05:47:23 +0100581 format = PyUnicode_EncodeLocale(format_arg, "surrogateescape");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000582 if (format == NULL)
583 return NULL;
584 fmt = PyBytes_AS_STRING(format);
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000585#endif
Amaury Forgeot d'Arcb5be6d42009-03-02 23:52:57 +0000586
Victor Stinner5a3ff792011-10-16 19:08:23 +0200587#if defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000588 /* check that the format string contains only valid directives */
Victor Stinner5a3ff792011-10-16 19:08:23 +0200589 for(outbuf = strchr(fmt, '%');
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000590 outbuf != NULL;
Victor Stinner5a3ff792011-10-16 19:08:23 +0200591 outbuf = strchr(outbuf+2, '%'))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000592 {
593 if (outbuf[1]=='#')
594 ++outbuf; /* not documented by python, */
595 if (outbuf[1]=='\0' ||
Victor Stinner5a3ff792011-10-16 19:08:23 +0200596 !strchr("aAbBcdHIjmMpSUwWxXyYzZ%", outbuf[1]))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000597 {
598 PyErr_SetString(PyExc_ValueError, "Invalid format string");
599 return 0;
600 }
601 }
Amaury Forgeot d'Arcb5be6d42009-03-02 23:52:57 +0000602#endif
603
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000604 fmtlen = time_strlen(fmt);
Guido van Rossumc222ec21999-02-23 00:00:10 +0000605
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000606 /* I hate these functions that presume you know how big the output
607 * will be ahead of time...
608 */
609 for (i = 1024; ; i += i) {
Victor Stinner136ea492011-12-17 22:37:18 +0100610#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100611 int err;
Victor Stinner136ea492011-12-17 22:37:18 +0100612#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000613 outbuf = (time_char *)PyMem_Malloc(i*sizeof(time_char));
614 if (outbuf == NULL) {
Victor Stinnerb2904782010-09-29 10:34:19 +0000615 PyErr_NoMemory();
616 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000617 }
618 buflen = format_time(outbuf, i, fmt, &buf);
Victor Stinner136ea492011-12-17 22:37:18 +0100619#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100620 err = errno;
Victor Stinner136ea492011-12-17 22:37:18 +0100621#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000622 if (buflen > 0 || i >= 256 * fmtlen) {
623 /* If the buffer is 256 times as long as the format,
624 it's probably not failing for lack of room!
625 More likely, the format yields an empty result,
626 e.g. an empty format, or %Z when the timezone
627 is unknown. */
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000628#ifdef HAVE_WCSFTIME
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000629 ret = PyUnicode_FromWideChar(outbuf, buflen);
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000630#else
Victor Stinner1b579672011-12-17 05:47:23 +0100631 ret = PyUnicode_DecodeLocaleAndSize(outbuf, buflen,
632 "surrogateescape");
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000633#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000634 PyMem_Free(outbuf);
Victor Stinnerb2904782010-09-29 10:34:19 +0000635 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000636 }
637 PyMem_Free(outbuf);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000638#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000639 /* VisualStudio .NET 2005 does this properly */
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100640 if (buflen == 0 && err == EINVAL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000641 PyErr_SetString(PyExc_ValueError, "Invalid format string");
Victor Stinnerb2904782010-09-29 10:34:19 +0000642 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000643 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000644#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000645 }
Victor Stinnerb2904782010-09-29 10:34:19 +0000646#ifdef HAVE_WCSFTIME
647 PyMem_Free(format);
648#else
649 Py_DECREF(format);
650#endif
651 return ret;
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000652}
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000653
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000654#undef time_char
655#undef format_time
656
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000657PyDoc_STRVAR(strftime_doc,
Thomas Woutersfe385252001-01-19 23:16:56 +0000658"strftime(format[, tuple]) -> string\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000659\n\
660Convert a time tuple to a string according to a format specification.\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000661See the library reference manual for formatting codes. When the time tuple\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000662is not present, current time as returned by localtime() is used.");
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000663#endif /* HAVE_STRFTIME */
664
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000665static PyObject *
666time_strptime(PyObject *self, PyObject *args)
667{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000668 PyObject *strptime_module = PyImport_ImportModuleNoBlock("_strptime");
669 PyObject *strptime_result;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200670 _Py_IDENTIFIER(_strptime_time);
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000671
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000672 if (!strptime_module)
673 return NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200674 strptime_result = _PyObject_CallMethodId(strptime_module,
675 &PyId__strptime_time, "O", args);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000676 Py_DECREF(strptime_module);
677 return strptime_result;
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000678}
679
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000680
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000681PyDoc_STRVAR(strptime_doc,
Brett Cannon20def8b2003-07-01 05:16:08 +0000682"strptime(string, format) -> struct_time\n\
Martin v. Löwisb3cfc1d2001-12-02 12:27:43 +0000683\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000684Parse a string to a time tuple according to a format specification.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000685See the library reference manual for formatting codes (same as strftime()).");
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000686
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000687static PyObject *
688_asctime(struct tm *timeptr)
689{
690 /* Inspired by Open Group reference implementation available at
691 * http://pubs.opengroup.org/onlinepubs/009695399/functions/asctime.html */
Victor Stinner499dfcf2011-03-21 13:26:24 +0100692 static char wday_name[7][4] = {
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000693 "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
694 };
Victor Stinner499dfcf2011-03-21 13:26:24 +0100695 static char mon_name[12][4] = {
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000696 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
697 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
698 };
Victor Stinner499dfcf2011-03-21 13:26:24 +0100699 return PyUnicode_FromFormat(
700 "%s %s%3d %.2d:%.2d:%.2d %d",
701 wday_name[timeptr->tm_wday],
702 mon_name[timeptr->tm_mon],
703 timeptr->tm_mday, timeptr->tm_hour,
704 timeptr->tm_min, timeptr->tm_sec,
705 1900 + timeptr->tm_year);
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000706}
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000707
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000708static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000709time_asctime(PyObject *self, PyObject *args)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000710{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000711 PyObject *tup = NULL;
712 struct tm buf;
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000713
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000714 if (!PyArg_UnpackTuple(args, "asctime", 0, 1, &tup))
715 return NULL;
716 if (tup == NULL) {
717 time_t tt = time(NULL);
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100718 if (pylocaltime(&tt, &buf) == -1)
719 return NULL;
720
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000721 } else if (!gettmarg(tup, &buf) || !checktm(&buf))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000722 return NULL;
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000723 return _asctime(&buf);
Guido van Rossum9e90a671993-06-24 11:10:19 +0000724}
725
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000726PyDoc_STRVAR(asctime_doc,
Thomas Woutersfe385252001-01-19 23:16:56 +0000727"asctime([tuple]) -> string\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000728\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000729Convert a time tuple to a string, e.g. 'Sat Jun 06 16:26:11 1998'.\n\
730When the time tuple is not present, current time as returned by localtime()\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000731is used.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000732
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000733static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000734time_ctime(PyObject *self, PyObject *args)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000735{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000736 time_t tt;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100737 struct tm buf;
738 if (!parse_time_t_args(args, "|O:ctime", &tt))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000739 return NULL;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100740 if (pylocaltime(&tt, &buf) == -1)
Alexander Belopolsky5da468f2011-01-04 17:15:52 +0000741 return NULL;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100742 return _asctime(&buf);
Guido van Rossum9e90a671993-06-24 11:10:19 +0000743}
744
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000745PyDoc_STRVAR(ctime_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000746"ctime(seconds) -> string\n\
747\n\
748Convert a time in seconds since the Epoch to a string in local time.\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000749This is equivalent to asctime(localtime(seconds)). When the time tuple is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000750not present, current time as returned by localtime() is used.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000751
Guido van Rossum60cd8131998-03-06 17:16:21 +0000752#ifdef HAVE_MKTIME
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000753static PyObject *
Victor Stinnerccd57152012-02-08 14:31:50 +0100754time_mktime(PyObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossum234f9421993-06-17 12:35:49 +0000755{
Victor Stinnerccd57152012-02-08 14:31:50 +0100756 static char *kwlist[] = {"t", "timestamp", NULL};
757 PyObject *timestamp = NULL;
758 PyObject *tup;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000759 struct tm buf;
760 time_t tt;
Victor Stinnerccd57152012-02-08 14:31:50 +0100761 _PyTime_t ts;
762
763 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|O:mktime", kwlist,
764 &tup, &timestamp))
765 return NULL;
766
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000767 if (!gettmarg(tup, &buf))
768 return NULL;
Alexander Belopolskyb7d40d12011-01-11 01:21:25 +0000769 buf.tm_wday = -1; /* sentinel; original value ignored */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000770 tt = mktime(&buf);
Alexander Belopolskyb7d40d12011-01-11 01:21:25 +0000771 /* Return value of -1 does not necessarily mean an error, but tm_wday
Ezio Melotti13925002011-03-16 11:05:33 +0200772 * cannot remain set to -1 if mktime succeeded. */
Alexander Belopolskyb7d40d12011-01-11 01:21:25 +0000773 if (tt == (time_t)(-1) && buf.tm_wday == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000774 PyErr_SetString(PyExc_OverflowError,
775 "mktime argument out of range");
776 return NULL;
777 }
Victor Stinnerccd57152012-02-08 14:31:50 +0100778 ts.seconds = tt;
779 ts.numerator = 0;
780 ts.denominator = 1;
781 return _PyTime_Convert(&ts, timestamp);
Guido van Rossum234f9421993-06-17 12:35:49 +0000782}
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000783
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000784PyDoc_STRVAR(mktime_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000785"mktime(tuple) -> floating point number\n\
786\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000787Convert a time tuple in local time to seconds since the Epoch.");
Guido van Rossum60cd8131998-03-06 17:16:21 +0000788#endif /* HAVE_MKTIME */
Guido van Rossum234f9421993-06-17 12:35:49 +0000789
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000790#ifdef HAVE_WORKING_TZSET
Martin v. Löwis1a214512008-06-11 05:26:20 +0000791static void PyInit_timezone(PyObject *module);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000792
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000793static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000794time_tzset(PyObject *self, PyObject *unused)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000795{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000796 PyObject* m;
Fred Drake9bb74322002-04-01 14:49:59 +0000797
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000798 m = PyImport_ImportModuleNoBlock("time");
799 if (m == NULL) {
800 return NULL;
801 }
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000802
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000803 tzset();
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000804
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000805 /* Reset timezone, altzone, daylight and tzname */
806 PyInit_timezone(m);
807 Py_DECREF(m);
Tim Peters1b6f7a92004-06-20 02:50:16 +0000808
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000809 Py_INCREF(Py_None);
810 return Py_None;
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000811}
812
813PyDoc_STRVAR(tzset_doc,
R. David Murray4d55bf92010-12-14 00:55:46 +0000814"tzset()\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000815\n\
816Initialize, or reinitialize, the local timezone to the value stored in\n\
817os.environ['TZ']. The TZ environment variable should be specified in\n\
Neal Norwitzdc8e1942004-07-20 22:34:37 +0000818standard Unix timezone format as documented in the tzset man page\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000819(eg. 'US/Eastern', 'Europe/Amsterdam'). Unknown timezones will silently\n\
820fall back to UTC. If the TZ environment variable is not set, the local\n\
821timezone is set to the systems best guess of wallclock time.\n\
822Changing the TZ environment variable without calling tzset *may* change\n\
823the local timezone used by methods such as localtime, but this behaviour\n\
824should not be relied on.");
825#endif /* HAVE_WORKING_TZSET */
826
Victor Stinnerccd57152012-02-08 14:31:50 +0100827static int
828pywallclock(_PyTime_t *ts)
Victor Stinnerb94b2662012-01-18 01:50:21 +0100829{
830#if defined(MS_WINDOWS) && !defined(__BORLANDC__)
Victor Stinnerccd57152012-02-08 14:31:50 +0100831 return win32_clock(ts, 1);
832#else
833
834#if defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_MONOTONIC)
Victor Stinnerb94b2662012-01-18 01:50:21 +0100835 static int clk_index = 0;
836 clockid_t clk_ids[] = {
837#ifdef CLOCK_MONOTONIC_RAW
838 CLOCK_MONOTONIC_RAW,
839#endif
840 CLOCK_MONOTONIC
841#ifdef CLOCK_REALTIME
842 /* On Linux, CLOCK_REALTIME uses the same clock than gettimeofday(),
843 but clock_gettime() has a nanosecond resolution. */
844 , CLOCK_REALTIME
845#endif
846 };
847 int ret;
848 struct timespec tp;
849
850 while (0 <= clk_index) {
851 clockid_t clk_id = clk_ids[clk_index];
852 ret = clock_gettime(clk_id, &tp);
853 if (ret == 0)
Victor Stinnerccd57152012-02-08 14:31:50 +0100854 {
855 ts->seconds = tp.tv_sec;
856 ts->numerator = tp.tv_nsec;
857 ts->denominator = 1000000000;
858 return 0;
859 }
Victor Stinnerb94b2662012-01-18 01:50:21 +0100860
861 clk_index++;
862 if (Py_ARRAY_LENGTH(clk_ids) <= clk_index)
863 clk_index = -1;
864 }
Victor Stinnerccd57152012-02-08 14:31:50 +0100865#endif /* defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_MONOTONIC) */
866
867 _PyTime_get(ts);
868 return 0;
Victor Stinnerb94b2662012-01-18 01:50:21 +0100869#endif
870}
871
Victor Stinnerccd57152012-02-08 14:31:50 +0100872static PyObject *
873time_wallclock(PyObject *self, PyObject *args, PyObject *kwargs)
874{
875 static char *kwlist[] = {"timestamp", NULL};
876 PyObject *timestamp = NULL;
877 _PyTime_t ts;
878
879 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|O:wallclock", kwlist,
880 &timestamp))
881 return NULL;
882 if (pywallclock(&ts))
883 return NULL;
884 return _PyTime_Convert(&ts, timestamp);
885}
886
Victor Stinnerb94b2662012-01-18 01:50:21 +0100887PyDoc_STRVAR(wallclock_doc,
Victor Stinnerccd57152012-02-08 14:31:50 +0100888"wallclock(timestamp=float)\n\
Victor Stinnerb94b2662012-01-18 01:50:21 +0100889\n\
890Return the current time in fractions of a second to the system's best\n\
891ability. Use this when the most accurate representation of wall-clock is\n\
Victor Stinner855889b2012-01-18 01:57:19 +0100892required, i.e. when \"processor time\" is inappropriate. The reference point\n\
Victor Stinnerb94b2662012-01-18 01:50:21 +0100893of the returned value is undefined so only the difference of consecutive\n\
894calls is valid.");
895
Victor Stinner8b302012012-02-07 23:29:46 +0100896#if (defined(MS_WINDOWS) && !defined(__BORLANDC__)) \
897 || (defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_MONOTONIC))
898# define HAVE_PYTIME_MONOTONIC
899#endif
900
901#ifdef HAVE_PYTIME_MONOTONIC
902static PyObject *
Victor Stinnerccd57152012-02-08 14:31:50 +0100903time_monotonic(PyObject *self, PyObject *args, PyObject *kwargs)
Victor Stinner8b302012012-02-07 23:29:46 +0100904{
Victor Stinnerccd57152012-02-08 14:31:50 +0100905 static char *kwlist[] = {"timestamp", NULL};
906 PyObject *timestamp = NULL;
907#if defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_MONOTONIC)
Victor Stinner8b302012012-02-07 23:29:46 +0100908 static int clk_index = 0;
909 clockid_t clk_ids[] = {
910#ifdef CLOCK_MONOTONIC_RAW
911 CLOCK_MONOTONIC_RAW,
912#endif
913 CLOCK_MONOTONIC
914 };
915 int ret;
916 struct timespec tp;
Victor Stinnerccd57152012-02-08 14:31:50 +0100917#endif
918 _PyTime_t ts;
Victor Stinner8b302012012-02-07 23:29:46 +0100919
Victor Stinnerccd57152012-02-08 14:31:50 +0100920 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|O:monotonic", kwlist,
921 &timestamp))
922 return NULL;
923
924#if defined(MS_WINDOWS) && !defined(__BORLANDC__)
925 if (win32_clock(&ts, 0) == -1)
926 return NULL;
927 return _PyTime_Convert(&ts, timestamp);
928#else
Victor Stinner8b302012012-02-07 23:29:46 +0100929 while (0 <= clk_index) {
930 clockid_t clk_id = clk_ids[clk_index];
931 ret = clock_gettime(clk_id, &tp);
932 if (ret == 0)
Victor Stinnerccd57152012-02-08 14:31:50 +0100933 {
934 ts.seconds = tp.tv_sec;
935 ts.numerator = tp.tv_nsec;
936 ts.denominator = 1000000000;
937 return _PyTime_Convert(&ts, timestamp);
938 }
Victor Stinner8b302012012-02-07 23:29:46 +0100939
940 clk_index++;
941 if (Py_ARRAY_LENGTH(clk_ids) <= clk_index)
942 clk_index = -1;
943 }
944 PyErr_SetFromErrno(PyExc_OSError);
945 return NULL;
946#endif
947}
948
949PyDoc_STRVAR(monotonic_doc,
950"monotonic() -> float\n\
951\n\
952Monotonic clock. The reference point of the returned value is undefined so\n\
953only the difference of consecutive calls is valid.");
954#endif
955
Martin v. Löwisd218dc12008-04-07 03:17:54 +0000956static void
Martin v. Löwis1a214512008-06-11 05:26:20 +0000957PyInit_timezone(PyObject *m) {
958 /* This code moved from PyInit_time wholesale to allow calling it from
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000959 time_tzset. In the future, some parts of it can be moved back
960 (for platforms that don't HAVE_WORKING_TZSET, when we know what they
961 are), and the extraneous calls to tzset(3) should be removed.
962 I haven't done this yet, as I don't want to change this code as
963 little as possible when introducing the time.tzset and time.tzsetwall
964 methods. This should simply be a method of doing the following once,
965 at the top of this function and removing the call to tzset() from
966 time_tzset():
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000967
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000968 #ifdef HAVE_TZSET
969 tzset()
970 #endif
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000971
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000972 And I'm lazy and hate C so nyer.
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000973 */
Guido van Rossum10b164a2001-09-25 13:59:01 +0000974#if defined(HAVE_TZNAME) && !defined(__GLIBC__) && !defined(__CYGWIN__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000975 PyObject *otz0, *otz1;
976 tzset();
Guido van Rossum26452411998-09-28 22:07:11 +0000977#ifdef PYOS_OS2
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000978 PyModule_AddIntConstant(m, "timezone", _timezone);
Guido van Rossum26452411998-09-28 22:07:11 +0000979#else /* !PYOS_OS2 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000980 PyModule_AddIntConstant(m, "timezone", timezone);
Guido van Rossum26452411998-09-28 22:07:11 +0000981#endif /* PYOS_OS2 */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000982#ifdef HAVE_ALTZONE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000983 PyModule_AddIntConstant(m, "altzone", altzone);
Guido van Rossumb6775db1994-08-01 11:34:53 +0000984#else
Guido van Rossum26452411998-09-28 22:07:11 +0000985#ifdef PYOS_OS2
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000986 PyModule_AddIntConstant(m, "altzone", _timezone-3600);
Guido van Rossum26452411998-09-28 22:07:11 +0000987#else /* !PYOS_OS2 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000988 PyModule_AddIntConstant(m, "altzone", timezone-3600);
Guido van Rossum26452411998-09-28 22:07:11 +0000989#endif /* PYOS_OS2 */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000990#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000991 PyModule_AddIntConstant(m, "daylight", daylight);
Victor Stinner1b579672011-12-17 05:47:23 +0100992 otz0 = PyUnicode_DecodeLocale(tzname[0], "surrogateescape");
993 otz1 = PyUnicode_DecodeLocale(tzname[1], "surrogateescape");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000994 PyModule_AddObject(m, "tzname", Py_BuildValue("(NN)", otz0, otz1));
Guido van Rossum10b164a2001-09-25 13:59:01 +0000995#else /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/
Martin v. Löwis60a5d722002-10-16 20:28:25 +0000996#ifdef HAVE_STRUCT_TM_TM_ZONE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000997 {
Guido van Rossum234f9421993-06-17 12:35:49 +0000998#define YEAR ((time_t)((365 * 24 + 6) * 3600))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000999 time_t t;
1000 struct tm *p;
1001 long janzone, julyzone;
1002 char janname[10], julyname[10];
1003 t = (time((time_t *)0) / YEAR) * YEAR;
1004 p = localtime(&t);
1005 janzone = -p->tm_gmtoff;
1006 strncpy(janname, p->tm_zone ? p->tm_zone : " ", 9);
1007 janname[9] = '\0';
1008 t += YEAR/2;
1009 p = localtime(&t);
1010 julyzone = -p->tm_gmtoff;
1011 strncpy(julyname, p->tm_zone ? p->tm_zone : " ", 9);
1012 julyname[9] = '\0';
Guido van Rossum10b164a2001-09-25 13:59:01 +00001013
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001014 if( janzone < julyzone ) {
1015 /* DST is reversed in the southern hemisphere */
1016 PyModule_AddIntConstant(m, "timezone", julyzone);
1017 PyModule_AddIntConstant(m, "altzone", janzone);
1018 PyModule_AddIntConstant(m, "daylight",
1019 janzone != julyzone);
1020 PyModule_AddObject(m, "tzname",
1021 Py_BuildValue("(zz)",
1022 julyname, janname));
1023 } else {
1024 PyModule_AddIntConstant(m, "timezone", janzone);
1025 PyModule_AddIntConstant(m, "altzone", julyzone);
1026 PyModule_AddIntConstant(m, "daylight",
1027 janzone != julyzone);
1028 PyModule_AddObject(m, "tzname",
1029 Py_BuildValue("(zz)",
1030 janname, julyname));
1031 }
1032 }
Guido van Rossume6a4b7b1997-10-08 15:27:56 +00001033#else
Martin v. Löwis60a5d722002-10-16 20:28:25 +00001034#endif /* HAVE_STRUCT_TM_TM_ZONE */
Tim Peters26ae7cd2001-03-20 03:26:49 +00001035#ifdef __CYGWIN__
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001036 tzset();
1037 PyModule_AddIntConstant(m, "timezone", _timezone);
1038 PyModule_AddIntConstant(m, "altzone", _timezone-3600);
1039 PyModule_AddIntConstant(m, "daylight", _daylight);
1040 PyModule_AddObject(m, "tzname",
1041 Py_BuildValue("(zz)", _tzname[0], _tzname[1]));
Tim Peters26ae7cd2001-03-20 03:26:49 +00001042#endif /* __CYGWIN__ */
Guido van Rossum10b164a2001-09-25 13:59:01 +00001043#endif /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/
Victor Stinnere0be4232011-10-25 13:06:09 +02001044
1045#if defined(HAVE_CLOCK_GETTIME) || defined(HAVE_CLOCK_GETRES)
1046#ifdef CLOCK_REALTIME
1047 PyModule_AddIntMacro(m, CLOCK_REALTIME);
1048#endif
1049#ifdef CLOCK_MONOTONIC
1050 PyModule_AddIntMacro(m, CLOCK_MONOTONIC);
1051#endif
1052#ifdef CLOCK_MONOTONIC_RAW
1053 PyModule_AddIntMacro(m, CLOCK_MONOTONIC_RAW);
1054#endif
1055#ifdef CLOCK_PROCESS_CPUTIME_ID
1056 PyModule_AddIntMacro(m, CLOCK_PROCESS_CPUTIME_ID);
1057#endif
1058#ifdef CLOCK_THREAD_CPUTIME_ID
1059 PyModule_AddIntMacro(m, CLOCK_THREAD_CPUTIME_ID);
1060#endif
1061#endif /* HAVE_CLOCK_GETTIME */
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001062}
1063
1064
1065static PyMethodDef time_methods[] = {
Victor Stinnerccd57152012-02-08 14:31:50 +01001066 {"time", (PyCFunction)time_time,
1067 METH_VARARGS | METH_KEYWORDS, time_doc},
1068#ifdef HAVE_PYCLOCK
1069 {"clock", (PyCFunction)time_clock,
1070 METH_VARARGS | METH_KEYWORDS, clock_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001071#endif
Victor Stinnere0be4232011-10-25 13:06:09 +02001072#ifdef HAVE_CLOCK_GETTIME
Victor Stinnerccd57152012-02-08 14:31:50 +01001073 {"clock_gettime", (PyCFunction)time_clock_gettime,
1074 METH_VARARGS | METH_KEYWORDS, clock_gettime_doc},
Victor Stinnere0be4232011-10-25 13:06:09 +02001075#endif
1076#ifdef HAVE_CLOCK_GETRES
Victor Stinnerccd57152012-02-08 14:31:50 +01001077 {"clock_getres", (PyCFunction)time_clock_getres,
1078 METH_VARARGS | METH_KEYWORDS, clock_getres_doc},
Victor Stinnere0be4232011-10-25 13:06:09 +02001079#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001080 {"sleep", time_sleep, METH_VARARGS, sleep_doc},
1081 {"gmtime", time_gmtime, METH_VARARGS, gmtime_doc},
1082 {"localtime", time_localtime, METH_VARARGS, localtime_doc},
1083 {"asctime", time_asctime, METH_VARARGS, asctime_doc},
1084 {"ctime", time_ctime, METH_VARARGS, ctime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001085#ifdef HAVE_MKTIME
Victor Stinnerccd57152012-02-08 14:31:50 +01001086 {"mktime", (PyCFunction)time_mktime,
1087 METH_VARARGS | METH_KEYWORDS, mktime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001088#endif
Victor Stinner8b302012012-02-07 23:29:46 +01001089#ifdef HAVE_PYTIME_MONOTONIC
Victor Stinnerccd57152012-02-08 14:31:50 +01001090 {"monotonic", (PyCFunction)time_monotonic,
1091 METH_VARARGS | METH_KEYWORDS, monotonic_doc},
Victor Stinner8b302012012-02-07 23:29:46 +01001092#endif
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001093#ifdef HAVE_STRFTIME
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001094 {"strftime", time_strftime, METH_VARARGS, strftime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001095#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001096 {"strptime", time_strptime, METH_VARARGS, strptime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001097#ifdef HAVE_WORKING_TZSET
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001098 {"tzset", time_tzset, METH_NOARGS, tzset_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001099#endif
Victor Stinnerccd57152012-02-08 14:31:50 +01001100 {"wallclock", (PyCFunction)time_wallclock,
1101 METH_VARARGS | METH_KEYWORDS, wallclock_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001102 {NULL, NULL} /* sentinel */
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001103};
1104
1105
1106PyDoc_STRVAR(module_doc,
1107"This module provides various functions to manipulate time values.\n\
1108\n\
1109There are two standard representations of time. One is the number\n\
1110of seconds since the Epoch, in UTC (a.k.a. GMT). It may be an integer\n\
1111or a floating point number (to represent fractions of seconds).\n\
1112The Epoch is system-defined; on Unix, it is generally January 1st, 1970.\n\
1113The actual value can be retrieved by calling gmtime(0).\n\
1114\n\
1115The other representation is a tuple of 9 integers giving local time.\n\
1116The tuple items are:\n\
Alexander Belopolsky03163ac2011-05-02 12:20:52 -04001117 year (including century, e.g. 1998)\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001118 month (1-12)\n\
1119 day (1-31)\n\
1120 hours (0-23)\n\
1121 minutes (0-59)\n\
1122 seconds (0-59)\n\
1123 weekday (0-6, Monday is 0)\n\
1124 Julian day (day in the year, 1-366)\n\
1125 DST (Daylight Savings Time) flag (-1, 0 or 1)\n\
1126If the DST flag is 0, the time is given in the regular time zone;\n\
1127if it is 1, the time is given in the DST time zone;\n\
1128if it is -1, mktime() should guess based on the date and time.\n\
1129\n\
1130Variables:\n\
1131\n\
1132timezone -- difference in seconds between UTC and local standard time\n\
1133altzone -- difference in seconds between UTC and local DST time\n\
1134daylight -- whether local time should reflect DST\n\
1135tzname -- tuple of (standard time zone name, DST time zone name)\n\
1136\n\
1137Functions:\n\
1138\n\
1139time() -- return current time in seconds since the Epoch as a float\n\
1140clock() -- return CPU time since process start as a float\n\
1141sleep() -- delay for a number of seconds given as a float\n\
1142gmtime() -- convert seconds since Epoch to UTC tuple\n\
1143localtime() -- convert seconds since Epoch to local time tuple\n\
1144asctime() -- convert time tuple to string\n\
1145ctime() -- convert time in seconds to string\n\
1146mktime() -- convert local time tuple to seconds since Epoch\n\
1147strftime() -- convert time tuple to string according to format specification\n\
1148strptime() -- parse string to time tuple according to format specification\n\
1149tzset() -- change the local timezone");
1150
1151
Martin v. Löwis1a214512008-06-11 05:26:20 +00001152
1153static struct PyModuleDef timemodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001154 PyModuleDef_HEAD_INIT,
1155 "time",
1156 module_doc,
1157 -1,
1158 time_methods,
1159 NULL,
1160 NULL,
1161 NULL,
1162 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00001163};
1164
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001165PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00001166PyInit_time(void)
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001167{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001168 PyObject *m;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001169 m = PyModule_Create(&timemodule);
1170 if (m == NULL)
1171 return NULL;
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001172
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001173 /* Set, or reset, module variables like time.timezone */
1174 PyInit_timezone(m);
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001175
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001176 if (!initialized) {
1177 PyStructSequence_InitType(&StructTimeType,
1178 &struct_time_type_desc);
1179 }
1180 Py_INCREF(&StructTimeType);
1181 PyModule_AddObject(m, "struct_time", (PyObject*) &StructTimeType);
1182 initialized = 1;
1183 return m;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001184}
1185
Guido van Rossumb6775db1994-08-01 11:34:53 +00001186/* Implement floatsleep() for various platforms.
1187 When interrupted (or when another error occurs), return -1 and
1188 set an exception; else return 0. */
1189
1190static int
Guido van Rossuma320fd31995-03-09 12:14:15 +00001191floatsleep(double secs)
Guido van Rossum426035c1991-02-19 12:27:35 +00001192{
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001193/* XXX Should test for MS_WINDOWS first! */
Skip Montanaroeb33e5a2007-08-17 12:57:41 +00001194#if defined(HAVE_SELECT) && !defined(__EMX__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001195 struct timeval t;
1196 double frac;
Victor Stinner48b1ce52011-07-01 13:50:09 +02001197 int err;
1198
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001199 frac = fmod(secs, 1.0);
1200 secs = floor(secs);
1201 t.tv_sec = (long)secs;
1202 t.tv_usec = (long)(frac*1000000.0);
1203 Py_BEGIN_ALLOW_THREADS
Victor Stinner48b1ce52011-07-01 13:50:09 +02001204 err = select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &t);
1205 Py_END_ALLOW_THREADS
1206 if (err != 0) {
Guido van Rossum09cbb011999-11-08 15:32:27 +00001207#ifdef EINTR
Victor Stinner48b1ce52011-07-01 13:50:09 +02001208 if (errno == EINTR) {
1209 if (PyErr_CheckSignals())
1210 return -1;
1211 }
1212 else
Guido van Rossum09cbb011999-11-08 15:32:27 +00001213#endif
Victor Stinner48b1ce52011-07-01 13:50:09 +02001214 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001215 PyErr_SetFromErrno(PyExc_IOError);
1216 return -1;
1217 }
1218 }
Martin v. Löwis02af9642002-01-16 11:04:06 +00001219#elif defined(__WATCOMC__) && !defined(__QNX__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001220 /* XXX Can't interrupt this sleep */
1221 Py_BEGIN_ALLOW_THREADS
1222 delay((int)(secs * 1000 + 0.5)); /* delay() uses milliseconds */
1223 Py_END_ALLOW_THREADS
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001224#elif defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001225 {
1226 double millisecs = secs * 1000.0;
1227 unsigned long ul_millis;
Tim Peters513a1cd2003-01-19 04:54:58 +00001228
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001229 if (millisecs > (double)ULONG_MAX) {
1230 PyErr_SetString(PyExc_OverflowError,
1231 "sleep length is too large");
1232 return -1;
1233 }
1234 Py_BEGIN_ALLOW_THREADS
1235 /* Allow sleep(0) to maintain win32 semantics, and as decreed
1236 * by Guido, only the main thread can be interrupted.
1237 */
1238 ul_millis = (unsigned long)millisecs;
Antoine Pitrou6dd381e2011-11-21 21:26:56 +01001239 if (ul_millis == 0 || !_PyOS_IsMainThread())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001240 Sleep(ul_millis);
1241 else {
1242 DWORD rc;
Antoine Pitrou6dd381e2011-11-21 21:26:56 +01001243 HANDLE hInterruptEvent = _PyOS_SigintEvent();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001244 ResetEvent(hInterruptEvent);
1245 rc = WaitForSingleObject(hInterruptEvent, ul_millis);
1246 if (rc == WAIT_OBJECT_0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001247 Py_BLOCK_THREADS
1248 errno = EINTR;
1249 PyErr_SetFromErrno(PyExc_IOError);
1250 return -1;
1251 }
1252 }
1253 Py_END_ALLOW_THREADS
1254 }
Martin v. Löwis02af9642002-01-16 11:04:06 +00001255#elif defined(PYOS_OS2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001256 /* This Sleep *IS* Interruptable by Exceptions */
1257 Py_BEGIN_ALLOW_THREADS
1258 if (DosSleep(secs * 1000) != NO_ERROR) {
1259 Py_BLOCK_THREADS
1260 PyErr_SetFromErrno(PyExc_IOError);
1261 return -1;
1262 }
1263 Py_END_ALLOW_THREADS
Martin v. Löwis02af9642002-01-16 11:04:06 +00001264#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001265 /* XXX Can't interrupt this sleep */
1266 Py_BEGIN_ALLOW_THREADS
1267 sleep((int)secs);
1268 Py_END_ALLOW_THREADS
Martin v. Löwis02af9642002-01-16 11:04:06 +00001269#endif
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001270
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001271 return 0;
Guido van Rossum80c9d881991-04-16 08:47:51 +00001272}