bytearray(byte object)无法附加时间戳

时间:2017-01-31 15:56:44

标签: arrays python-3.x numpy struct byte

我正在尝试将时间戳添加到具有十六进制值的字节对象的开头,但是我遇到了一些问题。

我希望将时间戳附加到索引0的字节obejct(数据),如下所示:

b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00`\xc2\xf5(\x00\x00\x00\x00x\x00\x00\x00!\xa1\x07\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00x\x00\x00\x00\xf5\x00\x00\x00}\x00\x00\x00\x00\x00\x00\x00\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\xff\xff\x7f\x00\x00\x00\x00\x00\x00\x00\x00\xff\x7f\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x98\xe0\x0e\x00 \xa1\x07\x00\xac\r\x00\x00P\xc3\x00\x00o\x12\x83\x00"\x00\x00\x00P\xc3\x00\x00)\\\x8f\x02\xac\x00\x00\x00\xe4\x14\x1d-B\xcff-\x8f\xc2\xf5(\xebQP\xc3(\\\xccLx\x00\x86qd\x00L\x1d}\x00\xf5\x00L\x1d\xb5\x012\x00\x10\'\xcc\x0c\x00\x00\x00\x00\x00\x00l\xe7\xfb)\x00\x00\x00\x00`\xc2\xf5(\xd0\x07\xd0\x07\xfa\x00\xfa\x00\xd0\x07\xd0\x07\x01\x00\x01\x00\xc4\t\xc4\t\xc7\x01\x00\x00\xd0\x07\xee\x02\x8f\xc2\xf5(+\xf6\x97)\xc4\tzT\x05\x02\xb8\x0b\x00\x00\x05\x01\x00\x00\x00\x00\x00\x00\x00\x08<\x0f2\x00\n\x01K\x00\x00\x00\xc4\t\x00\x04\x07@\x01\x00\x00\x00'

我试图以这种方式插入时间戳:

import struct, time 
import numpy as np
g = bytearray(data)
time_ = struct.pack("I",int(time.time()))
g.append(int(time_))

我的错误如下:

ValueError:基数为10的int()的无效文字:b'\ x11 \ xb2 \ x90X'

我怎么能这样做?

1 个答案:

答案 0 :(得分:0)

In [878]: g=bytearray([])
In [879]: import struct, time
In [880]: time_ = struct.pack("I",int(time.time()))
In [881]: time_
Out[881]: b'U\xc5\x90X'

通过尝试将time_解释为整数来生成错误:

In [886]: int(time_)
...
ValueError: invalid literal for int() with base 10: b'U\xc5\x90X'

但附加time_也不起作用,因为它有多个字节:

In [882]: g.append(time_)
...
TypeError: an integer is required
In [883]: g.append?
Signature: g.append(item, /)
Docstring:
Append a single item to the end of the bytearray.

但是扩展确实有效:

In [884]: g.extend(time_)
In [885]: g
Out[885]: bytearray(b'U\xc5\x90X')

int(time)是一个整数,占用4个字节:

In [887]: int(time.time())
Out[887]: 1485882974
In [888]: len(time_)
Out[888]: 4
相关问题