oop的方式来操纵时间

减少return 减少传参。

主要是在调用上比以前强大很多,以前很怕操作时间,在一堆函数中传来传去。这个调用爽。

 

class DatetimeConverter:
    DATETIME_FORMATTER = "%Y-%m-%d %H:%M:%S"
    DATETIME_FORMATTER2 = "%Y-%m-%d"

    @classmethod
    def bulid_conveter_with_other_formatter(cls, datetime_str, datetime_formatter):
        """
        :param datetime_str: 时间字符串
        :param datetime_formatter: 能够格式化该字符串的模板
        :return:
        """
        datetime_obj = datetime.datetime.strptime(datetime_str, datetime_formatter)
        return cls(datetime_obj)

    def __init__(self, datetimex: typing.Union[int, float, datetime.datetime, str] = time.time()):
        """
        :param datetimex: 接受时间戳  datatime类型 和 时间字符串三种类型
        """
        if isinstance(datetimex, str):
            if not re.match('\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}', datetimex):
                raise ValueError('时间字符串的格式不符合此传参的规定')
            else:
                self.datetime_obj = datetime.datetime.strptime(datetimex, self.DATETIME_FORMATTER)
        elif isinstance(datetimex, (int, float)):
            self.datetime_obj = datetime.datetime.utcfromtimestamp(datetimex)
        elif isinstance(datetimex, datetime.datetime):
            self.datetime_obj = datetimex
        else:
            raise ValueError('实例化时候的传参不符合规定')

    @property
    def datetime_str(self):
        return self.datetime_obj.strftime(self.DATETIME_FORMATTER)

    @property
    def timestamp(self):
        return self.datetime_obj.timestamp()

    @property
    def date_str(self):
        return self.datetime_obj.strftime(self.DATETIME_FORMATTER2)

    @property
    def one_hour_ago_datetime_converter(self):
        """
        酒店经常需要提前一小时免费取消,直接封装在这里
        :return:
        """
        one_hour_ago_datetime_obj = self.datetime_obj + datetime.timedelta(hours=-1)
        return self.__class__(one_hour_ago_datetime_obj)

    def is_greater_than_now(self):
        return self.timestamp > time.time()

    def __str__(self):
        return self.datetime_str

    def __call__(self):
        return self.datetime_obj


if __name__ == '__main__':
    """
    1557113661.0
    '2019-05-06 12:34:21'
    '2019/05/06 12:34:21'
    DatetimeConverter(1557113661.0)()
    """
    o3 = DatetimeConverter('2019-05-06 12:34:21')
    print(o3)
    print('- - - - -  - - -')
    o = DatetimeConverter.bulid_conveter_with_other_formatter('2019/05/06 12:34:21', '%Y/%m/%d %H:%M:%S')
    print(o)
    print(o.date_str)
    print(o.timestamp)
    print('***************')
    o2 = o.one_hour_ago_datetime_converter
    print(o2)
    print(o2.date_str)
    print(o2.timestamp)
    print(o2.is_greater_than_now())
    print(o2(), type(o2()))
    print(DatetimeConverter())

 

 

posted @ 2019-05-04 20:10  北风之神0509  阅读(235)  评论(0编辑  收藏  举报