Skip to content
Advertisement

What is the opposite of fromtimestamp()?

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:

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)

Is there a function (or set of functions) that can convert a date into a bytestream?

Advertisement

Answer

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'xd5x1bx9f]'

Then you’ll probably want to use data.index(unix_time_bytes) to look for the string, not regexps.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement