I’m trying to figure out how to import a binary file into python, but it’s a lot of guesswork and trial and error. What I’d like to do in this case to is find where a specific date occurs in the bytestream, i.e:
JavaScript
x
18
18
1
import re
2
import datetime
3
import binascii
4
import time
5
6
with open('inputfile.nda', 'rb') as f:
7
data = f.read()
8
9
# This line needs fixing
10
i = int.oppositeof_fromtimestamp(2019, 10, 10, 14, 53, 57.000) # '2019/10/10 14:53:57.000'
11
12
13
time_stamp = i.to_bytes(4, byteorder='little')
14
15
df = [m.start() for m in re.finditer(time_stamp, data)]
16
17
print(df)
18
Is there a function (or set of functions) that can convert a date into a bytestream?
Advertisement
Answer
You’re looking for datetime.timestamp()
:
JavaScript
1
7
1
import datetime
2
3
ts = datetime.datetime(2019, 10, 10, 14, 53, 57)
4
unix_time = int(ts.timestamp())
5
unix_time_bytes = unix_time.to_bytes(4, byteorder='little')
6
print(ts, unix_time, unix_time_bytes)
7
outputs
JavaScript
1
2
1
2019-10-10 14:53:57 1570708437 b'xd5x1bx9f]'
2
Then you’ll probably want to use data.index(unix_time_bytes)
to look for the string, not regexps.