/* Time module */ #include "Python.h"#include "structseq.h"#include "timefuncs.h" #ifdef __APPLE__#if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_FTIME) /* * floattime falls back to ftime when getttimeofday fails because the latter * might fail on some platforms. This fallback is unwanted on MacOSX because * that makes it impossible to use a binary build on OSX 10.4 on earlier * releases of the OS. Therefore claim we don't support ftime. */# undef HAVE_FTIME#endif#endif #include <ctype.h> #ifdef HAVE_SYS_TYPES_H#include <sys/types.h>#endif /* HAVE_SYS_TYPES_H */ #ifdef QUICKWIN#include <io.h>#endif #ifdef HAVE_FTIME#include <sys/timeb.h>#if !defined(MS_WINDOWS) && !defined(PYOS_OS2)extern int ftime(struct timeb *);#endif /* MS_WINDOWS */#endif /* HAVE_FTIME */ #if defined(__WATCOMC__) && !defined(__QNX__)#include <i86.h>#else#ifdef MS_WINDOWS#define WIN32_LEAN_AND_MEAN#include <windows.h>#include "pythread.h" /* helper to allow us to interrupt sleep() on Windows*/static HANDLE hInterruptEvent = NULL;static BOOL WINAPI PyCtrlHandler(DWORD dwCtrlType){ SetEvent(hInterruptEvent); /* allow other default handlers to be called. Default Python handler will setup the KeyboardInterrupt exception. */ return FALSE;}static long main_thread; #if defined(__BORLANDC__)/* These overrides not needed for Win32 */#define timezone _timezone#define tzname _tzname#define daylight _daylight#endif /* __BORLANDC__ */#endif /* MS_WINDOWS */#endif /* !__WATCOMC__ || __QNX__ */ #if defined(MS_WINDOWS) && !defined(__BORLANDC__)/* Win32 has better clock replacement; we have our own version below. */#undef HAVE_CLOCK#endif /* MS_WINDOWS && !defined(__BORLANDC__) */ #if defined(PYOS_OS2)#define INCL_DOS#define INCL_ERRORS#include <os2.h>#endif #if defined(PYCC_VACPP)#include <sys/time.h>#endif #ifdef __BEOS__#include <time.h>/* For bigtime_t, snooze(). - [cjh] */#include <support/SupportDefs.h>#include <kernel/OS.h>#endif #ifdef RISCOSextern int riscos_sleep(double);#endif /* Forward declarations */static int floatsleep(double);static double floattime(void); /* For Y2K check */static PyObject *moddict; /* Exposed in timefuncs.h. */time_t_PyTime_DoubleToTimet(double x){ time_t result; double diff; result = (time_t)x; /* How much info did we lose? time_t may be an integral or * floating type, and we don't know which. If it's integral, * we don't know whether C truncates, rounds, returns the floor, * etc. If we lost a second or more, the C rounding is * unreasonable, or the input just doesn't fit in a time_t; * call it an error regardless. Note that the original cast to * time_t can cause a C error too, but nothing we can do to * worm around that. */ diff = x - (double)result; if (diff <= -1.0 || diff >= 1.0) { PyErr_SetString(PyExc_ValueError, "timestamp out of range for platform time_t"); result = (time_t)-1; } return result;} static PyObject *time_time(PyObject *self, PyObject *unused){ double secs; secs = floattime(); if (secs == 0.0) { PyErr_SetFromErrno(PyExc_IOError); return NULL; } return PyFloat_FromDouble(secs);} PyDoc_STRVAR(time_doc,"time() -> floating point number\n\\n\Return the current time in seconds since the Epoch.\n\Fractions of a second may be present if the system clock provides them."); #ifdef HAVE_CLOCK #ifndef CLOCKS_PER_SEC#ifdef CLK_TCK#define CLOCKS_PER_SEC CLK_TCK#else#define CLOCKS_PER_SEC 1000000#endif#endif static PyObject *time_clock(PyObject *self, PyObject *unused){ return PyFloat_FromDouble(((double)clock()) / CLOCKS_PER_SEC);}#endif /* HAVE_CLOCK */ #if defined(MS_WINDOWS) && !defined(__BORLANDC__)/* Due to Mark Hammond and Tim Peters */static PyObject *time_clock(PyObject *self, PyObject *unused){ static LARGE_INTEGER ctrStart; static double divisor = 0.0; LARGE_INTEGER now; double diff; if (divisor == 0.0) { LARGE_INTEGER freq; QueryPerformanceCounter(&ctrStart); if (!QueryPerformanceFrequency(&freq) || freq.QuadPart == 0) { /* Unlikely to happen - this works on all intel machines at least! Revert to clock() */ return PyFloat_FromDouble(((double)clock()) / CLOCKS_PER_SEC); } divisor = (double)freq.QuadPart; } QueryPerformanceCounter(&now); diff = (double)(now.QuadPart - ctrStart.QuadPart); return PyFloat_FromDouble(diff / divisor);} #define HAVE_CLOCK /* So it gets included in the methods */#endif /* MS_WINDOWS && !defined(__BORLANDC__) */ #ifdef HAVE_CLOCKPyDoc_STRVAR(clock_doc,"clock() -> floating point number\n\\n\Return the CPU time or real time since the start of the process or since\n\the first call to clock(). This has as much precision as the system\n\records.");#endif static PyObject *time_sleep(PyObject *self, PyObject *args){ double secs; if (!PyArg_ParseTuple(args, "d:sleep", &secs)) return NULL; if (floatsleep(secs) != 0) return NULL; Py_INCREF(Py_None); return Py_None;} PyDoc_STRVAR(sleep_doc,"sleep(seconds)\n\\n\Delay execution for a given number of seconds. The argument may be\n\a floating point number for subsecond precision."); static PyStructSequence_Field struct_time_type_fields[] = { {"tm_year", NULL}, {"tm_mon", NULL}, {"tm_mday", NULL}, {"tm_hour", NULL}, {"tm_min", NULL}, {"tm_sec", NULL}, {"tm_wday", NULL}, {"tm_yday", NULL}, {"tm_isdst", NULL}, {0}}; static PyStructSequence_Desc struct_time_type_desc = { "time.struct_time", NULL, struct_time_type_fields, 9,}; static int initialized;static PyTypeObject StructTimeType; static PyObject *tmtotuple(struct tm *p){ PyObject *v = PyStructSequence_New(&StructTimeType); if (v == NULL) return NULL; #define SET(i,val) PyStructSequence_SET_ITEM(v, i, PyInt_FromLong((long) val)) SET(0, p->tm_year + 1900); SET(1, p->tm_mon + 1); /* Want January == 1 */ SET(2, p->tm_mday); SET(3, p->tm_hour); SET(4, p->tm_min); SET(5, p->tm_sec); SET(6, (p->tm_wday + 6) % 7); /* Want Monday == 0 */ SET(7, p->tm_yday + 1); /* Want January, 1 == 1 */ SET(8, p->tm_isdst);#undef SET if (PyErr_Occurred()) { Py_XDECREF(v); return NULL; } return v;} static PyObject *time_convert(double when, struct tm * (*function)(const time_t *)){ struct tm *p; time_t whent = _PyTime_DoubleToTimet(when); if (whent == (time_t)-1 && PyErr_Occurred()) return NULL; errno = 0; p = function(&whent); if (p == NULL) {#ifdef EINVAL if (errno == 0) errno = EINVAL;#endif return PyErr_SetFromErrno(PyExc_ValueError); } return tmtotuple(p);} /* Parse arg tuple that can contain an optional float-or-None value; format needs to be "|O:name". Returns non-zero on success (parallels PyArg_ParseTuple).*/static intparse_time_double_args(PyObject *args, char *format, double *pwhen){ PyObject *ot = NULL; if (!PyArg_ParseTuple(args, format, &ot)) return 0; if (ot == NULL || ot == Py_None) *pwhen = floattime(); else { double when = PyFloat_AsDouble(ot); if (PyErr_Occurred()) return 0; *pwhen = when; } return 1;} static PyObject *time_gmtime(PyObject *self, PyObject *args){ double when; if (!parse_time_double_args(args, "|O:gmtime", &when)) return NULL; return time_convert(when, gmtime);} PyDoc_STRVAR(gmtime_doc,"gmtime([seconds]) -> (tm_year, tm_mon, tm_day, tm_hour, tm_min,\n\ tm_sec, tm_wday, tm_yday, tm_isdst)\n\\n\Convert seconds since the Epoch to a time tuple expressing UTC (a.k.a.\n\GMT). When 'seconds' is not passed in, convert the current time instead."); static PyObject *time_localtime(PyObject *self, PyObject *args){ double when; if (!parse_time_double_args(args, "|O:localtime", &when)) return NULL; return time_convert(when, localtime);} PyDoc_STRVAR(localtime_doc,"localtime([seconds]) -> (tm_year,tm_mon,tm_day,tm_hour,tm_min,tm_sec,tm_wday,tm_yday,tm_isdst)\n\\n\Convert seconds since the Epoch to a time tuple expressing local time.\n\When 'seconds' is not passed in, convert the current time instead."); static intgettmarg(PyObject *args, struct tm *p){ int y; memset((void *) p, '\0', sizeof(struct tm)); if (!PyArg_Parse(args, "(iiiiiiiii)", &y, &p->tm_mon, &p->tm_mday, &p->tm_hour, &p->tm_min, &p->tm_sec, &p->tm_wday, &p->tm_yday, &p->tm_isdst)) return 0; if (y < 1900) { PyObject *accept = PyDict_GetItemString(moddict, "accept2dyear"); if (accept == NULL || !PyInt_Check(accept) || PyInt_AsLong(accept) == 0) { PyErr_SetString(PyExc_ValueError, "year >= 1900 required"); return 0; } if (69 <= y && y <= 99) y += 1900; else if (0 <= y && y <= 68) y += 2000; else { PyErr_SetString(PyExc_ValueError, "year out of range"); return 0; } } p->tm_year = y - 1900; p->tm_mon--; p->tm_wday = (p->tm_wday + 1) % 7; p->tm_yday--; return 1;} #ifdef HAVE_STRFTIMEstatic PyObject *time_strftime(PyObject *self, PyObject *args){ PyObject *tup = NULL; struct tm buf; const char *fmt; size_t fmtlen, buflen; char *outbuf = 0; size_t i; memset((void *) &buf, '\0', sizeof(buf)); if (!PyArg_ParseTuple(args, "s|O:strftime", &fmt, &tup)) return NULL; if (tup == NULL) { time_t tt = time(NULL); buf = *localtime(&tt); } else if (!gettmarg(tup, &buf)) return NULL; /* Checks added to make sure strftime() does not crash Python by indexing blindly into some array for a textual representation by some bad index (fixes bug #897625). Also support values of zero from Python code for arguments in which that is out of range by forcing that value to the lowest value that is valid (fixed bug #1520914). Valid ranges based on what is allowed in struct tm: - tm_year: [0, max(int)] (1) - tm_mon: [0, 11] (2) - tm_mday: [1, 31] - tm_hour: [0, 23] - tm_min: [0, 59] - tm_sec: [0, 60] - tm_wday: [0, 6] (1) - tm_yday: [0, 365] (2) - tm_isdst: [-max(int), max(int)] (1) gettmarg() handles bounds-checking. (2) Python's acceptable range is one greater than the range in C, thus need to check against automatic decrement by gettmarg(). */ if (buf.tm_mon == -1) buf.tm_mon = 0; else if (buf.tm_mon < 0 || buf.tm_mon > 11) { PyErr_SetString(PyExc_ValueError, "month out of range"); return NULL; } if (buf.tm_mday == 0) buf.tm_mday = 1; else if (buf.tm_mday < 0 || buf.tm_mday > 31) { PyErr_SetString(PyExc_ValueError, "day of month out of range"); return NULL; } if (buf.tm_hour < 0 || buf.tm_hour > 23) { PyErr_SetString(PyExc_ValueError, "hour out of range"); return NULL; } if (buf.tm_min < 0 || buf.tm_min > 59) { PyErr_SetString(PyExc_ValueError, "minute out of range"); return NULL; } if (buf.tm_sec < 0 || buf.tm_sec > 61) { PyErr_SetString(PyExc_ValueError, "seconds out of range"); return NULL; } /* tm_wday does not need checking of its upper-bound since taking ``% 7`` in gettmarg() automatically restricts the range. */ if (buf.tm_wday < 0) { PyErr_SetString(PyExc_ValueError, "day of week out of range"); return NULL; } if (buf.tm_yday == -1) buf.tm_yday = 0; else if (buf.tm_yday < 0 || buf.tm_yday > 365) { PyErr_SetString(PyExc_ValueError, "day of year out of range"); return NULL; } if (buf.tm_isdst < -1 || buf.tm_isdst > 1) { PyErr_SetString(PyExc_ValueError, "daylight savings flag out of range"); return NULL; } fmtlen = strlen(fmt); /* I hate these functions that presume you know how big the output * will be ahead of time... */ for (i = 1024; ; i += i) { outbuf = (char *)malloc(i); if (outbuf == NULL) { return PyErr_NoMemory(); } buflen = strftime(outbuf, i, fmt, &buf); if (buflen > 0 || i >= 256 * fmtlen) { /* If the buffer is 256 times as long as the format, it's probably not failing for lack of room! More likely, the format yields an empty result, e.g. an empty format, or %Z when the timezone is unknown. */ PyObject *ret; ret = PyString_FromStringAndSize(outbuf, buflen); free(outbuf); return ret; } free(outbuf);#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__) /* VisualStudio .NET 2005 does this properly */ if (buflen == 0 && errno == EINVAL) { PyErr_SetString(PyExc_ValueError, "Invalid format string"); return 0; }Lines 1–500 of 1027. Load more
/* Time module */ #include "Python.h" #include "structseq.h" #include "timefuncs.h" #ifdef __APPLE__ #if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_FTIME) /* * floattime falls back to ftime when getttimeofday fails because the latter * might fail on some platforms. This fallback is unwanted on MacOSX because * that makes it impossible to use a binary build on OSX 10.4 on earlier * releases of the OS. Therefore claim we don't support ftime. */ # undef HAVE_FTIME #endif #endif #include <ctype.h> #ifdef HAVE_SYS_TYPES_H #include <sys/types.h> #endif /* HAVE_SYS_TYPES_H */ #ifdef QUICKWIN #include <io.h> #endif #ifdef HAVE_FTIME #include <sys/timeb.h> #if !defined(MS_WINDOWS) && !defined(PYOS_OS2) extern int ftime(struct timeb *); #endif /* MS_WINDOWS */ #endif /* HAVE_FTIME */ #if defined(__WATCOMC__) && !defined(__QNX__) #include <i86.h> #else #ifdef MS_WINDOWS #define WIN32_LEAN_AND_MEAN #include <windows.h> #include "pythread.h" /* helper to allow us to interrupt sleep() on Windows*/ static HANDLE hInterruptEvent = NULL; static BOOL WINAPI PyCtrlHandler(DWORD dwCtrlType) { SetEvent(hInterruptEvent); /* allow other default handlers to be called. Default Python handler will setup the KeyboardInterrupt exception. */ return FALSE; } static long main_thread; #if defined(__BORLANDC__) /* These overrides not needed for Win32 */ #define timezone _timezone #define tzname _tzname #define daylight _daylight #endif /* __BORLANDC__ */ #endif /* MS_WINDOWS */ #endif /* !__WATCOMC__ || __QNX__ */ #if defined(MS_WINDOWS) && !defined(__BORLANDC__) /* Win32 has better clock replacement; we have our own version below. */ #undef HAVE_CLOCK #endif /* MS_WINDOWS && !defined(__BORLANDC__) */ #if defined(PYOS_OS2) #define INCL_DOS #define INCL_ERRORS #include <os2.h> #endif #if defined(PYCC_VACPP) #include <sys/time.h> #endif #ifdef __BEOS__ #include <time.h> /* For bigtime_t, snooze(). - [cjh] */ #include <support/SupportDefs.h> #include <kernel/OS.h> #endif #ifdef RISCOS extern int riscos_sleep(double); #endif /* Forward declarations */ static int floatsleep(double); static double floattime(void); /* For Y2K check */ static PyObject *moddict; /* Exposed in timefuncs.h. */ time_t _PyTime_DoubleToTimet(double x) { time_t result; double diff; result = (time_t)x; /* How much info did we lose? time_t may be an integral or * floating type, and we don't know which. If it's integral, * we don't know whether C truncates, rounds, returns the floor, * etc. If we lost a second or more, the C rounding is * unreasonable, or the input just doesn't fit in a time_t; * call it an error regardless. Note that the original cast to * time_t can cause a C error too, but nothing we can do to * worm around that. */ diff = x - (double)result; if (diff <= -1.0 || diff >= 1.0) { PyErr_SetString(PyExc_ValueError, "timestamp out of range for platform time_t"); result = (time_t)-1; } return result; } static PyObject * time_time(PyObject *self, PyObject *unused) { double secs; secs = floattime(); if (secs == 0.0) { PyErr_SetFromErrno(PyExc_IOError); return NULL; } return PyFloat_FromDouble(secs); } PyDoc_STRVAR(time_doc, "time() -> floating point number\n\ \n\ Return the current time in seconds since the Epoch.\n\ Fractions of a second may be present if the system clock provides them."); #ifdef HAVE_CLOCK #ifndef CLOCKS_PER_SEC #ifdef CLK_TCK #define CLOCKS_PER_SEC CLK_TCK #else #define CLOCKS_PER_SEC 1000000 #endif #endif static PyObject * time_clock(PyObject *self, PyObject *unused) { return PyFloat_FromDouble(((double)clock()) / CLOCKS_PER_SEC); } #endif /* HAVE_CLOCK */ #if defined(MS_WINDOWS) && !defined(__BORLANDC__) /* Due to Mark Hammond and Tim Peters */ static PyObject * time_clock(PyObject *self, PyObject *unused) { static LARGE_INTEGER ctrStart; static double divisor = 0.0; LARGE_INTEGER now; double diff; if (divisor == 0.0) { LARGE_INTEGER freq; QueryPerformanceCounter(&ctrStart); if (!QueryPerformanceFrequency(&freq) || freq.QuadPart == 0) { /* Unlikely to happen - this works on all intel machines at least! Revert to clock() */ return PyFloat_FromDouble(((double)clock()) / CLOCKS_PER_SEC); } divisor = (double)freq.QuadPart; } QueryPerformanceCounter(&now); diff = (double)(now.QuadPart - ctrStart.QuadPart); return PyFloat_FromDouble(diff / divisor); } #define HAVE_CLOCK /* So it gets included in the methods */ #endif /* MS_WINDOWS && !defined(__BORLANDC__) */ #ifdef HAVE_CLOCK PyDoc_STRVAR(clock_doc, "clock() -> floating point number\n\ \n\ Return the CPU time or real time since the start of the process or since\n\ the first call to clock(). This has as much precision as the system\n\ records."); #endif static PyObject * time_sleep(PyObject *self, PyObject *args) { double secs; if (!PyArg_ParseTuple(args, "d:sleep", &secs)) return NULL; if (floatsleep(secs) != 0) return NULL; Py_INCREF(Py_None); return Py_None; } PyDoc_STRVAR(sleep_doc, "sleep(seconds)\n\ \n\ Delay execution for a given number of seconds. The argument may be\n\ a floating point number for subsecond precision."); static PyStructSequence_Field struct_time_type_fields[] = { {"tm_year", NULL}, {"tm_mon", NULL}, {"tm_mday", NULL}, {"tm_hour", NULL}, {"tm_min", NULL}, {"tm_sec", NULL}, {"tm_wday", NULL}, {"tm_yday", NULL}, {"tm_isdst", NULL}, {0} }; static PyStructSequence_Desc struct_time_type_desc = { "time.struct_time", NULL, struct_time_type_fields, 9, }; static int initialized; static PyTypeObject StructTimeType; static PyObject * tmtotuple(struct tm *p) { PyObject *v = PyStructSequence_New(&StructTimeType); if (v == NULL) return NULL; #define SET(i,val) PyStructSequence_SET_ITEM(v, i, PyInt_FromLong((long) val)) SET(0, p->tm_year + 1900); SET(1, p->tm_mon + 1); /* Want January == 1 */ SET(2, p->tm_mday); SET(3, p->tm_hour); SET(4, p->tm_min); SET(5, p->tm_sec); SET(6, (p->tm_wday + 6) % 7); /* Want Monday == 0 */ SET(7, p->tm_yday + 1); /* Want January, 1 == 1 */ SET(8, p->tm_isdst); #undef SET if (PyErr_Occurred()) { Py_XDECREF(v); return NULL; } return v; } static PyObject * time_convert(double when, struct tm * (*function)(const time_t *)) { struct tm *p; time_t whent = _PyTime_DoubleToTimet(when); if (whent == (time_t)-1 && PyErr_Occurred()) return NULL; errno = 0; p = function(&whent); if (p == NULL) { #ifdef EINVAL if (errno == 0) errno = EINVAL; #endif return PyErr_SetFromErrno(PyExc_ValueError); } return tmtotuple(p); } /* Parse arg tuple that can contain an optional float-or-None value; format needs to be "|O:name". Returns non-zero on success (parallels PyArg_ParseTuple). */ static int parse_time_double_args(PyObject *args, char *format, double *pwhen) { PyObject *ot = NULL; if (!PyArg_ParseTuple(args, format, &ot)) return 0; if (ot == NULL || ot == Py_None) *pwhen = floattime(); else { double when = PyFloat_AsDouble(ot); if (PyErr_Occurred()) return 0; *pwhen = when; } return 1; } static PyObject * time_gmtime(PyObject *self, PyObject *args) { double when; if (!parse_time_double_args(args, "|O:gmtime", &when)) return NULL; return time_convert(when, gmtime); } PyDoc_STRVAR(gmtime_doc, "gmtime([seconds]) -> (tm_year, tm_mon, tm_day, tm_hour, tm_min,\n\ tm_sec, tm_wday, tm_yday, tm_isdst)\n\ \n\ Convert seconds since the Epoch to a time tuple expressing UTC (a.k.a.\n\ GMT). When 'seconds' is not passed in, convert the current time instead."); static PyObject * time_localtime(PyObject *self, PyObject *args) { double when; if (!parse_time_double_args(args, "|O:localtime", &when)) return NULL; return time_convert(when, localtime); } PyDoc_STRVAR(localtime_doc, "localtime([seconds]) -> (tm_year,tm_mon,tm_day,tm_hour,tm_min,tm_sec,tm_wday,tm_yday,tm_isdst)\n\ \n\ Convert seconds since the Epoch to a time tuple expressing local time.\n\ When 'seconds' is not passed in, convert the current time instead."); static int gettmarg(PyObject *args, struct tm *p) { int y; memset((void *) p, '\0', sizeof(struct tm)); if (!PyArg_Parse(args, "(iiiiiiiii)", &y, &p->tm_mon, &p->tm_mday, &p->tm_hour, &p->tm_min, &p->tm_sec, &p->tm_wday, &p->tm_yday, &p->tm_isdst)) return 0; if (y < 1900) { PyObject *accept = PyDict_GetItemString(moddict, "accept2dyear"); if (accept == NULL || !PyInt_Check(accept) || PyInt_AsLong(accept) == 0) { PyErr_SetString(PyExc_ValueError, "year >= 1900 required"); return 0; } if (69 <= y && y <= 99) y += 1900; else if (0 <= y && y <= 68) y += 2000; else { PyErr_SetString(PyExc_ValueError, "year out of range"); return 0; } } p->tm_year = y - 1900; p->tm_mon--; p->tm_wday = (p->tm_wday + 1) % 7; p->tm_yday--; return 1; } #ifdef HAVE_STRFTIME static PyObject * time_strftime(PyObject *self, PyObject *args) { PyObject *tup = NULL; struct tm buf; const char *fmt; size_t fmtlen, buflen; char *outbuf = 0; size_t i; memset((void *) &buf, '\0', sizeof(buf)); if (!PyArg_ParseTuple(args, "s|O:strftime", &fmt, &tup)) return NULL; if (tup == NULL) { time_t tt = time(NULL); buf = *localtime(&tt); } else if (!gettmarg(tup, &buf)) return NULL; /* Checks added to make sure strftime() does not crash Python by indexing blindly into some array for a textual representation by some bad index (fixes bug #897625). Also support values of zero from Python code for arguments in which that is out of range by forcing that value to the lowest value that is valid (fixed bug #1520914). Valid ranges based on what is allowed in struct tm: - tm_year: [0, max(int)] (1) - tm_mon: [0, 11] (2) - tm_mday: [1, 31] - tm_hour: [0, 23] - tm_min: [0, 59] - tm_sec: [0, 60] - tm_wday: [0, 6] (1) - tm_yday: [0, 365] (2) - tm_isdst: [-max(int), max(int)] (1) gettmarg() handles bounds-checking. (2) Python's acceptable range is one greater than the range in C, thus need to check against automatic decrement by gettmarg(). */ if (buf.tm_mon == -1) buf.tm_mon = 0; else if (buf.tm_mon < 0 || buf.tm_mon > 11) { PyErr_SetString(PyExc_ValueError, "month out of range"); return NULL; } if (buf.tm_mday == 0) buf.tm_mday = 1; else if (buf.tm_mday < 0 || buf.tm_mday > 31) { PyErr_SetString(PyExc_ValueError, "day of month out of range"); return NULL; } if (buf.tm_hour < 0 || buf.tm_hour > 23) { PyErr_SetString(PyExc_ValueError, "hour out of range"); return NULL; } if (buf.tm_min < 0 || buf.tm_min > 59) { PyErr_SetString(PyExc_ValueError, "minute out of range"); return NULL; } if (buf.tm_sec < 0 || buf.tm_sec > 61) { PyErr_SetString(PyExc_ValueError, "seconds out of range"); return NULL; } /* tm_wday does not need checking of its upper-bound since taking ``% 7`` in gettmarg() automatically restricts the range. */ if (buf.tm_wday < 0) { PyErr_SetString(PyExc_ValueError, "day of week out of range"); return NULL; } if (buf.tm_yday == -1) buf.tm_yday = 0; else if (buf.tm_yday < 0 || buf.tm_yday > 365) { PyErr_SetString(PyExc_ValueError, "day of year out of range"); return NULL; } if (buf.tm_isdst < -1 || buf.tm_isdst > 1) { PyErr_SetString(PyExc_ValueError, "daylight savings flag out of range"); return NULL; } fmtlen = strlen(fmt); /* I hate these functions that presume you know how big the output * will be ahead of time... */ for (i = 1024; ; i += i) { outbuf = (char *)malloc(i); if (outbuf == NULL) { return PyErr_NoMemory(); } buflen = strftime(outbuf, i, fmt, &buf); if (buflen > 0 || i >= 256 * fmtlen) { /* If the buffer is 256 times as long as the format, it's probably not failing for lack of room! More likely, the format yields an empty result, e.g. an empty format, or %Z when the timezone is unknown. */ PyObject *ret; ret = PyString_FromStringAndSize(outbuf, buflen); free(outbuf); return ret; } free(outbuf); #if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__) /* VisualStudio .NET 2005 does this properly */ if (buflen == 0 && errno == EINVAL) { PyErr_SetString(PyExc_ValueError, "Invalid format string"); return 0; }