不废话上代码
from datetime import datetime
from dateutil.parser import parse
start_at = '2021-07-01 06:08:40'
d1 = parse(start_at)
end_at = '2021-08-05 06:08:43'
d2 = parse(end_at)
if (d2-d1).days > 30:
raise Exception('do not exceed 30 days')
print((d2-d1).days)
还有一个就是列举出两个日期之间的每一天开始和结束,效果如下图: 在某些查询的时候可能需要用到,一并做下记录。
import datetime
start_at = '2021-07-01'
end_at = '2021-07-07'
step = 1
resp_list = []
start_array = start_at.split('-')
end_array = end_at.split('-')
start_day = datetime.datetime(
int(start_array[0]), int(start_array[1]), int(start_array[2]))
end_day = datetime.datetime(
int(end_array[0]), int(end_array[1]), int(end_array[2]))
interval = (end_day - start_day).days + 2
day_str = start_at + ' 00:00:00'
for i in range(1, interval, step):
start_day = datetime.datetime.strptime(day_str, '%Y-%m-%d %H:%M:%S')
start_at = start_day + datetime.timedelta(days=i-1)
end_at = start_at + datetime.timedelta(days=1)
|