home *** CD-ROM | disk | FTP | other *** search
/ linuxmafia.com 2016 / linuxmafia.com.tar / linuxmafia.com / pub / palmos / pippy-0.6beta-src.tar.gz / pippy-0.6beta-src.tar / pippy-0.6beta-src / src / Modules / timemodule.c < prev    next >
C/C++ Source or Header  |  2000-12-21  |  22KB  |  863 lines

  1. /***********************************************************
  2. Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam,
  3. The Netherlands.
  4.  
  5.                         All Rights Reserved
  6.  
  7. Permission to use, copy, modify, and distribute this software and its
  8. documentation for any purpose and without fee is hereby granted,
  9. provided that the above copyright notice appear in all copies and that
  10. both that copyright notice and this permission notice appear in
  11. supporting documentation, and that the names of Stichting Mathematisch
  12. Centrum or CWI or Corporation for National Research Initiatives or
  13. CNRI not be used in advertising or publicity pertaining to
  14. distribution of the software without specific, written prior
  15. permission.
  16.  
  17. While CWI is the initial source for this software, a modified version
  18. is made available by the Corporation for National Research Initiatives
  19. (CNRI) at the Internet address ftp://ftp.python.org.
  20.  
  21. STICHTING MATHEMATISCH CENTRUM AND CNRI DISCLAIM ALL WARRANTIES WITH
  22. REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF
  23. MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH
  24. CENTRUM OR CNRI BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL
  25. DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
  26. PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  27. TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  28. PERFORMANCE OF THIS SOFTWARE.
  29.  
  30. ******************************************************************/
  31.  
  32. /* Time module */
  33.  
  34. #include "Python.h"
  35.  
  36. #include <ctype.h>
  37.  
  38. #ifdef HAVE_SELECT
  39. #include "mymath.h"
  40. #endif
  41.  
  42. #ifdef macintosh
  43. #include <time.h>
  44. #else
  45. #include <sys/types.h>
  46. #endif
  47.  
  48. #ifdef QUICKWIN
  49. #include <io.h>
  50. #endif
  51.  
  52. #ifdef HAVE_UNISTD_H
  53. #include <unistd.h>
  54. #endif
  55.  
  56. #if defined(HAVE_SELECT) && !defined(__BEOS__)
  57. #include "myselect.h"
  58. #else
  59. #include "mytime.h"
  60. #endif
  61.  
  62. #ifdef HAVE_FTIME
  63. #include <sys/timeb.h>
  64. #if !defined(MS_WINDOWS) && !defined(PYOS_OS2)
  65. extern int ftime();
  66. #endif /* MS_WINDOWS */
  67. #endif /* HAVE_FTIME */
  68.  
  69. #if defined(__WATCOMC__) && !defined(__QNX__)
  70. #include <i86.h>
  71. #else
  72. #ifdef MS_WINDOWS
  73. #include <windows.h>
  74. #ifdef MS_WIN16
  75. /* These overrides not needed for Win32 */
  76. #define timezone _timezone
  77. #define tzname _tzname
  78. #define daylight _daylight
  79. #define altzone _altzone
  80. #endif /* MS_WIN16 */
  81. #endif /* MS_WINDOWS */
  82. #endif /* !__WATCOMC__ || __QNX__ */
  83.  
  84. #ifdef MS_WIN32
  85. /* Win32 has better clock replacement */
  86. #include <largeint.h>
  87. #undef HAVE_CLOCK /* We have our own version down below */
  88. #endif /* MS_WIN32 */
  89.  
  90. #if defined(PYCC_VACPP)
  91. #include <sys/time.h>
  92. #endif
  93.  
  94. #ifdef __BEOS__
  95. /* For bigtime_t, snooze(). - [cjh] */
  96. #include <support/SupportDefs.h>
  97. #include <kernel/OS.h>
  98. #ifndef CLOCKS_PER_SEC
  99. /* C'mon, fix the bloody headers... - [cjh] */
  100. #define CLOCKS_PER_SEC 1000
  101. #endif
  102. #endif
  103.  
  104. /* Forward declarations */
  105. static int floatsleep Py_PROTO((double));
  106. static double floattime Py_PROTO(());
  107.  
  108. /* For Y2K check */
  109. static PyObject *moddict;
  110.  
  111. #ifdef macintosh
  112. /* Our own timezone. We have enough information to deduce whether
  113. ** DST is on currently, but unfortunately we cannot put it to good
  114. ** use because we don't know the rules (and that is needed to have
  115. ** localtime() return correct tm_isdst values for times other than
  116. ** the current time. So, we cop out and only tell the user the current
  117. ** timezone.
  118. */
  119. static long timezone;
  120.  
  121. static void 
  122. initmactimezone()
  123. {
  124.     MachineLocation    loc;
  125.     long        delta;
  126.  
  127.     ReadLocation(&loc);
  128.     
  129.     if (loc.latitude == 0 && loc.longitude == 0 && loc.u.gmtDelta == 0)
  130.         return;
  131.     
  132.     delta = loc.u.gmtDelta & 0x00FFFFFF;
  133.     
  134.     if (delta & 0x00800000)
  135.         delta |= 0xFF000000;
  136.     
  137.     timezone = -delta;
  138. }
  139. #endif /* macintosh */
  140.  
  141.  
  142. static PyObject *
  143. time_time(self, args)
  144.     PyObject *self;
  145.     PyObject *args;
  146. {
  147.     double secs;
  148.     if (!PyArg_NoArgs(args))
  149.         return NULL;
  150.     secs = floattime();
  151.     if (secs == 0.0) {
  152.         PyErr_SetFromErrno(PyExc_IOError);
  153.         return NULL;
  154.     }
  155.     return PyFloat_FromDouble(secs);
  156. }
  157.  
  158. static char time_doc[] =
  159. "time() -> floating point number\n\
  160. \n\
  161. Return the current time in seconds since the Epoch.\n\
  162. Fractions of a second may be present if the system clock provides them.";
  163.  
  164. #ifdef HAVE_CLOCK
  165.  
  166. #ifndef CLOCKS_PER_SEC
  167. #ifdef CLK_TCK
  168. #define CLOCKS_PER_SEC CLK_TCK
  169. #else
  170. #define CLOCKS_PER_SEC 1000000
  171. #endif
  172. #endif
  173.  
  174. static PyObject *
  175. time_clock(self, args)
  176.     PyObject *self;
  177.     PyObject *args;
  178. {
  179.     if (!PyArg_NoArgs(args))
  180.         return NULL;
  181.     return PyFloat_FromDouble(((double)clock()) / CLOCKS_PER_SEC);
  182. }
  183. #endif /* HAVE_CLOCK */
  184.  
  185. #ifdef MS_WIN32
  186. /* Due to Mark Hammond */
  187. static PyObject *
  188. time_clock(self, args)
  189.     PyObject *self;
  190.     PyObject *args;
  191. {
  192.     static LARGE_INTEGER ctrStart;
  193.     static LARGE_INTEGER divisor = {0,0};
  194.     LARGE_INTEGER now, diff, rem;
  195.  
  196.     if (!PyArg_NoArgs(args))
  197.         return NULL;
  198.  
  199.     if (LargeIntegerEqualToZero(divisor)) {
  200.         QueryPerformanceCounter(&ctrStart);
  201.         if (!QueryPerformanceFrequency(&divisor) || 
  202.             LargeIntegerEqualToZero(divisor)) {
  203.                 /* Unlikely to happen - 
  204.                    this works on all intel machines at least! 
  205.                    Revert to clock() */
  206.             return PyFloat_FromDouble(clock());
  207.         }
  208.     }
  209.     QueryPerformanceCounter(&now);
  210.     diff = LargeIntegerSubtract(now, ctrStart);
  211.     diff = LargeIntegerDivide(diff, divisor, &rem);
  212.     /* XXX - we assume both divide results fit in 32 bits.  This is
  213.        true on Intels.  First person who can afford a machine that 
  214.        doesnt deserves to fix it :-)
  215.     */
  216.     return PyFloat_FromDouble((double)diff.LowPart + 
  217.                       ((double)rem.LowPart / (double)divisor.LowPart));
  218. }
  219.  
  220. #define HAVE_CLOCK /* So it gets included in the methods */
  221. #endif /* MS_WIN32 */
  222.  
  223. #ifdef HAVE_CLOCK
  224. static char clock_doc[] =
  225. "clock() -> floating point number\n\
  226. \n\
  227. Return the CPU time or real time since the start of the process or since\n\
  228. the first call to clock().  This has as much precision as the system records.";
  229. #endif
  230.  
  231. static PyObject *
  232. time_sleep(self, args)
  233.     PyObject *self;
  234.     PyObject *args;
  235. {
  236.     double secs;
  237.     if (!PyArg_Parse(args, "d", &secs))
  238.         return NULL;
  239.     if (floatsleep(secs) != 0)
  240.         return NULL;
  241.     Py_INCREF(Py_None);
  242.     return Py_None;
  243. }
  244.  
  245. static char sleep_doc[] =
  246. "sleep(seconds)\n\
  247. \n\
  248. Delay execution for a given number of seconds.  The argument may be\n\
  249. a floating point number for subsecond precision.";
  250.  
  251. static PyObject *
  252. tmtotuple(p)
  253.     struct tm *p;
  254. {
  255.     return Py_BuildValue("(iiiiiiiii)",
  256.                  p->tm_year + 1900,
  257.                  p->tm_mon + 1,       /* Want January == 1 */
  258.                  p->tm_mday,
  259.                  p->tm_hour,
  260.                  p->tm_min,
  261.                  p->tm_sec,
  262.                  (p->tm_wday + 6) % 7, /* Want Monday == 0 */
  263.                  p->tm_yday + 1,       /* Want January, 1 == 1 */
  264.                  p->tm_isdst);
  265. }
  266.  
  267. static PyObject *
  268. time_convert(when, function)
  269.     time_t when;
  270.     struct tm * (*function) Py_PROTO((const time_t *));
  271. {
  272.     struct tm *p;
  273.     errno = 0;
  274.     p = function(&when);
  275.     if (p == NULL) {
  276. #ifdef EINVAL
  277.         if (errno == 0)
  278.             errno = EINVAL;
  279. #endif
  280.         return PyErr_SetFromErrno(PyExc_IOError);
  281.     }
  282.     return tmtotuple(p);
  283. }
  284.  
  285. static PyObject *
  286. time_gmtime(self, args)
  287.     PyObject *self;
  288.     PyObject *args;
  289. {
  290.     double when;
  291.     if (!PyArg_Parse(args, "d", &when))
  292.         return NULL;
  293.     return time_convert((time_t)when, gmtime);
  294. }
  295.  
  296. static char gmtime_doc[] =
  297. "gmtime(seconds) -> tuple\n\
  298. \n\
  299. Convert seconds since the Epoch to a time tuple expressing UTC (a.k.a. GMT).";
  300.  
  301. static PyObject *
  302. time_localtime(self, args)
  303.     PyObject *self;
  304.     PyObject *args;
  305. {
  306.     double when;
  307.     if (!PyArg_Parse(args, "d", &when))
  308.         return NULL;
  309.     return time_convert((time_t)when, localtime);
  310. }
  311.  
  312. static char localtime_doc[] =
  313. "localtime(seconds) -> tuple\n\
  314. Convert seconds since the Epoch to a time tuple expressing local time.";
  315.  
  316. static int
  317. gettmarg(args, p)
  318.     PyObject *args;
  319.     struct tm *p;
  320. {
  321.     int y;
  322.     memset((ANY *) p, '\0', sizeof(struct tm));
  323.  
  324.     if (!PyArg_Parse(args, "(iiiiiiiii)",
  325.              &y,
  326.              &p->tm_mon,
  327.              &p->tm_mday,
  328.              &p->tm_hour,
  329.              &p->tm_min,
  330.              &p->tm_sec,
  331.              &p->tm_wday,
  332.              &p->tm_yday,
  333.              &p->tm_isdst))
  334.         return 0;
  335.     if (y < 1900) {
  336.         PyObject *accept = PyDict_GetItemString(moddict,
  337.                             "accept2dyear");
  338.         if (accept == NULL || !PyInt_Check(accept) ||
  339.             PyInt_AsLong(accept) == 0) {
  340.             PyErr_SetString(PyExc_ValueError,
  341.                     "year >= 1900 required");
  342.             return 0;
  343.         }
  344.         if (69 <= y && y <= 99)
  345.             y += 1900;
  346.         else if (0 <= y && y <= 68)
  347.             y += 2000;
  348.         else {
  349.             PyErr_SetString(PyExc_ValueError,
  350.                     "year out of range (00-99, 1900-*)");
  351.             return 0;
  352.         }
  353.     }
  354.     p->tm_year = y - 1900;
  355.     p->tm_mon--;
  356.     p->tm_wday = (p->tm_wday + 1) % 7;
  357.     p->tm_yday--;
  358.     return 1;
  359. }
  360.  
  361. #ifdef HAVE_STRFTIME
  362. static PyObject *
  363. time_strftime(self, args)
  364.     PyObject *self;
  365.     PyObject *args;
  366. {
  367.     PyObject *tup;
  368.     struct tm buf;
  369.     const char *fmt;
  370.     int fmtlen, buflen;
  371.     char *outbuf = 0;
  372.     int i;
  373.  
  374.     memset((ANY *) &buf, '\0', sizeof(buf));
  375.  
  376.     if (!PyArg_ParseTuple(args, "sO:strftime", &fmt, &tup) || !gettmarg(tup, &buf))
  377.         return NULL;
  378.     fmtlen = strlen(fmt);
  379.  
  380.     /* I hate these functions that presume you know how big the output
  381.      * will be ahead of time...
  382.      */
  383.     for (i = 1024; ; i += i) {
  384.         outbuf = malloc(i);
  385.         if (outbuf == NULL) {
  386.             return PyErr_NoMemory();
  387.         }
  388.         buflen = strftime(outbuf, i, fmt, &buf);
  389.         if (buflen > 0 || i >= 256 * fmtlen) {
  390.             /* If the buffer is 256 times as long as the format,
  391.                it's probably not failing for lack of room!
  392.                More likely, the format yields an empty result,
  393.                e.g. an empty format, or %Z when the timezone
  394.                is unknown. */
  395.             PyObject *ret;
  396.             ret = PyString_FromStringAndSize(outbuf, buflen);
  397.             free(outbuf);
  398.             return ret;
  399.         }
  400.         free(outbuf);
  401.     }
  402. }
  403.  
  404. static char strftime_doc[] =
  405. "strftime(format, tuple) -> string\n\
  406. \n\
  407. Convert a time tuple to a string according to a format specification.\n\
  408. See the library reference manual for formatting codes.";
  409. #endif /* HAVE_STRFTIME */
  410.  
  411. #ifdef HAVE_STRPTIME
  412. /* extern char *strptime(); /* Enable this if it's not declared in <time.h> */
  413.  
  414. static PyObject *
  415. time_strptime(self, args)
  416.     PyObject *self;
  417.     PyObject *args;
  418. {
  419.     struct tm tm;
  420.     char *fmt = "%a %b %d %H:%M:%S %Y";
  421.     char *buf;
  422.     char *s;
  423.  
  424.     if (!PyArg_ParseTuple(args, "s|s:strptime", &buf, &fmt)) {
  425.         PyErr_SetString(PyExc_ValueError, "invalid argument");
  426.         return NULL;
  427.     }
  428.     memset((ANY *) &tm, '\0', sizeof(tm));
  429.     s = strptime(buf, fmt, &tm);
  430.     if (s == NULL) {
  431.         PyErr_SetString(PyExc_ValueError, "format mismatch");
  432.         return NULL;
  433.     }
  434.     while (*s && isspace(*s))
  435.         s++;
  436.     if (*s) {
  437.         PyErr_Format(PyExc_ValueError,
  438.                  "unconverted data remains: '%.400s'", s);
  439.         return NULL;
  440.     }
  441.     return tmtotuple(&tm);
  442. }
  443.  
  444. static char strptime_doc[] =
  445. "strptime(string, format) -> tuple\n\
  446. Parse a string to a time tuple according to a format specification.\n\
  447. See the library reference manual for formatting codes (same as strftime()).";
  448. #endif /* HAVE_STRPTIME */
  449.  
  450. static PyObject *
  451. time_asctime(self, args)
  452.     PyObject *self;
  453.     PyObject *args;
  454. {
  455.     PyObject *tup;
  456.     struct tm buf;
  457.     char *p;
  458.     if (!PyArg_ParseTuple(args, "O:asctime", &tup))
  459.         return NULL;
  460.     if (!gettmarg(tup, &buf))
  461.         return NULL;
  462.     p = asctime(&buf);
  463.     if (p[24] == '\n')
  464.         p[24] = '\0';
  465.     return PyString_FromString(p);
  466. }
  467.  
  468. static char asctime_doc[] =
  469. "asctime(tuple) -> string\n\
  470. \n\
  471. Convert a time tuple to a string, e.g. 'Sat Jun 06 16:26:11 1998'.";
  472.  
  473. static PyObject *
  474. time_ctime(self, args)
  475.     PyObject *self;
  476.     PyObject *args;
  477. {
  478.     double dt;
  479.     time_t tt;
  480.     char *p;
  481.     if (!PyArg_Parse(args, "d", &dt))
  482.         return NULL;
  483.     tt = (time_t)dt;
  484.     p = ctime(&tt);
  485.     if (p == NULL) {
  486.         PyErr_SetString(PyExc_ValueError, "unconvertible time");
  487.         return NULL;
  488.     }
  489.     if (p[24] == '\n')
  490.         p[24] = '\0';
  491.     return PyString_FromString(p);
  492. }
  493.  
  494. static char ctime_doc[] =
  495. "ctime(seconds) -> string\n\
  496. \n\
  497. Convert a time in seconds since the Epoch to a string in local time.\n\
  498. This is equivalent to asctime(localtime(seconds)).";
  499.  
  500. #ifdef HAVE_MKTIME
  501. static PyObject *
  502. time_mktime(self, args)
  503.     PyObject *self;
  504.     PyObject *args;
  505. {
  506.     PyObject *tup;
  507.     struct tm buf;
  508.     time_t tt;
  509.     if (!PyArg_ParseTuple(args, "O:mktime", &tup))
  510.         return NULL;
  511.     tt = time(&tt);
  512.     buf = *localtime(&tt);
  513.     if (!gettmarg(tup, &buf))
  514.         return NULL;
  515.     tt = mktime(&buf);
  516.     if (tt == (time_t)(-1)) {
  517.         PyErr_SetString(PyExc_OverflowError,
  518.                                 "mktime argument out of range");
  519.         return NULL;
  520.     }
  521.     return PyFloat_FromDouble((double)tt);
  522. }
  523.  
  524. static char mktime_doc[] =
  525. "mktime(tuple) -> floating point number\n\
  526. \n\
  527. Convert a time tuple in local time to seconds since the Epoch.";
  528. #endif /* HAVE_MKTIME */
  529.  
  530. static PyMethodDef time_methods[] = {
  531.     {"time",    time_time, 0, time_doc},
  532. #ifdef HAVE_CLOCK
  533.     {"clock",    time_clock, 0, clock_doc},
  534. #endif
  535.     {"sleep",    time_sleep, 0, sleep_doc},
  536.     {"gmtime",    time_gmtime, 0, gmtime_doc},
  537.     {"localtime",    time_localtime, 0, localtime_doc},
  538.     {"asctime",    time_asctime, 1, asctime_doc},
  539.     {"ctime",    time_ctime, 0, ctime_doc},
  540. #ifdef HAVE_MKTIME
  541.     {"mktime",    time_mktime, 1, mktime_doc},
  542. #endif
  543. #ifdef HAVE_STRFTIME
  544.     {"strftime",    time_strftime, 1, strftime_doc},
  545. #endif
  546. #ifdef HAVE_STRPTIME
  547.     {"strptime",    time_strptime, 1, strptime_doc},
  548. #endif
  549.     {NULL,        NULL}        /* sentinel */
  550. };
  551.  
  552. static void
  553. ins(d, name, v)
  554.     PyObject *d;
  555.     char *name;
  556.     PyObject *v;
  557. {
  558.     if (v == NULL)
  559.         Py_FatalError("Can't initialize time module -- NULL value");
  560.     if (PyDict_SetItemString(d, name, v) != 0)
  561.         Py_FatalError(
  562.         "Can't initialize time module -- PyDict_SetItemString failed");
  563.     Py_DECREF(v);
  564. }
  565.  
  566. static char module_doc[] =
  567. "This module provides various functions to manipulate time values.\n\
  568. \n\
  569. There are two standard representations of time.  One is the number\n\
  570. of seconds since the Epoch, in UTC (a.k.a. GMT).  It may be an integer\n\
  571. or a floating point number (to represent fractions of seconds).\n\
  572. The Epoch is system-defined; on Unix, it is generally January 1st, 1970.\n\
  573. The actual value can be retrieved by calling gmtime(0).\n\
  574. \n\
  575. The other representation is a tuple of 9 integers giving local time.\n\
  576. The tuple items are:\n\
  577.   year (four digits, e.g. 1998)\n\
  578.   month (1-12)\n\
  579.   day (1-31)\n\
  580.   hours (0-23)\n\
  581.   minutes (0-59)\n\
  582.   seconds (0-59)\n\
  583.   weekday (0-6, Monday is 0)\n\
  584.   Julian day (day in the year, 1-366)\n\
  585.   DST (Daylight Savings Time) flag (-1, 0 or 1)\n\
  586. If the DST flag is 0, the time is given in the regular time zone;\n\
  587. if it is 1, the time is given in the DST time zone;\n\
  588. if it is -1, mktime() should guess based on the date and time.\n\
  589. \n\
  590. Variables:\n\
  591. \n\
  592. timezone -- difference in seconds between UTC and local standard time\n\
  593. altzone -- difference in  seconds between UTC and local DST time\n\
  594. daylight -- whether local time should reflect DST\n\
  595. tzname -- tuple of (standard time zone name, DST time zone name)\n\
  596. \n\
  597. Functions:\n\
  598. \n\
  599. time() -- return current time in seconds since the Epoch as a float\n\
  600. clock() -- return CPU time since process start as a float\n\
  601. sleep() -- delay for a number of seconds given as a float\n\
  602. gmtime() -- convert seconds since Epoch to UTC tuple\n\
  603. localtime() -- convert seconds since Epoch to local time tuple\n\
  604. asctime() -- convert time tuple to string\n\
  605. ctime() -- convert time in seconds to string\n\
  606. mktime() -- convert local time tuple to seconds since Epoch\n\
  607. strftime() -- convert time tuple to string according to format specification\n\
  608. strptime() -- parse string to time tuple according to format specification\n\
  609. ";
  610.   
  611.  
  612. DL_EXPORT(void)
  613. inittime()
  614. {
  615.     PyObject *m, *d;
  616.     char *p;
  617.     m = Py_InitModule3("time", time_methods, module_doc);
  618.     d = PyModule_GetDict(m);
  619.     /* Accept 2-digit dates unless PYTHONY2K is set and non-empty */
  620.     p = getenv("PYTHONY2K");
  621.     ins(d, "accept2dyear", PyInt_FromLong((long) (!p || !*p)));
  622.     /* Squirrel away the module's dictionary for the y2k check */
  623.     Py_INCREF(d);
  624.     moddict = d;
  625. #if defined(HAVE_TZNAME) && !defined(__GLIBC__)
  626.     tzset();
  627. #ifdef PYOS_OS2
  628.     ins(d, "timezone", PyInt_FromLong((long)_timezone));
  629. #else /* !PYOS_OS2 */
  630.     ins(d, "timezone", PyInt_FromLong((long)timezone));
  631. #endif /* PYOS_OS2 */
  632. #ifdef HAVE_ALTZONE
  633.     ins(d, "altzone", PyInt_FromLong((long)altzone));
  634. #else
  635. #ifdef PYOS_OS2
  636.     ins(d, "altzone", PyInt_FromLong((long)_timezone-3600));
  637. #else /* !PYOS_OS2 */
  638.     ins(d, "altzone", PyInt_FromLong((long)timezone-3600));
  639. #endif /* PYOS_OS2 */
  640. #endif
  641.     ins(d, "daylight", PyInt_FromLong((long)daylight));
  642.     ins(d, "tzname", Py_BuildValue("(zz)", tzname[0], tzname[1]));
  643. #else /* !HAVE_TZNAME || __GLIBC__ */
  644. #ifdef HAVE_TM_ZONE
  645.     {
  646. #define YEAR ((time_t)((365 * 24 + 6) * 3600))
  647.         time_t t;
  648.         struct tm *p;
  649.         long janzone, julyzone;
  650.         char janname[10], julyname[10];
  651.         t = (time((time_t *)0) / YEAR) * YEAR;
  652.         p = localtime(&t);
  653.         janzone = -p->tm_gmtoff;
  654.         strncpy(janname, p->tm_zone ? p->tm_zone : "   ", 9);
  655.         janname[9] = '\0';
  656.         t += YEAR/2;
  657.         p = localtime(&t);
  658.         julyzone = -p->tm_gmtoff;
  659.         strncpy(julyname, p->tm_zone ? p->tm_zone : "   ", 9);
  660.         julyname[9] = '\0';
  661.         
  662.         if( janzone < julyzone ) {
  663.             /* DST is reversed in the southern hemisphere */
  664.             ins(d, "timezone", PyInt_FromLong(julyzone));
  665.             ins(d, "altzone", PyInt_FromLong(janzone));
  666.             ins(d, "daylight",
  667.                 PyInt_FromLong((long)(janzone != julyzone)));
  668.             ins(d, "tzname",
  669.                 Py_BuildValue("(zz)", julyname, janname));
  670.         } else {
  671.             ins(d, "timezone", PyInt_FromLong(janzone));
  672.             ins(d, "altzone", PyInt_FromLong(julyzone));
  673.             ins(d, "daylight",
  674.                 PyInt_FromLong((long)(janzone != julyzone)));
  675.             ins(d, "tzname",
  676.                 Py_BuildValue("(zz)", janname, julyname));
  677.         }
  678.     }
  679. #else
  680. #ifdef macintosh
  681.     /* The only thing we can obtain is the current timezone
  682.     ** (and whether dst is currently _active_, but that is not what
  683.     ** we're looking for:-( )
  684.     */
  685.     initmactimezone();
  686.     ins(d, "timezone", PyInt_FromLong(timezone));
  687.     ins(d, "altzone", PyInt_FromLong(timezone));
  688.     ins(d, "daylight", PyInt_FromLong((long)0));
  689.     ins(d, "tzname", Py_BuildValue("(zz)", "", ""));
  690. #endif /* macintosh */
  691. #endif /* HAVE_TM_ZONE */
  692. #endif /* !HAVE_TZNAME || __GLIBC__ */
  693.     if (PyErr_Occurred())
  694.         Py_FatalError("Can't initialize time module");
  695. }
  696.  
  697.  
  698. /* Implement floattime() for various platforms */
  699.  
  700. static double
  701. floattime()
  702. {
  703.     /* There are three ways to get the time:
  704.       (1) gettimeofday() -- resolution in microseconds
  705.       (2) ftime() -- resolution in milliseconds
  706.       (3) time() -- resolution in seconds
  707.       In all cases the return value is a float in seconds.
  708.       Since on some systems (e.g. SCO ODT 3.0) gettimeofday() may
  709.       fail, so we fall back on ftime() or time().
  710.       Note: clock resolution does not imply clock accuracy! */
  711. #ifdef HAVE_GETTIMEOFDAY
  712.     {
  713.         struct timeval t;
  714. #ifdef GETTIMEOFDAY_NO_TZ
  715.         if (gettimeofday(&t) == 0)
  716.             return (double)t.tv_sec + t.tv_usec*0.000001;
  717. #else /* !GETTIMEOFDAY_NO_TZ */
  718.         if (gettimeofday(&t, (struct timezone *)NULL) == 0)
  719.             return (double)t.tv_sec + t.tv_usec*0.000001;
  720. #endif /* !GETTIMEOFDAY_NO_TZ */
  721.     }
  722. #endif /* !HAVE_GETTIMEOFDAY */
  723.     {
  724. #if defined(HAVE_FTIME)
  725.         struct timeb t;
  726.         ftime(&t);
  727.         return (double)t.time + (double)t.millitm * (double)0.001;
  728. #else /* !HAVE_FTIME */
  729.         time_t secs;
  730.         time(&secs);
  731.         return (double)secs;
  732. #endif /* !HAVE_FTIME */
  733.     }
  734. }
  735.  
  736.  
  737. /* Implement floatsleep() for various platforms.
  738.    When interrupted (or when another error occurs), return -1 and
  739.    set an exception; else return 0. */
  740.  
  741. static int
  742. #ifdef MPW
  743. floatsleep(double secs)
  744. #else
  745.     floatsleep(secs)
  746.     double secs;
  747. #endif /* MPW */
  748. {
  749. /* XXX Should test for MS_WIN32 first! */
  750. #if defined(HAVE_SELECT) && !defined(__BEOS__)
  751.     struct timeval t;
  752.     double frac;
  753.     frac = fmod(secs, 1.0);
  754.     secs = floor(secs);
  755.     t.tv_sec = (long)secs;
  756.     t.tv_usec = (long)(frac*1000000.0);
  757.     Py_BEGIN_ALLOW_THREADS
  758.     if (select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &t) != 0) {
  759.         Py_BLOCK_THREADS
  760. #ifdef EINTR
  761.         if (errno != EINTR) {
  762. #else
  763.         if (1) {
  764. #endif
  765.             PyErr_SetFromErrno(PyExc_IOError);
  766.             return -1;
  767.         }
  768.     }
  769.     Py_END_ALLOW_THREADS
  770. #else /* !HAVE_SELECT || __BEOS__ */
  771. #ifdef macintosh
  772. #define MacTicks    (* (long *)0x16A)
  773.     long deadline;
  774.     deadline = MacTicks + (long)(secs * 60.0);
  775.     while (MacTicks < deadline) {
  776.         /* XXX Should call some yielding function here */
  777.         if (PyErr_CheckSignals())
  778.             return -1;
  779.     }
  780. #else /* !macintosh */
  781. #if defined(__WATCOMC__) && !defined(__QNX__)
  782.     /* XXX Can't interrupt this sleep */
  783.     Py_BEGIN_ALLOW_THREADS
  784.     delay((int)(secs * 1000 + 0.5));  /* delay() uses milliseconds */
  785.     Py_END_ALLOW_THREADS
  786. #else /* !__WATCOMC__ || __QNX__ */
  787. #ifdef MSDOS
  788.     struct timeb t1, t2;
  789.     double frac;
  790.     extern double fmod Py_PROTO((double, double));
  791.     extern double floor Py_PROTO((double));
  792.     if (secs <= 0.0)
  793.         return;
  794.     frac = fmod(secs, 1.0);
  795.     secs = floor(secs);
  796.     ftime(&t1);
  797.     t2.time = t1.time + (int)secs;
  798.     t2.millitm = t1.millitm + (int)(frac*1000.0);
  799.     while (t2.millitm >= 1000) {
  800.         t2.time++;
  801.         t2.millitm -= 1000;
  802.     }
  803.     for (;;) {
  804. #ifdef QUICKWIN
  805.         Py_BEGIN_ALLOW_THREADS
  806.         _wyield();
  807.         Py_END_ALLOW_THREADS
  808. #endif
  809.         if (PyErr_CheckSignals())
  810.             return -1;
  811.         ftime(&t1);
  812.         if (t1.time > t2.time ||
  813.             t1.time == t2.time && t1.millitm >= t2.millitm)
  814.             break;
  815.     }
  816. #else /* !MSDOS */
  817. #ifdef MS_WIN32
  818.     /* XXX Can't interrupt this sleep */
  819.     Py_BEGIN_ALLOW_THREADS
  820.     Sleep((int)(secs*1000));
  821.     Py_END_ALLOW_THREADS
  822. #else /* !MS_WIN32 */
  823. #ifdef PYOS_OS2
  824.     /* This Sleep *IS* Interruptable by Exceptions */
  825.     Py_BEGIN_ALLOW_THREADS
  826.     if (DosSleep(secs * 1000) != NO_ERROR) {
  827.         Py_BLOCK_THREADS
  828.         PyErr_SetFromErrno(PyExc_IOError);
  829.         return -1;
  830.     }
  831.     Py_END_ALLOW_THREADS
  832. #else /* !PYOS_OS2 */
  833. #ifdef __BEOS__
  834.     /* This sleep *CAN BE* interrupted. */
  835.     {
  836.         if( secs <= 0.0 ) {
  837.             return;
  838.         }
  839.         
  840.         Py_BEGIN_ALLOW_THREADS
  841.         /* BeOS snooze() is in microseconds... */
  842.         if( snooze( (bigtime_t)( secs * 1000.0 * 1000.0 ) ) == B_INTERRUPTED ) {
  843.             Py_BLOCK_THREADS
  844.             PyErr_SetFromErrno( PyExc_IOError );
  845.             return -1;
  846.         }
  847.         Py_END_ALLOW_THREADS
  848.     }
  849. #else /* !__BEOS__ */
  850.     /* XXX Can't interrupt this sleep */
  851.     Py_BEGIN_ALLOW_THREADS
  852.     sleep((int)secs);
  853.     Py_END_ALLOW_THREADS
  854. #endif /* !__BEOS__ */
  855. #endif /* !PYOS_OS2 */
  856. #endif /* !MS_WIN32 */
  857. #endif /* !MSDOS */
  858. #endif /* !__WATCOMC__ || __QNX__ */
  859. #endif /* !macintosh */
  860. #endif /* !HAVE_SELECT */
  861.     return 0;
  862. }
  863.