問題描述
fromtimestamp() 的反義詞是什麼? (What is the opposite of fromtimestamp()?)
我正在嘗試弄清楚如何將二進製文件導入 python,但這需要大量的猜測和反複試驗。在這種情況下,我想做的是找到字節流中特定日期出現的位置,即:
import re
import datetime
import binascii
import time
with open('inputfile.nda', 'rb') as f:
data = f.read()
# This line needs fixing
i = int.oppositeof_fromtimestamp(2019, 10, 10, 14, 53, 57.000) # '2019/10/10 14:53:57.000'
time_stamp = i.to_bytes(4, byteorder='little')
df = [m.start() for m in re.finditer(time_stamp, data)]
print(df)
是否有一個函數(或一組函數)可以將日期轉換為字節流?
參考解法
方法 1:
You're looking for datetime.timestamp()
:
import datetime
ts = datetime.datetime(2019, 10, 10, 14, 53, 57)
unix_time = int(ts.timestamp())
unix_time_bytes = unix_time.to_bytes(4, byteorder='little')
print(ts, unix_time, unix_time_bytes)
outputs
2019‑10‑10 14:53:57 1570708437 b'\xd5\x1b\x9f]'
Then you'll probably want to use data.index(unix_time_bytes)
to look for the string, not regexps.
(by Frederik Huld、AKX)