python3.9 与 python3.6 中的时间增量问题

timedelta issue in python3.9 vs.python3.6

我在名为 'GPS_Date.py' 的文件中有以下 class:

import datetime
from math import floor

class GPS_Date(datetime.datetime):

    ref_date = datetime.datetime(1980, 1, 6)

    def __init__(self, year, month, day, hour=0, minute=0, second=0):
        datetime.datetime.__init__(year, month, day, hour, minute, second)

    def gps_week(self):
        difftime = self-self.ref_date
        return floor(difftime.days / 7)

    def day_of_week(self):
        difftime = self-self.ref_date
        return difftime.days % 7

    def day_of_year(self):
        return self.timetuple().tm_yday

    @staticmethod
    def to_GPS_date(date):
        return GPS_Date(date.year, date.month, date.day, date.hour, date.minute, date.second)

    @staticmethod
    def now():
        return GPS_Date.to_GPS_date(datetime.datetime.utcnow())

当我运行下面的代码在python3.6我得到正确的解决方案:

import datetime
from GPS_Date import GPS_Date

time_string = '2019-01-01 23:59:30.0'
date_format = '%Y-%m-%d %H:%M:%S.%f'

time_1 = datetime.datetime.strptime(time_string, date_format)

time_2 = GPS_Date.to_GPS_date(time_1)

add_time = time_2 + datetime.timedelta(minutes=30)

但是当我 运行 它与 python3.9 我得到以下错误:

    add_time = time_2 + datetime.timedelta(minutes=30)
TypeError: __init__() takes from 4 to 7 positional arguments but 9 were given

我假设 python3.6 和 python3.9 之间发生了一些变化。我查看了文档,但没有找到任何东西。谁能赐教一下?

datetime.datetime 确实比 GPS_Date 有更多的参数可以传递(即 tzinfofold)。为什么这不会在 Python3.6 中爆炸,我不确定。但是你根本不需要重写 __init__,因为你什么都没做:

class GPS_Date(datetime.datetime):

    ref_date = datetime.datetime(1980, 1, 6)

    def gps_week(self):
        difftime = self - self.ref_date
        return floor(difftime.days / 7)

    def day_of_week(self):
        difftime = self - self.ref_date
        return difftime.days % 7

    def day_of_year(self):
        return self.timetuple().tm_yday

    @staticmethod
    def to_GPS_date(date):
        return GPS_Date(date.year, date.month, date.day, date.hour, date.minute, date.second)

    @staticmethod
    def now():
        return GPS_Date.to_GPS_date(datetime.datetime.utcnow())

完全没问题。 (另请注意:如果您要执行某些操作,则需要覆盖 __new__ 而不是 __init__