根據給定時間及偏移的年份求偏移後時間的前一天(支持偏移量為正和負)
阿新 • • 發佈:2019-01-24
普通 and strftime 每年 color 代碼 != class str
直接上代碼
class DateHandler: @staticmethod def get_date(cur_date, offset_year): # 時間算法,往後偏移的年份; cur_day = cur_date.day cur_month = cur_date.month cur_year = cur_date.year if cur_day > 1: # 天數大於一 return cur_date.replace(year=cur_year + offset_year, day=cur_day - 1)else: if cur_month > 1: # 天數等於一,但是月份大於一 if cur_month - 1 in (1, 3, 5, 7, 8, 10, 12): return cur_date.replace(year=cur_year + offset_year, month=cur_month - 1, day=31) elif cur_month - 1 in (4, 6, 9, 11):return cur_date.replace(year=cur_year + offset_year, month=cur_month - 1, day=30) elif cur_month - 1 == 2: next_year = cur_year + offset_year if (next_year % 4 == 0 and next_year % 100 != 0) or (next_year % 400 == 0): # 普通閏年和世紀閏年return cur_date.replace(year=cur_year + offset_year, month=cur_month - 1, day=29) else: return cur_date.replace(year=cur_year + offset_year, month=cur_month - 1, day=28) else: # 天數等於1、月份等於1;每年的12月31日繳納 return cur_date.replace(year=cur_year + offset_year - 1,month=12, day=31) @staticmethod def date_str_to_datetime(time): # ‘2018-01-01.862458‘ 時間精確 if type(time) == str: return datetime.datetime.strptime(time,‘%Y-%m-%d.%f‘) elif type(time) == datetime: return datetime.datetime.now().strftime(‘%Y-%m-%d.%f‘) print(DateHandler.get_date(DateHandler.date_str_to_datetime(‘2018-01-01.862458‘),3))
根據給定時間及偏移的年份求偏移後時間的前一天(支持偏移量為正和負)