将时间字符串转换为单独的十六进制字节

Convert time-string into individual hex bytes

dt = datetime.datetime.now()
dt = dt.strftime('%Y%m%d%H%M%S')
t = dt.decode("hex")
print list(t)

返回 [' ', '\x15', '\x12', ')', '\x10', ')', '6']。但它不会转换为十六进制。虽然我想有例如。 year-2015 必须转换为 \x07\xdf 并相应地将 month, date, hour, minute, second 转换为它们各自的 hex。谁能帮我解决这个问题?

不知道这是不是你要找的:

import datetime;
dt = datetime.datetime.now()
print hex(dt.year)
print hex(dt.month)
print hex(dt.day)
print hex(dt.hour)
print hex(dt.minute)
print hex(dt.second)

这将为您提供所需的十六进制数字。如果你想将它们放在一个列表中,你可以将它们中的每一个附加到一个空列表中。

如果打印:

dt = dt.strftime('%Y%m%d%H%M%S')
print list(dt)

您将获得:

['2', '0', '1', '5', '1', '2', '2', '9', '0', '8', '3', '7', '3', '2']

如果转换为十六进制:

t = dt.decode("hex")
print list(t)

您将获得:

[' ', '\x15', '\x12', ')', '\x08', 'B', '\x07']

Jorge Torres这样的混合解决方案是这样的:

mystr=""
mystr+=hex(dt.year)
mystr+=hex(dt.month)
mystr+=hex(dt.day)
mystr+=hex(dt.hour)
mystr+=hex(dt.minute)
mystr+=hex(dt.second)
print mystr

结果如你所愿:

0x7df0xc0x1d0x80x2f0x6

如果您担心性能问题,这里是我的机器(core2duo)中 1M 迭代的示例,我已经删除了打印:

@timeit
def tst_1():
    for i in range(1000000):
        dt = datetime.datetime.now()
        mystr=""
        mystr+=hex(dt.year)
        mystr+=hex(dt.month)
        mystr+=hex(dt.day)
        mystr+=hex(dt.hour)
        mystr+=hex(dt.minute)
        mystr+=hex(dt.second)
        #print mystr
    
@timeit 
def tst_2():
    for i in range(1000000):
        dt = datetime.datetime.now()
        dt = dt.strftime('%Y%m%d%H%M%S')
        t = dt.decode("hex")
        #print list(t)  

结果:

func:'tst_1' args:[(), {}] took: 3.6850 sec

func:'tst_2' args:[(), {}] took: 9.9950 sec

所以从字符串解码 Hex 实际上花费了 2.7 倍的时间。