Reputation: 57
Please i need some help, i have a python script that parses serial data, the data is stored on a byte array.
the problem, i ave an array with the string representation of a datetime:
bytearray['\x01','\x35','\x40','\x02','\x21','\x016']
meaning that the array represents 01:35:40 02/21/2016
how can i parse this array into a datetime i mean i can do this without a problem
datetime.strptime('01:35:40 02/21/16', %H:%M:S %m/%d/%y)
but i cant get the freaking str representation out of that hex array
please help! thanks!
Upvotes: 1
Views: 277
Reputation: 142859
Maybe it looks like strings but bytearray()
keeps numbers (bytes) and you see their hex codes.
It looks like BCD
(Binary-Coded Decimals) and you can easily convert to integers using bit operations
import datetime
b = bytearray('\x01\x35\x40\x02\x21\x16')
# decode BCD numbers
n = [(x>>4)*10 + (x&15) for x in b]
# add 2000 to year
n[5] += 2000
# create datetime object
#d = datetime.datetime(year=n[5], month=n[3], day=n[4], hour=n[0], minute=n[1], second=n[2])
d = datetime.datetime(n[5], n[3], n[4], n[0], n[1], n[2])
# print it
print(d.strftime('%H:%M:%S %m/%d/%y'))
BTW: if you don't have Python bytearray()
but normal list then you can use ord()
b = ['\x01', '\x35', '\x40', '\x02', '\x21', '\x16']
b = [ord(x) for x in b]
# decode BCD numbers
n = [(x>>4)*10 + (x&15) for x in b]
# ...
Upvotes: 1