Rifet Gazdic
Rifet Gazdic

Reputation: 31

Convert date to hexadecimal with identical value

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])

Upvotes: 0

Views: 128

Answers (2)

martineau
martineau

Reputation: 123491

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

Here's how to do to so the hexadecimal values are numerically equal to their decimal counterparts:

# Do it so values are equal numerically.
values = [int(value) for value in dt.strftime('%d %m %y %H %M %S').split()]
ba = bytearray(values)
print(' '.join(f'0x{b:02x}' for b in ba))  # -> 0x0c 0x0b 0x15 0x0a 0x3a 0x34

Upvotes: 1

ncica
ncica

Reputation: 7206

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.

Upvotes: 0

Related Questions