Python: pytz returns unsuitability __repr __ ()

I understand that the goal repr()is to return a string that can be used to evaluate as python commands and returns the same object. Unfortunately, pytzit does not seem to be very friendly with this function, although it should be quite simple, since the instances pytzare created in one 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 other ipython windows and evaluated because it returns a syntax error in the attribute tzinfo.

Is there an easy way to enable printing:

datetime.datetime(2010, 10, 1, 13, 2, 17, 659333, tzinfo=pytz.timezone('Europe/Berlin'))

when is the line 'Europe/Berlin'already clearly visible on the original output repr()?

+3
source share
1 answer
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"))
+1

Source: https://habr.com/ru/post/1767511/


All Articles