I have implemented a system of callbacks. I want to display the time in unix epoch when I call the function.
For example:
JavaScript
x
6
1
from datetime import datetime
2
3
def my_callback():
4
print(datetime.now().timestamp())
5
print(datetime.now())
6
In game:
JavaScript
1
12
12
1
First call:
2
1614270080.0
3
2021-02-25 19:22:14.304776
4
5
Second call after a second:
6
1614270080.0
7
2021-02-25 19:22:15.498516
8
9
Last call after a 2 seconds:
10
1614270080.0
11
2021-02-25 19:22:17.701154
12
Why datetime.now().timestamp()
return same time? The same problem with time.time()
I use Python 3.8 x32
Advertisement
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:
JavaScript
1
10
10
1
>>> import struct
2
>>> def as_f32(num: float): return struct.unpack('f', struct.pack('f', num))[0]
3
>>> def as_f64(num: float): return struct.unpack('d', struct.pack('d', num))[0]
4
>>> # 32-bit expressible timestamps in a 10 second range
5
>>> set(map(as_f32, range(1614270075, 1614270085)))
6
{1614270080.0}
7
>>> # 64-bit expressible timestamps in a 10 second range
8
>>> set(map(as_f64, range(1614270075, 1614270085)))
9
{1614270075.0, 1614270076.0, 1614270077.0, 1614270078.0, 1614270079.0, 1614270080.0, 1614270081.0, 1614270082.0, 1614270083.0, 1614270084.0}
10
Use a 64-bit build if the full precision is needed.