3

repr()の目的は、Python コマンドとして評価して同じオブジェクトを返すために使用できる文字列を返すことであることを理解しています。残念ながら、インスタンスは 1 回の呼び出しで作成される 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()

4

1 に答える 1

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"))
于 2010-10-01T11:59:05.800 に答える