Python:pytz返回不可用__repr __()

时间:2010-10-01 11:06:46

标签: python instance representation pytz

我理解repr()的目的是返回一个字符串,该字符串可用于作为python命令进行求值并返回相同的对象。遗憾的是,pytz对此函数似乎不太友好,尽管它应该非常简单,因为pytz个实例是通过一次调用创建的:

import datetime, pytz
now = datetime.datetime.now(pytz.timezone('Europe/Berlin'))
repr(now)

返回:

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()的原始输出中已清晰可见?

1 个答案:

答案 0 :(得分:1)

import datetime
import pytz
import pytz.tzinfo

def tzinfo_repr(self):
    return 'pytz.timezone({z})'.format(z=self.zone)
pytz.tzinfo.DstTzInfo.__repr__=tzinfo_repr

berlin=pytz.timezone('Europe/Berlin')
now = datetime.datetime.now(berlin)
print(repr(now))
# datetime.datetime(2010, 10, 1, 14, 39, 4, 456039, tzinfo=pytz.timezone("Europe/Berlin"))

请注意,由于夏令时,夏季的pytz.timezone("Europe/Berlin")在冬季可能意味着与pytz.timezone("Europe/Berlin"))不同。因此,monkeypatched __repr__并不是self的正确表示。但是在复制和粘贴到IPython所需的时间内它应该可以工作(极端极端情况除外)。


另一种方法是继承datetime.tzinfo

class MyTimezone(datetime.tzinfo):
    def __init__(self,zone):
        self.timezone=pytz.timezone(zone)
    def __repr__(self):
        return 'MyTimezone("{z}")'.format(z=self.timezone.zone)
    def utcoffset(self, dt):
        return self.timezone._utcoffset
    def tzname(self, dt):
        return self.timezone._tzname
    def dst(self, dt):
        return self.timezone._dst

berlin=MyTimezone('Europe/Berlin')
now = datetime.datetime.now(berlin)
print(repr(now))
# datetime.datetime(2010, 10, 1, 19, 2, 58, 702758, tzinfo=MyTimezone("Europe/Berlin"))