如何更改datetime .__ add__的行为?

时间:2018-05-24 09:38:54

标签: python-3.x datetime inheritance

我有一个代码库this error可能经常出现在其中:向时区感知日期时间对象添加timedelta可能会导致datetime对象具有正确的时区和正确的时间点,但是DST引起的错误偏移。

我想覆盖datetime.__add__的行为。我以为我是datetime的子类,然后导入我修改过的子类,但是由于datetime是不可变的,所以它比我想象的要复杂得多。

以下是我的尝试:

#!/usr/bin/env python

import datetime as dt_orig

# 3rd party
import pytz


class datetime(dt_orig.datetime):
    def __new__(cls, *args, **kwargs):
        tzstring = None
        if 'tzinfo' in kwargs and isinstance(kwargs['tzinfo'], str):
            tzstring = kwargs['tzinfo']
            kwargs['tzinfo'] = dt_orig.timezone.utc
        dt_obj = super().__new__(cls, *args, **kwargs)
        # if tzstring is not None:  # When this is uncommented, it's not the custom datetime class but the standard Python class
        #     dt_obj = dt_obj.astimezone(pytz.timezone(tzstring))
        return dt_obj

    def __add__(self, other):
        if isinstance(other, dt_orig.timedelta):
            tmp = super().__add__(other)  # creates a datetime.datetime
            tmp = tmp.astimezone(pytz.utc).astimezone(tmp.tzinfo)
            return tmp
        else:
            return super().__add__(other)

    __radd__ = __add__

通过这种方式,我可以创建自定义日期时间对象,但是当我应用obj.astimezone(...)(或任何其他方法,例如添加)时,我会返回datetime.datetime

在大多数情况下,如何在保持datetime.datetime的实现的同时恢复我的自定义日期时间对象?

0 个答案:

没有答案