Bar*_*art 5 python datetime zeromq python-3.x msgpack
zeromq
我需要一种在 python 多处理进程之间每秒发送 300 条短消息的快速方法。每条消息都需要包含一个ID
andtime.time()
msgpack
似乎是在通过 发送之前序列化字典的最佳方法zeromq
,并且方便地,msgpack
有一个正是我需要的示例,除了它有一个datetime.datetime.now()
.
import datetime
import msgpack
useful_dict = {
"id": 1,
"created": datetime.datetime.now(),
}
def decode_datetime(obj):
if b'__datetime__' in obj:
obj = datetime.datetime.strptime(obj["as_str"], "%Y%m%dT%H:%M:%S.%f")
return obj
def encode_datetime(obj):
if isinstance(obj, datetime.datetime):
return {'__datetime__': True, 'as_str': obj.strftime("%Y%m%dT%H:%M:%S.%f")}
return obj
packed_dict = msgpack.packb(useful_dict, default=encode_datetime)
this_dict_again = msgpack.unpackb(packed_dict, object_hook=decode_datetime)
Run Code Online (Sandbox Code Playgroud)
问题是他们的示例不起作用,我收到此错误:
obj = datetime.datetime.strptime(obj["as_str"], "%Y%m%dT%H:%M:%S.%f")
KeyError: 'as_str'
Run Code Online (Sandbox Code Playgroud)
也许因为我使用的是python 3.4,但我不知道strptime有什么问题。将不胜感激您的帮助。
Python3 和 Python2 管理不同的字符串编码:encoding-and-decoding-strings-in-python-3-x
然后需要:
b'as_str'
(而不是'as_str'
)作为字典键encode
和decode
储值像这样修改代码适用于 python2 和 python3 :
import datetime
import msgpack
useful_dict = {
"id": 1,
"created": datetime.datetime.now(),
}
def decode_datetime(obj):
if b'__datetime__' in obj:
obj = datetime.datetime.strptime(obj[b'as_str'].decode(), "%Y%m%dT%H:%M:%S.%f")
return obj
def encode_datetime(obj):
if isinstance(obj, datetime.datetime):
obj = {'__datetime__': True, 'as_str': obj.strftime("%Y%m%dT%H:%M:%S.%f").encode()}
return obj
packed_dict = msgpack.packb(useful_dict, default=encode_datetime)
this_dict_again = msgpack.unpackb(packed_dict, object_hook=decode_datetime)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
5464 次 |
最近记录: |