~ubuntu-branches/ubuntu/maverick/python3.1/maverick

« back to all changes in this revision

Viewing changes to Modules/timemodule.c

  • Committer: Bazaar Package Importer
  • Author(s): Matthias Klose
  • Date: 2009-03-23 00:01:27 UTC
  • Revision ID: james.westby@ubuntu.com-20090323000127-5fstfxju4ufrhthq
Tags: upstream-3.1~a1+20090322
ImportĀ upstreamĀ versionĀ 3.1~a1+20090322

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
 
 
2
/* Time module */
 
3
 
 
4
#include "Python.h"
 
5
#include "structseq.h"
 
6
#include "timefuncs.h"
 
7
 
 
8
#define TZNAME_ENCODING "utf-8"
 
9
 
 
10
#ifdef __APPLE__
 
11
#if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_FTIME)
 
12
  /*
 
13
   * floattime falls back to ftime when getttimeofday fails because the latter
 
14
   * might fail on some platforms. This fallback is unwanted on MacOSX because
 
15
   * that makes it impossible to use a binary build on OSX 10.4 on earlier
 
16
   * releases of the OS. Therefore claim we don't support ftime.
 
17
   */
 
18
# undef HAVE_FTIME
 
19
#endif
 
20
#endif
 
21
 
 
22
#include <ctype.h>
 
23
 
 
24
#ifdef HAVE_SYS_TYPES_H
 
25
#include <sys/types.h>
 
26
#endif /* HAVE_SYS_TYPES_H */
 
27
 
 
28
#ifdef QUICKWIN
 
29
#include <io.h>
 
30
#endif
 
31
 
 
32
#ifdef HAVE_FTIME
 
33
#include <sys/timeb.h>
 
34
#if !defined(MS_WINDOWS) && !defined(PYOS_OS2)
 
35
extern int ftime(struct timeb *);
 
36
#endif /* MS_WINDOWS */
 
37
#endif /* HAVE_FTIME */
 
38
 
 
39
#if defined(__WATCOMC__) && !defined(__QNX__)
 
40
#include <i86.h>
 
41
#else
 
42
#ifdef MS_WINDOWS
 
43
#define WIN32_LEAN_AND_MEAN
 
44
#include <windows.h>
 
45
#include "pythread.h"
 
46
 
 
47
/* helper to allow us to interrupt sleep() on Windows*/
 
48
static HANDLE hInterruptEvent = NULL;
 
49
static BOOL WINAPI PyCtrlHandler(DWORD dwCtrlType)
 
50
{
 
51
        SetEvent(hInterruptEvent);
 
52
        /* allow other default handlers to be called.
 
53
           Default Python handler will setup the
 
54
           KeyboardInterrupt exception.
 
55
        */
 
56
        return FALSE;
 
57
}
 
58
static long main_thread;
 
59
 
 
60
#if defined(__BORLANDC__)
 
61
/* These overrides not needed for Win32 */
 
62
#define timezone _timezone
 
63
#define tzname _tzname
 
64
#define daylight _daylight
 
65
#endif /* __BORLANDC__ */
 
66
#endif /* MS_WINDOWS */
 
67
#endif /* !__WATCOMC__ || __QNX__ */
 
68
 
 
69
#if defined(MS_WINDOWS) && !defined(__BORLANDC__)
 
70
/* Win32 has better clock replacement; we have our own version below. */
 
71
#undef HAVE_CLOCK
 
72
#undef TZNAME_ENCODING
 
73
#define TZNAME_ENCODING "mbcs"
 
74
#endif /* MS_WINDOWS && !defined(__BORLANDC__) */
 
75
 
 
76
#if defined(PYOS_OS2)
 
77
#define INCL_DOS
 
78
#define INCL_ERRORS
 
79
#include <os2.h>
 
80
#endif
 
81
 
 
82
#if defined(PYCC_VACPP)
 
83
#include <sys/time.h>
 
84
#endif
 
85
 
 
86
/* Forward declarations */
 
87
static int floatsleep(double);
 
88
static double floattime(void);
 
89
 
 
90
/* For Y2K check */
 
91
static PyObject *moddict;
 
92
 
 
93
/* Exposed in timefuncs.h. */
 
94
time_t
 
95
_PyTime_DoubleToTimet(double x)
 
96
{
 
97
        time_t result;
 
98
        double diff;
 
99
 
 
100
        result = (time_t)x;
 
101
        /* How much info did we lose?  time_t may be an integral or
 
102
         * floating type, and we don't know which.  If it's integral,
 
103
         * we don't know whether C truncates, rounds, returns the floor,
 
104
         * etc.  If we lost a second or more, the C rounding is
 
105
         * unreasonable, or the input just doesn't fit in a time_t;
 
106
         * call it an error regardless.  Note that the original cast to
 
107
         * time_t can cause a C error too, but nothing we can do to
 
108
         * worm around that.
 
109
         */
 
110
        diff = x - (double)result;
 
111
        if (diff <= -1.0 || diff >= 1.0) {
 
112
                PyErr_SetString(PyExc_ValueError,
 
113
                                "timestamp out of range for platform time_t");
 
114
                result = (time_t)-1;
 
115
        }
 
116
        return result;
 
117
}
 
118
 
 
119
static PyObject *
 
120
time_time(PyObject *self, PyObject *unused)
 
121
{
 
122
        double secs;
 
123
        secs = floattime();
 
124
        if (secs == 0.0) {
 
125
                PyErr_SetFromErrno(PyExc_IOError);
 
126
                return NULL;
 
127
        }
 
128
        return PyFloat_FromDouble(secs);
 
129
}
 
130
 
 
131
PyDoc_STRVAR(time_doc,
 
132
"time() -> floating point number\n\
 
133
\n\
 
134
Return the current time in seconds since the Epoch.\n\
 
135
Fractions of a second may be present if the system clock provides them.");
 
136
 
 
137
#ifdef HAVE_CLOCK
 
138
 
 
139
#ifndef CLOCKS_PER_SEC
 
140
#ifdef CLK_TCK
 
141
#define CLOCKS_PER_SEC CLK_TCK
 
142
#else
 
143
#define CLOCKS_PER_SEC 1000000
 
144
#endif
 
145
#endif
 
146
 
 
147
static PyObject *
 
148
time_clock(PyObject *self, PyObject *unused)
 
149
{
 
150
        return PyFloat_FromDouble(((double)clock()) / CLOCKS_PER_SEC);
 
151
}
 
152
#endif /* HAVE_CLOCK */
 
153
 
 
154
#if defined(MS_WINDOWS) && !defined(__BORLANDC__)
 
155
/* Due to Mark Hammond and Tim Peters */
 
156
static PyObject *
 
157
time_clock(PyObject *self, PyObject *unused)
 
158
{
 
159
        static LARGE_INTEGER ctrStart;
 
160
        static double divisor = 0.0;
 
161
        LARGE_INTEGER now;
 
162
        double diff;
 
163
 
 
164
        if (divisor == 0.0) {
 
165
                LARGE_INTEGER freq;
 
166
                QueryPerformanceCounter(&ctrStart);
 
167
                if (!QueryPerformanceFrequency(&freq) || freq.QuadPart == 0) {
 
168
                        /* Unlikely to happen - this works on all intel
 
169
                           machines at least!  Revert to clock() */
 
170
                        return PyFloat_FromDouble(((double)clock()) /
 
171
                                                  CLOCKS_PER_SEC);
 
172
                }
 
173
                divisor = (double)freq.QuadPart;
 
174
        }
 
175
        QueryPerformanceCounter(&now);
 
176
        diff = (double)(now.QuadPart - ctrStart.QuadPart);
 
177
        return PyFloat_FromDouble(diff / divisor);
 
178
}
 
179
 
 
180
#define HAVE_CLOCK /* So it gets included in the methods */
 
181
#endif /* MS_WINDOWS && !defined(__BORLANDC__) */
 
182
 
 
183
#ifdef HAVE_CLOCK
 
184
PyDoc_STRVAR(clock_doc,
 
185
"clock() -> floating point number\n\
 
186
\n\
 
187
Return the CPU time or real time since the start of the process or since\n\
 
188
the first call to clock().  This has as much precision as the system\n\
 
189
records.");
 
190
#endif
 
191
 
 
192
static PyObject *
 
193
time_sleep(PyObject *self, PyObject *args)
 
194
{
 
195
        double secs;
 
196
        if (!PyArg_ParseTuple(args, "d:sleep", &secs))
 
197
                return NULL;
 
198
        if (floatsleep(secs) != 0)
 
199
                return NULL;
 
200
        Py_INCREF(Py_None);
 
201
        return Py_None;
 
202
}
 
203
 
 
204
PyDoc_STRVAR(sleep_doc,
 
205
"sleep(seconds)\n\
 
206
\n\
 
207
Delay execution for a given number of seconds.  The argument may be\n\
 
208
a floating point number for subsecond precision.");
 
209
 
 
210
static PyStructSequence_Field struct_time_type_fields[] = {
 
211
        {"tm_year", NULL},
 
212
        {"tm_mon", NULL},
 
213
        {"tm_mday", NULL},
 
214
        {"tm_hour", NULL},
 
215
        {"tm_min", NULL},
 
216
        {"tm_sec", NULL},
 
217
        {"tm_wday", NULL},
 
218
        {"tm_yday", NULL},
 
219
        {"tm_isdst", NULL},
 
220
        {0}
 
221
};
 
222
 
 
223
static PyStructSequence_Desc struct_time_type_desc = {
 
224
        "time.struct_time",
 
225
        NULL,
 
226
        struct_time_type_fields,
 
227
        9,
 
228
};
 
229
 
 
230
static int initialized;
 
231
static PyTypeObject StructTimeType;
 
232
 
 
233
static PyObject *
 
234
tmtotuple(struct tm *p)
 
235
{
 
236
        PyObject *v = PyStructSequence_New(&StructTimeType);
 
237
        if (v == NULL)
 
238
                return NULL;
 
239
 
 
240
#define SET(i,val) PyStructSequence_SET_ITEM(v, i, PyLong_FromLong((long) val))
 
241
 
 
242
        SET(0, p->tm_year + 1900);
 
243
        SET(1, p->tm_mon + 1);     /* Want January == 1 */
 
244
        SET(2, p->tm_mday);
 
245
        SET(3, p->tm_hour);
 
246
        SET(4, p->tm_min);
 
247
        SET(5, p->tm_sec);
 
248
        SET(6, (p->tm_wday + 6) % 7); /* Want Monday == 0 */
 
249
        SET(7, p->tm_yday + 1);    /* Want January, 1 == 1 */
 
250
        SET(8, p->tm_isdst);
 
251
#undef SET
 
252
        if (PyErr_Occurred()) {
 
253
                Py_XDECREF(v);
 
254
                return NULL;
 
255
        }
 
256
 
 
257
        return v;
 
258
}
 
259
 
 
260
static PyObject *
 
261
structtime_totuple(PyObject *t)
 
262
{
 
263
        PyObject *x = NULL;
 
264
        unsigned int i;
 
265
        PyObject *v = PyTuple_New(9);
 
266
        if (v == NULL)
 
267
                return NULL;
 
268
 
 
269
        for (i=0; i<9; i++) {
 
270
                x = PyStructSequence_GET_ITEM(t, i);
 
271
                Py_INCREF(x);
 
272
                PyTuple_SET_ITEM(v, i, x);
 
273
        }
 
274
 
 
275
        if (PyErr_Occurred()) {
 
276
                Py_XDECREF(v);
 
277
                return NULL;
 
278
        }
 
279
 
 
280
        return v;
 
281
}
 
282
 
 
283
static PyObject *
 
284
time_convert(double when, struct tm * (*function)(const time_t *))
 
285
{
 
286
        struct tm *p;
 
287
        time_t whent = _PyTime_DoubleToTimet(when);
 
288
 
 
289
        if (whent == (time_t)-1 && PyErr_Occurred())
 
290
                return NULL;
 
291
        errno = 0;
 
292
        p = function(&whent);
 
293
        if (p == NULL) {
 
294
#ifdef EINVAL
 
295
                if (errno == 0)
 
296
                        errno = EINVAL;
 
297
#endif
 
298
                return PyErr_SetFromErrno(PyExc_ValueError);
 
299
        }
 
300
        return tmtotuple(p);
 
301
}
 
302
 
 
303
/* Parse arg tuple that can contain an optional float-or-None value;
 
304
   format needs to be "|O:name".
 
305
   Returns non-zero on success (parallels PyArg_ParseTuple).
 
306
*/
 
307
static int
 
308
parse_time_double_args(PyObject *args, char *format, double *pwhen)
 
309
{
 
310
        PyObject *ot = NULL;
 
311
 
 
312
        if (!PyArg_ParseTuple(args, format, &ot))
 
313
                return 0;
 
314
        if (ot == NULL || ot == Py_None)
 
315
                *pwhen = floattime();
 
316
        else {
 
317
                double when = PyFloat_AsDouble(ot);
 
318
                if (PyErr_Occurred())
 
319
                        return 0;
 
320
                *pwhen = when;
 
321
        }
 
322
        return 1;
 
323
}
 
324
 
 
325
static PyObject *
 
326
time_gmtime(PyObject *self, PyObject *args)
 
327
{
 
328
        double when;
 
329
        if (!parse_time_double_args(args, "|O:gmtime", &when))
 
330
                return NULL;
 
331
        return time_convert(when, gmtime);
 
332
}
 
333
 
 
334
PyDoc_STRVAR(gmtime_doc,
 
335
"gmtime([seconds]) -> (tm_year, tm_mon, tm_mday, tm_hour, tm_min,\n\
 
336
                       tm_sec, tm_wday, tm_yday, tm_isdst)\n\
 
337
\n\
 
338
Convert seconds since the Epoch to a time tuple expressing UTC (a.k.a.\n\
 
339
GMT).  When 'seconds' is not passed in, convert the current time instead.");
 
340
 
 
341
static PyObject *
 
342
time_localtime(PyObject *self, PyObject *args)
 
343
{
 
344
        double when;
 
345
        if (!parse_time_double_args(args, "|O:localtime", &when))
 
346
                return NULL;
 
347
        return time_convert(when, localtime);
 
348
}
 
349
 
 
350
PyDoc_STRVAR(localtime_doc,
 
351
"localtime([seconds]) -> (tm_year,tm_mon,tm_mday,tm_hour,tm_min,\n\
 
352
                          tm_sec,tm_wday,tm_yday,tm_isdst)\n\
 
353
\n\
 
354
Convert seconds since the Epoch to a time tuple expressing local time.\n\
 
355
When 'seconds' is not passed in, convert the current time instead.");
 
356
 
 
357
static int
 
358
gettmarg(PyObject *args, struct tm *p)
 
359
{
 
360
        int y;
 
361
        PyObject *t = NULL;
 
362
 
 
363
        memset((void *) p, '\0', sizeof(struct tm));
 
364
 
 
365
        if (PyTuple_Check(args)) {
 
366
                t = args;
 
367
                Py_INCREF(t);
 
368
        }
 
369
        else if (Py_TYPE(args) == &StructTimeType) {
 
370
                t = structtime_totuple(args);
 
371
        }
 
372
        else {
 
373
                PyErr_SetString(PyExc_TypeError,
 
374
                                "Tuple or struct_time argument required");
 
375
                return 0;
 
376
        }
 
377
 
 
378
        if (t == NULL || !PyArg_ParseTuple(t, "iiiiiiiii",
 
379
                                           &y,
 
380
                                           &p->tm_mon,
 
381
                                           &p->tm_mday,
 
382
                                           &p->tm_hour,
 
383
                                           &p->tm_min,
 
384
                                           &p->tm_sec,
 
385
                                           &p->tm_wday,
 
386
                                           &p->tm_yday,
 
387
                                           &p->tm_isdst)) {
 
388
                Py_XDECREF(t);
 
389
                return 0;
 
390
        }
 
391
        Py_DECREF(t);
 
392
 
 
393
        if (y < 1900) {
 
394
                PyObject *accept = PyDict_GetItemString(moddict,
 
395
                                                        "accept2dyear");
 
396
                if (accept == NULL || !PyLong_CheckExact(accept) ||
 
397
                    !PyObject_IsTrue(accept)) {
 
398
                        PyErr_SetString(PyExc_ValueError,
 
399
                                        "year >= 1900 required");
 
400
                        return 0;
 
401
                }
 
402
                if (69 <= y && y <= 99)
 
403
                        y += 1900;
 
404
                else if (0 <= y && y <= 68)
 
405
                        y += 2000;
 
406
                else {
 
407
                        PyErr_SetString(PyExc_ValueError,
 
408
                                        "year out of range");
 
409
                        return 0;
 
410
                }
 
411
        }
 
412
        p->tm_year = y - 1900;
 
413
        p->tm_mon--;
 
414
        p->tm_wday = (p->tm_wday + 1) % 7;
 
415
        p->tm_yday--;
 
416
        return 1;
 
417
}
 
418
 
 
419
#ifdef HAVE_STRFTIME
 
420
static PyObject *
 
421
time_strftime(PyObject *self, PyObject *args)
 
422
{
 
423
        PyObject *tup = NULL;
 
424
        struct tm buf;
 
425
        const char *fmt;
 
426
        PyObject *format;
 
427
        size_t fmtlen, buflen;
 
428
        char *outbuf = 0;
 
429
        size_t i;
 
430
 
 
431
        memset((void *) &buf, '\0', sizeof(buf));
 
432
 
 
433
        /* Will always expect a unicode string to be passed as format.
 
434
           Given that there's no str type anymore in py3k this seems safe.
 
435
        */
 
436
        if (!PyArg_ParseTuple(args, "U|O:strftime", &format, &tup))
 
437
                return NULL;
 
438
 
 
439
        if (tup == NULL) {
 
440
                time_t tt = time(NULL);
 
441
                buf = *localtime(&tt);
 
442
        } else if (!gettmarg(tup, &buf))
 
443
                return NULL;
 
444
 
 
445
        /* Checks added to make sure strftime() does not crash Python by
 
446
            indexing blindly into some array for a textual representation
 
447
            by some bad index (fixes bug #897625).
 
448
 
 
449
            Also support values of zero from Python code for arguments in which
 
450
            that is out of range by forcing that value to the lowest value that
 
451
            is valid (fixed bug #1520914).
 
452
 
 
453
            Valid ranges based on what is allowed in struct tm:
 
454
 
 
455
            - tm_year: [0, max(int)] (1)
 
456
            - tm_mon: [0, 11] (2)
 
457
            - tm_mday: [1, 31]
 
458
            - tm_hour: [0, 23]
 
459
            - tm_min: [0, 59]
 
460
            - tm_sec: [0, 60]
 
461
            - tm_wday: [0, 6] (1)
 
462
            - tm_yday: [0, 365] (2)
 
463
            - tm_isdst: [-max(int), max(int)]
 
464
 
 
465
            (1) gettmarg() handles bounds-checking.
 
466
            (2) Python's acceptable range is one greater than the range in C,
 
467
                thus need to check against automatic decrement by gettmarg().
 
468
        */
 
469
        if (buf.tm_mon == -1)
 
470
            buf.tm_mon = 0;
 
471
        else if (buf.tm_mon < 0 || buf.tm_mon > 11) {
 
472
            PyErr_SetString(PyExc_ValueError, "month out of range");
 
473
                        return NULL;
 
474
        }
 
475
        if (buf.tm_mday == 0)
 
476
            buf.tm_mday = 1;
 
477
        else if (buf.tm_mday < 0 || buf.tm_mday > 31) {
 
478
            PyErr_SetString(PyExc_ValueError, "day of month out of range");
 
479
                        return NULL;
 
480
        }
 
481
        if (buf.tm_hour < 0 || buf.tm_hour > 23) {
 
482
            PyErr_SetString(PyExc_ValueError, "hour out of range");
 
483
            return NULL;
 
484
        }
 
485
        if (buf.tm_min < 0 || buf.tm_min > 59) {
 
486
            PyErr_SetString(PyExc_ValueError, "minute out of range");
 
487
            return NULL;
 
488
        }
 
489
        if (buf.tm_sec < 0 || buf.tm_sec > 61) {
 
490
            PyErr_SetString(PyExc_ValueError, "seconds out of range");
 
491
            return NULL;
 
492
        }
 
493
        /* tm_wday does not need checking of its upper-bound since taking
 
494
        ``% 7`` in gettmarg() automatically restricts the range. */
 
495
        if (buf.tm_wday < 0) {
 
496
            PyErr_SetString(PyExc_ValueError, "day of week out of range");
 
497
            return NULL;
 
498
        }
 
499
        if (buf.tm_yday == -1)
 
500
            buf.tm_yday = 0;
 
501
        else if (buf.tm_yday < 0 || buf.tm_yday > 365) {
 
502
            PyErr_SetString(PyExc_ValueError, "day of year out of range");
 
503
            return NULL;
 
504
        }
 
505
        if (buf.tm_isdst < -1 || buf.tm_isdst > 1) {
 
506
            PyErr_SetString(PyExc_ValueError,
 
507
                            "daylight savings flag out of range");
 
508
            return NULL;
 
509
        }
 
510
 
 
511
        /* Convert the unicode string to an ascii one */
 
512
        format = PyUnicode_AsEncodedString(format, TZNAME_ENCODING, NULL);
 
513
        if (format == NULL)
 
514
                return NULL;
 
515
        fmt = PyBytes_AS_STRING(format);
 
516
 
 
517
#ifdef MS_WINDOWS
 
518
        /* check that the format string contains only valid directives */
 
519
        for(outbuf = strchr(fmt, '%');
 
520
                outbuf != NULL;
 
521
                outbuf = strchr(outbuf+2, '%'))
 
522
        {
 
523
                if (outbuf[1]=='#')
 
524
                        ++outbuf; /* not documented by python, */
 
525
                if (outbuf[1]=='\0' ||
 
526
                        !strchr("aAbBcdfHIjmMpSUwWxXyYzZ%", outbuf[1]))
 
527
                {
 
528
                        PyErr_SetString(PyExc_ValueError, "Invalid format string");
 
529
                        return 0;
 
530
                }
 
531
        }
 
532
#endif
 
533
 
 
534
        fmtlen = strlen(fmt);
 
535
 
 
536
        /* I hate these functions that presume you know how big the output
 
537
         * will be ahead of time...
 
538
         */
 
539
        for (i = 1024; ; i += i) {
 
540
                outbuf = (char *)PyMem_Malloc(i);
 
541
                if (outbuf == NULL) {
 
542
                        Py_DECREF(format);
 
543
                        return PyErr_NoMemory();
 
544
                }
 
545
                buflen = strftime(outbuf, i, fmt, &buf);
 
546
                if (buflen > 0 || i >= 256 * fmtlen) {
 
547
                        /* If the buffer is 256 times as long as the format,
 
548
                           it's probably not failing for lack of room!
 
549
                           More likely, the format yields an empty result,
 
550
                           e.g. an empty format, or %Z when the timezone
 
551
                           is unknown. */
 
552
                        PyObject *ret;
 
553
                        ret = PyUnicode_Decode(outbuf, buflen,
 
554
                                               TZNAME_ENCODING, NULL);
 
555
                        PyMem_Free(outbuf);
 
556
                        Py_DECREF(format);
 
557
                        return ret;
 
558
                }
 
559
                PyMem_Free(outbuf);
 
560
#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
 
561
                /* VisualStudio .NET 2005 does this properly */
 
562
                if (buflen == 0 && errno == EINVAL) {
 
563
                        PyErr_SetString(PyExc_ValueError, "Invalid format string");
 
564
                        Py_DECREF(format);
 
565
                        return 0;
 
566
                }
 
567
#endif
 
568
        }
 
569
}
 
570
 
 
571
PyDoc_STRVAR(strftime_doc,
 
572
"strftime(format[, tuple]) -> string\n\
 
573
\n\
 
574
Convert a time tuple to a string according to a format specification.\n\
 
575
See the library reference manual for formatting codes. When the time tuple\n\
 
576
is not present, current time as returned by localtime() is used.");
 
577
#endif /* HAVE_STRFTIME */
 
578
 
 
579
static PyObject *
 
580
time_strptime(PyObject *self, PyObject *args)
 
581
{
 
582
    PyObject *strptime_module = PyImport_ImportModuleNoBlock("_strptime");
 
583
    PyObject *strptime_result;
 
584
 
 
585
    if (!strptime_module)
 
586
        return NULL;
 
587
    strptime_result = PyObject_CallMethod(strptime_module, "_strptime_time", "O", args);
 
588
    Py_DECREF(strptime_module);
 
589
    return strptime_result;
 
590
}
 
591
 
 
592
PyDoc_STRVAR(strptime_doc,
 
593
"strptime(string, format) -> struct_time\n\
 
594
\n\
 
595
Parse a string to a time tuple according to a format specification.\n\
 
596
See the library reference manual for formatting codes (same as strftime()).");
 
597
 
 
598
 
 
599
static PyObject *
 
600
time_asctime(PyObject *self, PyObject *args)
 
601
{
 
602
        PyObject *tup = NULL;
 
603
        struct tm buf;
 
604
        char *p;
 
605
        if (!PyArg_UnpackTuple(args, "asctime", 0, 1, &tup))
 
606
                return NULL;
 
607
        if (tup == NULL) {
 
608
                time_t tt = time(NULL);
 
609
                buf = *localtime(&tt);
 
610
        } else if (!gettmarg(tup, &buf))
 
611
                return NULL;
 
612
        p = asctime(&buf);
 
613
        if (p[24] == '\n')
 
614
                p[24] = '\0';
 
615
        return PyUnicode_FromString(p);
 
616
}
 
617
 
 
618
PyDoc_STRVAR(asctime_doc,
 
619
"asctime([tuple]) -> string\n\
 
620
\n\
 
621
Convert a time tuple to a string, e.g. 'Sat Jun 06 16:26:11 1998'.\n\
 
622
When the time tuple is not present, current time as returned by localtime()\n\
 
623
is used.");
 
624
 
 
625
static PyObject *
 
626
time_ctime(PyObject *self, PyObject *args)
 
627
{
 
628
        PyObject *ot = NULL;
 
629
        time_t tt;
 
630
        char *p;
 
631
 
 
632
        if (!PyArg_UnpackTuple(args, "ctime", 0, 1, &ot))
 
633
                return NULL;
 
634
        if (ot == NULL || ot == Py_None)
 
635
                tt = time(NULL);
 
636
        else {
 
637
                double dt = PyFloat_AsDouble(ot);
 
638
                if (PyErr_Occurred())
 
639
                        return NULL;
 
640
                tt = _PyTime_DoubleToTimet(dt);
 
641
                if (tt == (time_t)-1 && PyErr_Occurred())
 
642
                        return NULL;
 
643
        }
 
644
        p = ctime(&tt);
 
645
        if (p == NULL) {
 
646
                PyErr_SetString(PyExc_ValueError, "unconvertible time");
 
647
                return NULL;
 
648
        }
 
649
        if (p[24] == '\n')
 
650
                p[24] = '\0';
 
651
        return PyUnicode_FromString(p);
 
652
}
 
653
 
 
654
PyDoc_STRVAR(ctime_doc,
 
655
"ctime(seconds) -> string\n\
 
656
\n\
 
657
Convert a time in seconds since the Epoch to a string in local time.\n\
 
658
This is equivalent to asctime(localtime(seconds)). When the time tuple is\n\
 
659
not present, current time as returned by localtime() is used.");
 
660
 
 
661
#ifdef HAVE_MKTIME
 
662
static PyObject *
 
663
time_mktime(PyObject *self, PyObject *tup)
 
664
{
 
665
        struct tm buf;
 
666
        time_t tt;
 
667
        if (!gettmarg(tup, &buf))
 
668
                return NULL;
 
669
        tt = mktime(&buf);
 
670
        if (tt == (time_t)(-1)) {
 
671
                PyErr_SetString(PyExc_OverflowError,
 
672
                                "mktime argument out of range");
 
673
                return NULL;
 
674
        }
 
675
        return PyFloat_FromDouble((double)tt);
 
676
}
 
677
 
 
678
PyDoc_STRVAR(mktime_doc,
 
679
"mktime(tuple) -> floating point number\n\
 
680
\n\
 
681
Convert a time tuple in local time to seconds since the Epoch.");
 
682
#endif /* HAVE_MKTIME */
 
683
 
 
684
#ifdef HAVE_WORKING_TZSET
 
685
static void PyInit_timezone(PyObject *module);
 
686
 
 
687
static PyObject *
 
688
time_tzset(PyObject *self, PyObject *unused)
 
689
{
 
690
        PyObject* m;
 
691
 
 
692
        m = PyImport_ImportModuleNoBlock("time");
 
693
        if (m == NULL) {
 
694
            return NULL;
 
695
        }
 
696
 
 
697
        tzset();
 
698
 
 
699
        /* Reset timezone, altzone, daylight and tzname */
 
700
        PyInit_timezone(m);
 
701
        Py_DECREF(m);
 
702
 
 
703
        Py_INCREF(Py_None);
 
704
        return Py_None;
 
705
}
 
706
 
 
707
PyDoc_STRVAR(tzset_doc,
 
708
"tzset(zone)\n\
 
709
\n\
 
710
Initialize, or reinitialize, the local timezone to the value stored in\n\
 
711
os.environ['TZ']. The TZ environment variable should be specified in\n\
 
712
standard Unix timezone format as documented in the tzset man page\n\
 
713
(eg. 'US/Eastern', 'Europe/Amsterdam'). Unknown timezones will silently\n\
 
714
fall back to UTC. If the TZ environment variable is not set, the local\n\
 
715
timezone is set to the systems best guess of wallclock time.\n\
 
716
Changing the TZ environment variable without calling tzset *may* change\n\
 
717
the local timezone used by methods such as localtime, but this behaviour\n\
 
718
should not be relied on.");
 
719
#endif /* HAVE_WORKING_TZSET */
 
720
 
 
721
static void
 
722
PyInit_timezone(PyObject *m) {
 
723
    /* This code moved from PyInit_time wholesale to allow calling it from
 
724
        time_tzset. In the future, some parts of it can be moved back
 
725
        (for platforms that don't HAVE_WORKING_TZSET, when we know what they
 
726
        are), and the extraneous calls to tzset(3) should be removed.
 
727
        I haven't done this yet, as I don't want to change this code as
 
728
        little as possible when introducing the time.tzset and time.tzsetwall
 
729
        methods. This should simply be a method of doing the following once,
 
730
        at the top of this function and removing the call to tzset() from
 
731
        time_tzset():
 
732
 
 
733
            #ifdef HAVE_TZSET
 
734
            tzset()
 
735
            #endif
 
736
 
 
737
        And I'm lazy and hate C so nyer.
 
738
     */
 
739
#if defined(HAVE_TZNAME) && !defined(__GLIBC__) && !defined(__CYGWIN__)
 
740
        PyObject *otz0, *otz1;
 
741
        tzset();
 
742
#ifdef PYOS_OS2
 
743
        PyModule_AddIntConstant(m, "timezone", _timezone);
 
744
#else /* !PYOS_OS2 */
 
745
        PyModule_AddIntConstant(m, "timezone", timezone);
 
746
#endif /* PYOS_OS2 */
 
747
#ifdef HAVE_ALTZONE
 
748
        PyModule_AddIntConstant(m, "altzone", altzone);
 
749
#else
 
750
#ifdef PYOS_OS2
 
751
        PyModule_AddIntConstant(m, "altzone", _timezone-3600);
 
752
#else /* !PYOS_OS2 */
 
753
        PyModule_AddIntConstant(m, "altzone", timezone-3600);
 
754
#endif /* PYOS_OS2 */
 
755
#endif
 
756
        PyModule_AddIntConstant(m, "daylight", daylight);
 
757
        otz0 = PyUnicode_Decode(tzname[0], strlen(tzname[0]), TZNAME_ENCODING, NULL);
 
758
        otz1 = PyUnicode_Decode(tzname[1], strlen(tzname[1]), TZNAME_ENCODING, NULL);
 
759
        PyModule_AddObject(m, "tzname", Py_BuildValue("(NN)", otz0, otz1));
 
760
#else /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/
 
761
#ifdef HAVE_STRUCT_TM_TM_ZONE
 
762
        {
 
763
#define YEAR ((time_t)((365 * 24 + 6) * 3600))
 
764
                time_t t;
 
765
                struct tm *p;
 
766
                long janzone, julyzone;
 
767
                char janname[10], julyname[10];
 
768
                t = (time((time_t *)0) / YEAR) * YEAR;
 
769
                p = localtime(&t);
 
770
                janzone = -p->tm_gmtoff;
 
771
                strncpy(janname, p->tm_zone ? p->tm_zone : "   ", 9);
 
772
                janname[9] = '\0';
 
773
                t += YEAR/2;
 
774
                p = localtime(&t);
 
775
                julyzone = -p->tm_gmtoff;
 
776
                strncpy(julyname, p->tm_zone ? p->tm_zone : "   ", 9);
 
777
                julyname[9] = '\0';
 
778
 
 
779
                if( janzone < julyzone ) {
 
780
                        /* DST is reversed in the southern hemisphere */
 
781
                        PyModule_AddIntConstant(m, "timezone", julyzone);
 
782
                        PyModule_AddIntConstant(m, "altzone", janzone);
 
783
                        PyModule_AddIntConstant(m, "daylight",
 
784
                                                janzone != julyzone);
 
785
                        PyModule_AddObject(m, "tzname",
 
786
                                           Py_BuildValue("(zz)",
 
787
                                                         julyname, janname));
 
788
                } else {
 
789
                        PyModule_AddIntConstant(m, "timezone", janzone);
 
790
                        PyModule_AddIntConstant(m, "altzone", julyzone);
 
791
                        PyModule_AddIntConstant(m, "daylight",
 
792
                                                janzone != julyzone);
 
793
                        PyModule_AddObject(m, "tzname",
 
794
                                           Py_BuildValue("(zz)",
 
795
                                                         janname, julyname));
 
796
                }
 
797
        }
 
798
#else
 
799
#endif /* HAVE_STRUCT_TM_TM_ZONE */
 
800
#ifdef __CYGWIN__
 
801
        tzset();
 
802
        PyModule_AddIntConstant(m, "timezone", _timezone);
 
803
        PyModule_AddIntConstant(m, "altzone", _timezone-3600);
 
804
        PyModule_AddIntConstant(m, "daylight", _daylight);
 
805
        PyModule_AddObject(m, "tzname",
 
806
                           Py_BuildValue("(zz)", _tzname[0], _tzname[1]));
 
807
#endif /* __CYGWIN__ */
 
808
#endif /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/
 
809
}
 
810
 
 
811
 
 
812
static PyMethodDef time_methods[] = {
 
813
        {"time",        time_time, METH_NOARGS, time_doc},
 
814
#ifdef HAVE_CLOCK
 
815
        {"clock",       time_clock, METH_NOARGS, clock_doc},
 
816
#endif
 
817
        {"sleep",       time_sleep, METH_VARARGS, sleep_doc},
 
818
        {"gmtime",      time_gmtime, METH_VARARGS, gmtime_doc},
 
819
        {"localtime",   time_localtime, METH_VARARGS, localtime_doc},
 
820
        {"asctime",     time_asctime, METH_VARARGS, asctime_doc},
 
821
        {"ctime",       time_ctime, METH_VARARGS, ctime_doc},
 
822
#ifdef HAVE_MKTIME
 
823
        {"mktime",      time_mktime, METH_O, mktime_doc},
 
824
#endif
 
825
#ifdef HAVE_STRFTIME
 
826
        {"strftime",    time_strftime, METH_VARARGS, strftime_doc},
 
827
#endif
 
828
        {"strptime",    time_strptime, METH_VARARGS, strptime_doc},
 
829
#ifdef HAVE_WORKING_TZSET
 
830
        {"tzset",       time_tzset, METH_NOARGS, tzset_doc},
 
831
#endif
 
832
        {NULL,          NULL}           /* sentinel */
 
833
};
 
834
 
 
835
 
 
836
PyDoc_STRVAR(module_doc,
 
837
"This module provides various functions to manipulate time values.\n\
 
838
\n\
 
839
There are two standard representations of time.  One is the number\n\
 
840
of seconds since the Epoch, in UTC (a.k.a. GMT).  It may be an integer\n\
 
841
or a floating point number (to represent fractions of seconds).\n\
 
842
The Epoch is system-defined; on Unix, it is generally January 1st, 1970.\n\
 
843
The actual value can be retrieved by calling gmtime(0).\n\
 
844
\n\
 
845
The other representation is a tuple of 9 integers giving local time.\n\
 
846
The tuple items are:\n\
 
847
  year (four digits, e.g. 1998)\n\
 
848
  month (1-12)\n\
 
849
  day (1-31)\n\
 
850
  hours (0-23)\n\
 
851
  minutes (0-59)\n\
 
852
  seconds (0-59)\n\
 
853
  weekday (0-6, Monday is 0)\n\
 
854
  Julian day (day in the year, 1-366)\n\
 
855
  DST (Daylight Savings Time) flag (-1, 0 or 1)\n\
 
856
If the DST flag is 0, the time is given in the regular time zone;\n\
 
857
if it is 1, the time is given in the DST time zone;\n\
 
858
if it is -1, mktime() should guess based on the date and time.\n\
 
859
\n\
 
860
Variables:\n\
 
861
\n\
 
862
timezone -- difference in seconds between UTC and local standard time\n\
 
863
altzone -- difference in  seconds between UTC and local DST time\n\
 
864
daylight -- whether local time should reflect DST\n\
 
865
tzname -- tuple of (standard time zone name, DST time zone name)\n\
 
866
\n\
 
867
Functions:\n\
 
868
\n\
 
869
time() -- return current time in seconds since the Epoch as a float\n\
 
870
clock() -- return CPU time since process start as a float\n\
 
871
sleep() -- delay for a number of seconds given as a float\n\
 
872
gmtime() -- convert seconds since Epoch to UTC tuple\n\
 
873
localtime() -- convert seconds since Epoch to local time tuple\n\
 
874
asctime() -- convert time tuple to string\n\
 
875
ctime() -- convert time in seconds to string\n\
 
876
mktime() -- convert local time tuple to seconds since Epoch\n\
 
877
strftime() -- convert time tuple to string according to format specification\n\
 
878
strptime() -- parse string to time tuple according to format specification\n\
 
879
tzset() -- change the local timezone");
 
880
 
 
881
 
 
882
 
 
883
static struct PyModuleDef timemodule = {
 
884
        PyModuleDef_HEAD_INIT,
 
885
        "time",
 
886
        module_doc,
 
887
        -1,
 
888
        time_methods,
 
889
        NULL,
 
890
        NULL,
 
891
        NULL,
 
892
        NULL
 
893
};
 
894
 
 
895
PyMODINIT_FUNC
 
896
PyInit_time(void)
 
897
{
 
898
        PyObject *m;
 
899
        char *p;
 
900
        m = PyModule_Create(&timemodule);
 
901
        if (m == NULL)
 
902
                return NULL;
 
903
 
 
904
        /* Accept 2-digit dates unless PYTHONY2K is set and non-empty */
 
905
        p = Py_GETENV("PYTHONY2K");
 
906
        PyModule_AddIntConstant(m, "accept2dyear", (long) (!p || !*p));
 
907
        /* Squirrel away the module's dictionary for the y2k check */
 
908
        moddict = PyModule_GetDict(m);
 
909
        Py_INCREF(moddict);
 
910
 
 
911
        /* Set, or reset, module variables like time.timezone */
 
912
        PyInit_timezone(m);
 
913
 
 
914
#ifdef MS_WINDOWS
 
915
        /* Helper to allow interrupts for Windows.
 
916
           If Ctrl+C event delivered while not sleeping
 
917
           it will be ignored.
 
918
        */
 
919
        main_thread = PyThread_get_thread_ident();
 
920
        hInterruptEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
 
921
        SetConsoleCtrlHandler( PyCtrlHandler, TRUE);
 
922
#endif /* MS_WINDOWS */
 
923
        if (!initialized) {
 
924
                PyStructSequence_InitType(&StructTimeType,
 
925
                                          &struct_time_type_desc);
 
926
        }
 
927
        Py_INCREF(&StructTimeType);
 
928
        PyModule_AddObject(m, "struct_time", (PyObject*) &StructTimeType);
 
929
        initialized = 1;
 
930
        return m;
 
931
}
 
932
 
 
933
 
 
934
/* Implement floattime() for various platforms */
 
935
 
 
936
static double
 
937
floattime(void)
 
938
{
 
939
        /* There are three ways to get the time:
 
940
          (1) gettimeofday() -- resolution in microseconds
 
941
          (2) ftime() -- resolution in milliseconds
 
942
          (3) time() -- resolution in seconds
 
943
          In all cases the return value is a float in seconds.
 
944
          Since on some systems (e.g. SCO ODT 3.0) gettimeofday() may
 
945
          fail, so we fall back on ftime() or time().
 
946
          Note: clock resolution does not imply clock accuracy! */
 
947
#ifdef HAVE_GETTIMEOFDAY
 
948
        {
 
949
                struct timeval t;
 
950
#ifdef GETTIMEOFDAY_NO_TZ
 
951
                if (gettimeofday(&t) == 0)
 
952
                        return (double)t.tv_sec + t.tv_usec*0.000001;
 
953
#else /* !GETTIMEOFDAY_NO_TZ */
 
954
                if (gettimeofday(&t, (struct timezone *)NULL) == 0)
 
955
                        return (double)t.tv_sec + t.tv_usec*0.000001;
 
956
#endif /* !GETTIMEOFDAY_NO_TZ */
 
957
        }
 
958
 
 
959
#endif /* !HAVE_GETTIMEOFDAY */
 
960
        {
 
961
#if defined(HAVE_FTIME)
 
962
                struct timeb t;
 
963
                ftime(&t);
 
964
                return (double)t.time + (double)t.millitm * (double)0.001;
 
965
#else /* !HAVE_FTIME */
 
966
                time_t secs;
 
967
                time(&secs);
 
968
                return (double)secs;
 
969
#endif /* !HAVE_FTIME */
 
970
        }
 
971
}
 
972
 
 
973
 
 
974
/* Implement floatsleep() for various platforms.
 
975
   When interrupted (or when another error occurs), return -1 and
 
976
   set an exception; else return 0. */
 
977
 
 
978
static int
 
979
floatsleep(double secs)
 
980
{
 
981
/* XXX Should test for MS_WINDOWS first! */
 
982
#if defined(HAVE_SELECT) && !defined(__EMX__)
 
983
        struct timeval t;
 
984
        double frac;
 
985
        frac = fmod(secs, 1.0);
 
986
        secs = floor(secs);
 
987
        t.tv_sec = (long)secs;
 
988
        t.tv_usec = (long)(frac*1000000.0);
 
989
        Py_BEGIN_ALLOW_THREADS
 
990
        if (select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &t) != 0) {
 
991
#ifdef EINTR
 
992
                if (errno != EINTR) {
 
993
#else
 
994
                if (1) {
 
995
#endif
 
996
                        Py_BLOCK_THREADS
 
997
                        PyErr_SetFromErrno(PyExc_IOError);
 
998
                        return -1;
 
999
                }
 
1000
        }
 
1001
        Py_END_ALLOW_THREADS
 
1002
#elif defined(__WATCOMC__) && !defined(__QNX__)
 
1003
        /* XXX Can't interrupt this sleep */
 
1004
        Py_BEGIN_ALLOW_THREADS
 
1005
        delay((int)(secs * 1000 + 0.5));  /* delay() uses milliseconds */
 
1006
        Py_END_ALLOW_THREADS
 
1007
#elif defined(MS_WINDOWS)
 
1008
        {
 
1009
                double millisecs = secs * 1000.0;
 
1010
                unsigned long ul_millis;
 
1011
 
 
1012
                if (millisecs > (double)ULONG_MAX) {
 
1013
                        PyErr_SetString(PyExc_OverflowError,
 
1014
                                        "sleep length is too large");
 
1015
                        return -1;
 
1016
                }
 
1017
                Py_BEGIN_ALLOW_THREADS
 
1018
                /* Allow sleep(0) to maintain win32 semantics, and as decreed
 
1019
                 * by Guido, only the main thread can be interrupted.
 
1020
                 */
 
1021
                ul_millis = (unsigned long)millisecs;
 
1022
                if (ul_millis == 0 ||
 
1023
                    main_thread != PyThread_get_thread_ident())
 
1024
                        Sleep(ul_millis);
 
1025
                else {
 
1026
                        DWORD rc;
 
1027
                        ResetEvent(hInterruptEvent);
 
1028
                        rc = WaitForSingleObject(hInterruptEvent, ul_millis);
 
1029
                        if (rc == WAIT_OBJECT_0) {
 
1030
                                /* Yield to make sure real Python signal
 
1031
                                 * handler called.
 
1032
                                 */
 
1033
                                Sleep(1);
 
1034
                                Py_BLOCK_THREADS
 
1035
                                errno = EINTR;
 
1036
                                PyErr_SetFromErrno(PyExc_IOError);
 
1037
                                return -1;
 
1038
                        }
 
1039
                }
 
1040
                Py_END_ALLOW_THREADS
 
1041
        }
 
1042
#elif defined(PYOS_OS2)
 
1043
        /* This Sleep *IS* Interruptable by Exceptions */
 
1044
        Py_BEGIN_ALLOW_THREADS
 
1045
        if (DosSleep(secs * 1000) != NO_ERROR) {
 
1046
                Py_BLOCK_THREADS
 
1047
                PyErr_SetFromErrno(PyExc_IOError);
 
1048
                return -1;
 
1049
        }
 
1050
        Py_END_ALLOW_THREADS
 
1051
#elif defined(PLAN9)
 
1052
        {
 
1053
                double millisecs = secs * 1000.0;
 
1054
                if (millisecs > (double)LONG_MAX) {
 
1055
                        PyErr_SetString(PyExc_OverflowError, "sleep length is too large");
 
1056
                        return -1;
 
1057
                }
 
1058
                /* This sleep *CAN BE* interrupted. */
 
1059
                Py_BEGIN_ALLOW_THREADS
 
1060
                if(sleep((long)millisecs) < 0){
 
1061
                        Py_BLOCK_THREADS
 
1062
                        PyErr_SetFromErrno(PyExc_IOError);
 
1063
                        return -1;
 
1064
                }
 
1065
                Py_END_ALLOW_THREADS
 
1066
        }
 
1067
#else
 
1068
        /* XXX Can't interrupt this sleep */
 
1069
        Py_BEGIN_ALLOW_THREADS
 
1070
        sleep((int)secs);
 
1071
        Py_END_ALLOW_THREADS
 
1072
#endif
 
1073
 
 
1074
        return 0;
 
1075
}