消息包和日期时间

Bar*_*art 5 python datetime zeromq python-3.x msgpack

zeromq我需要一种在 python 多处理进程之间每秒发送 300 条短消息的快速方法。每条消息都需要包含一个IDandtime.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有什么问题。将不胜感激您的帮助。

mpr*_*net 3

Python3 和 Python2 管理不同的字符串编码:encoding-and-decoding-strings-in-python-3-x

然后需要:

  • 使用b'as_str'(而不是'as_str')作为字典键
  • 使用encodedecode储值

像这样修改代码适用于 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)