Python embedded. timestamp() return same time over multiple seconds

Tags: , ,



I have implemented a system of callbacks. I want to display the time in unix epoch when I call the function.

For example:

from datetime import datetime

def my_callback():
    print(datetime.now().timestamp())
    print(datetime.now())

In game:

First call:
1614270080.0
2021-02-25 19:22:14.304776

Second call after a second:
1614270080.0
2021-02-25 19:22:15.498516

Last call after a 2 seconds:
1614270080.0
2021-02-25 19:22:17.701154

Why datetime.now().timestamp() return same time? The same problem with time.time()

I use Python 3.8 x32

Answer

The type of a timestamp is float, which is a floating point type of the width of the Python build. A 32-bit float is not sufficient to express the timestamp with second precision:

>>> import struct
>>> def as_f32(num: float): return struct.unpack('f', struct.pack('f', num))[0]
>>> def as_f64(num: float): return struct.unpack('d', struct.pack('d', num))[0]
>>> # 32-bit expressible timestamps in a 10 second range
>>> set(map(as_f32, range(1614270075, 1614270085)))
{1614270080.0}
>>> # 64-bit expressible timestamps in a 10 second range
>>> set(map(as_f64, range(1614270075, 1614270085)))
{1614270075.0, 1614270076.0, 1614270077.0, 1614270078.0, 1614270079.0, 1614270080.0, 1614270081.0, 1614270082.0, 1614270083.0, 1614270084.0}

Use a 64-bit build if the full precision is needed.



Source: stackoverflow