给定一个由数字组成的字符串,判断是否为日期类型数据(year-month-day),如果为日期,则返回N天前或者N天后的日期,如果不是日期类型数据,返回False
# 求距离N 天前后的日期
# 输入一串数字,如果为日期类型数据'YEAR-MONTH-DAY',则返回其n天后的日期,如果非日期数据,返回False
def monthndays(date,input_day):
if len(date.split('-'))!=3:
return False
year, month, day = int(date.split('-')[0]),int(date.split('-')[1]),int(date.split('-')[2])
# 月份信息
monthday = [31,28,31,30,31,30,31,31,30,31,30,31]
# 判断是否为闰年,则对2月份数据进行修改
if (year%400 == 0) or (year%4==0 and year % 100 != 0):
monthday[1] = 29
# 判断日期天数是否合法
if month <0 or month > 12 or day <0 or day > monthday[month-1]:
return False
# 求N天前的日期
if input_day < 0:
for i in range(abs(input_day)):
day -= 1
if day < 1:
month -= 1
if month < 1:
year -= 1
month = 12
day = monthday[month-1]
else:
# 求n天后的数据
for i in range(abs(input_day)):
day += 1
# 当day大于当前月份天数,则月份加一
if day > monthday[month-1]:
month += 1
# 当月份大于12时,则年份加一,同时,天数从1开始
if month > 12:
year += 1
month = 1
day = 1
return '-'.join([str(year), str(month), str(day)])
结果展示
print(monthndays('2023-1-32',10))
print(monthndays('2023-12-30',2))
print(monthndays('2023-12-30',-3))
## 返回值
False
2024-1-1
2023-12-27