【问题标题】:Convert date to hexadecimal with identical value将日期转换为具有相同值的十六进制
【发布时间】:2021-11-12 10:04:57
【问题描述】:

假设当前日期时间是12.11.21 10:58:52

我需要创建具有这些等效值的bytearray

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

我试图解决这个问题几个小时。

当我运行程序时出现以下错误:

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

所以为了简化,变量DateTime 需要是这样的

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

这是我的程序:

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

【问题讨论】:

  • 你为什么要这样表示日期/时间?此外,例如的十六进制表示十进制 52 不是 x52 而是 x34 ...
  • 转换为字节串/bytearray,你可以使用例如bytearray(map(int, "12.11.21 10:58:52".replace('.',' ').replace(':',' ').split()))

标签: python datetime hex


【解决方案1】:

这将满足您的需求,尽管如 cmets 中所述,十六进制值在数值上与对应的十进制值等效。

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

以下是如何使十六进制值在数值上等于其对应的十进制值:

# 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

【讨论】:

    【解决方案2】:

    如果您尝试从可迭代列表中获取字节数组,则可迭代对象必须是 0

    【讨论】:

    • 如果当前时间是这样的“12.11.21 10:58:52”,我需要得到这个:bytearray([0x12 0x11 0x21 0x10 0x58 0x52])
    猜你喜欢
    • 2018-11-29
    • 1970-01-01
    • 2011-05-26
    • 1970-01-01
    • 2014-02-05
    • 2017-03-11
    • 2022-09-29
    • 2023-01-25
    相关资源
    最近更新 更多