I have part of a binary file that represents a start time.
I am trying to read a time/date value in the file in Python but having trouble.
>>>file = open('file1',"rb")
>>>data = file.read()
>>>data[16:24]
b'Q\xca\rk\x9c\xc6\xd7\x88'
>>>unpacked, = unpack('<Q', data[16:24])
9860568284264254033
I already know that 16-24 location contains Int64 of 8 byte size.
in C#, I can successfully get the value {3/12/2020 11:45:40 AM} by doing
var value = _reader.ReadInt64();
sdatetime = DateTime.FromBinary(value);
Does anyone know how to read it correctly in Python?
Also if it helps,
>>> unpack('q',data[16:24])
(-8586175789445297583,)
>>> unpack('Q',data[16:24])
(9860568284264254033,)
I tried doing:
>>> unpacked
9860568284264254033
>>> secs = unpacked / 10.0 **7
>>> secs
986056828426.4253
>>> delta = datetime.timedelta(seconds = secs)
>>> delta
datetime.timedelta(days=11412694, seconds=66826, microseconds=425293)
>>> ts = datetime.datetime(1,1,1) + delta
which just resulted in OverflowError: date value out of range
I think I've figured it out
from datetime import datetime, timedelta
time_bytes = b'Q\xca\rk\x9c\xc6\xd7\x88'
time_int = int.from_bytes(time_bytes, 'little')
time_bin = bin(time_int)
# remove two unrelated bits and convert to integer number of ticks
n_ticks = int(time_bin[:2] + time_bin[4:], 2)
secs = n_ticks / 1e7
d1 = datetime(1, 1, 1)
t1 = timedelta(seconds=secs)
print(d1 + t1)
outputs:
2020-03-12 15:45:40.947823
So it's correct up to the time zone
To get an actual timezone, use timedelta
once more.
zone_delta = timedelta(hours=-4)
print(d1 + t1 + zone_delta)
gives
2020-03-12 11:45:40.947830