Skip to content

Commit fa09beb

Browse files
committed
Issue python#23485: Add _PyTime_FromMillisecondsObject() function
1 parent 749a6a8 commit fa09beb

2 files changed

Lines changed: 25 additions & 6 deletions

File tree

Include/pytime.h

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,12 +69,18 @@ PyAPI_FUNC(int) _PyTime_ObjectToTimespec(
6969
/* Create a timestamp from a number of nanoseconds (C long). */
7070
PyAPI_FUNC(_PyTime_t) _PyTime_FromNanoseconds(PY_LONG_LONG ns);
7171

72-
/* Convert a Python float or int to a timetamp.
72+
/* Convert a number of seconds (Python float or int) to a timetamp.
7373
Raise an exception and return -1 on error, return 0 on success. */
7474
PyAPI_FUNC(int) _PyTime_FromSecondsObject(_PyTime_t *t,
7575
PyObject *obj,
7676
_PyTime_round_t round);
7777

78+
/* Convert a number of milliseconds (Python float or int, 10^-3) to a timetamp.
79+
Raise an exception and return -1 on error, return 0 on success. */
80+
PyAPI_FUNC(int) _PyTime_FromMillisecondsObject(_PyTime_t *t,
81+
PyObject *obj,
82+
_PyTime_round_t round);
83+
7884
/* Convert a timestamp to a number of seconds as a C double. */
7985
PyAPI_FUNC(double) _PyTime_AsSecondsDouble(_PyTime_t t);
8086

Python/pytime.c

Lines changed: 18 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -203,16 +203,17 @@ _PyTime_FromTimeval(_PyTime_t *tp, struct timeval *tv, int raise)
203203
}
204204
#endif
205205

206-
int
207-
_PyTime_FromSecondsObject(_PyTime_t *t, PyObject *obj, _PyTime_round_t round)
206+
static int
207+
_PyTime_FromObject(_PyTime_t *t, PyObject *obj, _PyTime_round_t round,
208+
long to_nanoseconds)
208209
{
209210
if (PyFloat_Check(obj)) {
210211
/* volatile avoids unsafe optimization on float enabled by gcc -O3 */
211212
volatile double d, err;
212213

213214
/* convert to a number of nanoseconds */
214215
d = PyFloat_AsDouble(obj);
215-
d *= 1e9;
216+
d *= to_nanoseconds;
216217

217218
if (round == _PyTime_ROUND_CEILING)
218219
d = ceil(d);
@@ -242,15 +243,27 @@ _PyTime_FromSecondsObject(_PyTime_t *t, PyObject *obj, _PyTime_round_t round)
242243
_PyTime_overflow();
243244
return -1;
244245
}
245-
*t = sec * SEC_TO_NS;
246-
if (*t / SEC_TO_NS != sec) {
246+
*t = sec * to_nanoseconds;
247+
if (*t / to_nanoseconds != sec) {
247248
_PyTime_overflow();
248249
return -1;
249250
}
250251
return 0;
251252
}
252253
}
253254

255+
int
256+
_PyTime_FromSecondsObject(_PyTime_t *t, PyObject *obj, _PyTime_round_t round)
257+
{
258+
return _PyTime_FromObject(t, obj, round, SEC_TO_NS);
259+
}
260+
261+
int
262+
_PyTime_FromMillisecondsObject(_PyTime_t *t, PyObject *obj, _PyTime_round_t round)
263+
{
264+
return _PyTime_FromObject(t, obj, round, MS_TO_NS);
265+
}
266+
254267
double
255268
_PyTime_AsSecondsDouble(_PyTime_t t)
256269
{

0 commit comments

Comments
 (0)