问题
I'm looking into creating a python datetime-subclass which provides a default timezone when created.
For the sake of keeping this question simple, let's assume I always want to hard-code my datetimes to be in UTC.
I can't figure out why the following works:
import datetime, dateutil.tz
def foo(*args, **kwargs):
kwargs['tzinfo'] = dateutil.tz.tzutc()
return datetime.datetime(*args, **kwargs)
But the following doesn't work:
class Foo(datetime.datetime):
def __init__(self, *args, **kwargs):
kwargs['tzinfo'] = dateutil.tz.tzutc()
super(Foo, self).__init__(*args, **kwargs)
Running the first method gives me the datetime object I expect:
>>> foo(2012, 11, 10)
datetime.datetime(2012, 11, 10, 0, 0, tzinfo=tzutc())
>>> foo(2012, 11, 10).tzinfo is None
False
But creating an instance of the Foo class doesn't seem to set the tzinfo object.
>>> Foo(2012, 11, 10)
Foo(2012, 11, 10, 0, 0)
>>> Foo(2012, 11, 10).tzinfo is None
True
Any ideas of what's going on here?
Thanks!
回答1:
Providing the solution, as explained in Why can't I subclass datetime.date? for the sake of completeness, thanks to dano for the link.
The extra functionality has to be implemented in new since the datetime object is immutable:
class Foo(datetime.datetime):
def __new__(cls, *args, **kwargs):
kwargs['tzinfo'] = dateutil.tz.tzutc()
return datetime.datetime.__new__(cls, *args, **kwargs)
来源:https://stackoverflow.com/questions/24966806/subclassing-datetime-datetime