Python:pytz 返回不可用的 __repr__()
据我所知,repr() 的目的是返回一个字符串,该字符串可用于作为 python 命令进行评估并返回相同的对象。不幸的是, pytz 似乎对这个函数不太友好,尽管它应该很容易,因为 pytz 实例是通过一次调用创建的:
import datetime, pytz
now = datetime.datetime.now(pytz.timezone('Europe/Berlin'))
repr(now)
returns:
datetime.datetime(2010, 10, 1, 13, 2, 17, 659333, tzinfo=<DstTzInfo 'Europe/Berlin' CEST+2:00:00 DST>)
这不能是只需复制到另一个 ipython 窗口并进行评估,因为它在 tzinfo
属性上返回语法错误。
有没有简单的方法让它打印:
datetime.datetime(2010, 10, 1, 13, 2, 17, 659333, tzinfo=pytz.timezone('Europe/Berlin'))
当 'Europe/Berlin'
字符串在 repr()
的原始输出中已经清晰可见时?
I understand that repr()
's purpose is to return a string, that can be used to be evaluated as a python command and return the same object. Unfortunately, pytz
does not seem to be very friendly with this function, although it should be quite easy, since pytz
instances are created with a single call:
import datetime, pytz
now = datetime.datetime.now(pytz.timezone('Europe/Berlin'))
repr(now)
returns:
datetime.datetime(2010, 10, 1, 13, 2, 17, 659333, tzinfo=<DstTzInfo 'Europe/Berlin' CEST+2:00:00 DST>)
which cannot be simply copied to another ipython windows and evaluated, because it returns a Syntax Error on the tzinfo
attribute.
Is there any simple way to let it print:
datetime.datetime(2010, 10, 1, 13, 2, 17, 659333, tzinfo=pytz.timezone('Europe/Berlin'))
when the 'Europe/Berlin'
string is already clearly visible in the original output of repr()
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
请注意,夏季的 pytz.timezone("Europe/Berlin") 可能与冬季的 pytz.timezone("Europe/Berlin")) 含义不同,因为到夏令时。因此,monkeypatched
__repr__
始终不是self
的正确表示。但在复制并粘贴到 IPython 期间它应该可以工作(除了极端的极端情况)。另一种方法是子类化
datetime.tzinfo
:Note that
pytz.timezone("Europe/Berlin")
in the summer can mean something different thanpytz.timezone("Europe/Berlin"))
in the winter, due to daylight savings time. So the monkeypatched__repr__
is not a correct representation ofself
for all time. But it should work (except for extreme corner cases) during the time it takes to copy and paste into IPython.An alternative approach would be to subclass
datetime.tzinfo
: