Close #14180: Factorize code to convert a number of seconds to time_t, timeval or timespec

time.ctime(), gmtime(), time.localtime(), datetime.date.fromtimestamp(),
datetime.datetime.fromtimestamp() and datetime.datetime.utcfromtimestamp() now
raises an OverflowError, instead of a ValueError, if the timestamp does not fit
in time_t.

datetime.datetime.fromtimestamp() and datetime.datetime.utcfromtimestamp() now
round microseconds towards zero instead of rounding to nearest with ties going
away from zero.
diff --git a/Modules/selectmodule.c b/Modules/selectmodule.c
index 945055f..4d99250 100644
--- a/Modules/selectmodule.c
+++ b/Modules/selectmodule.c
@@ -206,9 +206,7 @@
     PyObject *ret = NULL;
     PyObject *tout = Py_None;
     fd_set ifdset, ofdset, efdset;
-    double timeout;
     struct timeval tv, *tvp;
-    long seconds;
     int imax, omax, emax, max;
     int n;
 
@@ -225,23 +223,12 @@
         return NULL;
     }
     else {
-        timeout = PyFloat_AsDouble(tout);
-        if (timeout == -1 && PyErr_Occurred())
+        if (_PyTime_ObjectToTimeval(tout, &tv.tv_sec, &tv.tv_usec) == -1)
             return NULL;
-        if (timeout > (double)LONG_MAX) {
-            PyErr_SetString(PyExc_OverflowError,
-                            "timeout period too long");
+        if (tv.tv_sec < 0) {
+            PyErr_SetString(PyExc_ValueError, "timeout must be non-negative");
             return NULL;
         }
-        if (timeout < 0) {
-            PyErr_SetString(PyExc_ValueError,
-                        "timeout must be non-negative");
-            return NULL;
-        }
-        seconds = (long)timeout;
-        timeout = timeout - (double)seconds;
-        tv.tv_sec = seconds;
-        tv.tv_usec = (long)(timeout * 1E6);
         tvp = &tv;
     }
 
@@ -1870,27 +1857,15 @@
         ptimeoutspec = NULL;
     }
     else if (PyNumber_Check(otimeout)) {
-        double timeout;
-        long seconds;
+        if (_PyTime_ObjectToTimespec(otimeout,
+                                     &timeout.tv_sec, &timeout.tv_nsec) == -1)
+            return NULL;
 
-        timeout = PyFloat_AsDouble(otimeout);
-        if (timeout == -1 && PyErr_Occurred())
-            return NULL;
-        if (timeout > (double)LONG_MAX) {
-            PyErr_SetString(PyExc_OverflowError,
-                            "timeout period too long");
-            return NULL;
-        }
-        if (timeout < 0) {
+        if (timeout.tv_sec < 0) {
             PyErr_SetString(PyExc_ValueError,
                             "timeout must be positive or None");
             return NULL;
         }
-
-        seconds = (long)timeout;
-        timeout = timeout - (double)seconds;
-        timeoutspec.tv_sec = seconds;
-        timeoutspec.tv_nsec = (long)(timeout * 1E9);
         ptimeoutspec = &timeoutspec;
     }
     else {