简体   繁体   English

TypeError:无法腌制时间对象

[英]TypeError: can't pickle time objects

After running code from my previous question , I get a result set from my subprocess that looks like this: 运行上一个问题的代码后,我从子进程中得到一个结果集,如下所示:

[[(<PyTime:6/10/2012 3:24:17 AM>, 1593.5, 413.0, 19.600000381469727, 430.0, 16.0, 47.0, 42.70000076293945, 15.600000381469727, 69.5), 
(<PyTime:6/10/2012 3:24:18 AM>, 1658.0, 412.0, 19.600000381469727, 429.0, 7.0, 34.400001525878906, 30.899999618530273, 15.699999809265137, 69.5), 
(<PyTime:6/10/2012 3:24:19 AM>, 1685.0, 406.0, 19.600000381469727, 425.0, 18.0, 28.700000762939453, 26.399999618530273, 15.699999809265137, 69.5)]]

When I attempt to send this from my subprocess to my parent process, I do this, where cu equals the above. 当我尝试从子进程发送到我的父进程时,我这样做,其中cu等于上面的。

conn.send(pickle.dumps(cu))

This results in the following error: TypeError: can't pickle time objects 这会导致以下错误: TypeError: can't pickle time objects

What is a work around to send the above list back to the parent process? 将上面的列表发送回父进程的工作是什么?

As the other answers said, PyTime objects aren't "pickleable". 正如其他答案所说, PyTime对象不是“pickleable”。 I would suggest converting them to regular datetime objects, which can be pickle: 我建议将它们转换为常规datetime对象,这可以是pickle:

from datetime import datetime

list_of_pytimes = [ ... ]
list_of_datetimes = [datetime.fromtimestamp(int(pytime)) for pytime in list_of_pytimes]
# Now this will work
pickle.dumps(list_of_datetimes)

Those PyTime objects do not look like the datetime objects from Python's standard library. 那些PyTime对象看起来不像Python标准库中的日期时间对象。 Since normal datetime objects appear to pickle without issue, I would recommend converting them. 由于正常的日期时间对象看起来没有问题,我建议转换它们。 I don't know what database driver you're using, but you may be able to configure it to use standard datetime objects. 我不知道您正在使用什么数据库驱动程序,但您可以将其配置为使用标准日期时间对象。

Try monkey-patching PyTime class with __getstate__ and __setstate__ ( documentation ). 尝试使用__getstate____setstate__文档 )修补PyTime类。 If that doesn't work you'll have to convert to a pickleable type eg datetime.time . 如果这不起作用,您将必须转换为pickleable类型,例如datetime.time

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM