#日期计算函数format yyyymmdd
def cal_date(isodate, op):
int_isodate = int(isodate)
year = int_isodate // 10000
tm = int_isodate - year * 10000
month = tm // 100
day = tm - month * 100
def is_r_y(y):
if (y % 100 != 0 and y % 4 == 0) or (y % 100 == 0 and y % 400 == 0):
return True
else:
return False
def get_y_d(y):
if is_r_y(y):
return 366
else:
return 365
def get_m_day(y,m,d):
m_days = [0,31,59,90,120,151,181,212,243,273,304,334,365]
#闰年
if is_r_y(y):
m_days = [0,31,60,91,121,152,182,213,244,274,305,335,366]
return m_days[m - 1] + d
def get_y_m_d(y,dy):
m_days = [0,31,59,90,120,151,181,212,243,273,304,334,365]
#闰年
if is_r_y(y):
m_days = [0,31,60,91,121,152,182,213,244,274,305,335,366]
cur_month = 1
cur_day = 1
for i in range(1,len(m_days)):
if dy > m_days[i]:
continue
else:
cur_month = i
break
cur_day = dy - m_days[cur_month-1]
return [y,cur_month, cur_day]
cur_day = get_m_day(year,month,day)
cur_day = cur_day + op
dat = None
if cur_day < 0:
year = year - 1
while(cur_day + get_y_d(year) <= 0):
cur_day = cur_day + get_y_d(year)
year = year - 1
cur_day = cur_day + get_y_d(year)
elif cur_day > get_y_d(year):
while(cur_day - get_y_d(year) > 0):
cur_day = cur_day - get_y_d(year)
year = year + 1
dat = get_y_m_d(year, cur_day)
new_date = ''
for d in dat:
if d > 0 and d < 10:
new_date = new_date + '0' + str(d)
else:
new_date = new_date + str(d)
return new_date
cal_date('20221113', -45)
python日期增减
于 2023-01-10 18:32:21 首次发布
该代码定义了一个用于日期计算的Python函数cal_date,它接受一个形如20221113的日期字符串和一个操作数(op),可以向前或向后推算日期。函数首先将输入转换为年、月、日,然后根据是否为闰年来确定每年的天数。通过get_y_d、get_m_day等辅助函数计算日期,最后返回新的日期字符串。例如,cal_date(20221113,-45)会返回一个新的日期。
摘要由CSDN通过智能技术生成