Home > Back-end >  Convert date to hexadecimal with identical value
Convert date to hexadecimal with identical value

Time:11-12

Lets say that current datetime is 12.11.21 10:58:52

I need to create bytearray that has these equivalent values:

bytearray([0x12 0x11 0x21 0x10 0x58 0x52])

I am trying to resolve this problem for several hours.

When I run program I get following error:

DateTime = bytearray([date_day,date_month,date_year,date_hour,date_minute,date_second])
TypeError: 'str' object cannot be interpreted as an integer

So to simplify, variable DateTime needs to be like this

DateTime = bytearray([0x12 0x11 0x21 0x10 0x58 0x52])

Here is my program:

import sys
import asyncio
import platform

from bleak import BleakClient
from datetime import datetime

def hexConvert(value):
    a = int(value, 16)
    an_integer = int(hex(a), 16)
    hex_value = hex(an_integer)
    return hex_value

# Get local DateTime
local_dt = datetime.now()

# Convert to hexadecimal values for sending to BLE stack
date_day = hexConvert("0x{}".format(local_dt.day))
date_month = hexConvert("0x{}".format(local_dt.month))
date_year = hexConvert("0x{}".format(local_dt.year-2000))

date_hour =  hexConvert("0x{}".format(local_dt.hour))
date_minute =  hexConvert("0x{}".format(local_dt.minute))
date_second =  hexConvert("0x{}".format(local_dt.second))

print(date_day,date_month,date_year,date_hour,date_minute,date_second) #output= 0x12 0x11 0x21 0x10 0x58 0x52

DateTime = bytearray([date_day,date_month,date_year,date_hour,date_minute,date_second])

CodePudding user response:

This will do what you apparently want, although as noted in the comments the hexadecimal values are not numerically equivalent to the corresponding decimal ones.

from datetime import datetime

date_string = '12.11.21 10:58:52'

dt = datetime.strptime(date_string, '%d.%m.%y %H:%M:%S')
values = [int(value, 16) for value in dt.strftime('%d %m %y %H %M %S').split()]
ba = bytearray(values)
print(' '.join(hex(b) for b in ba))  # -> 0x12 0x11 0x21 0x10 0x58 0x52

CodePudding user response:

If you are trying to get an Array of bytes from an iterable list, an iterable must be an iterable of integers in the range 0 <= x < 256, which are used as the initial contents of the array.

  • Related