题目:
计算日期数据周同比?
2022-04-16 62
2022-04-17 82
2022-04-18 97
2022-04-19 75
2022-04-20 93
2022-04-21 90
2022-04-22 90
2022-04-23 61
2022-04-24 81
2022-04-25 79
2022-04-26 88
2022-04-27 75
2022-04-28 85
2022-04-29 82
2022-04-30 71
2022-05-01 67
2022-05-02 64
2022-05-03 84
2022-05-04 72
思路:
1、创建新字典,读取文件内容,将数据遍历添加进字典中。
2、定义一个格式化初始日期和七天后日期的函数
3、遍历字典中的日期和值,将值进行处理输出。
结果:
import datetime
date_sale = {}
is_first_line = True
with open("./text") as fin:
for line in fin:
line = line[:-1]
date,sale_number = line.split(" ")
date_sale[date] = float(sale_number)
def get_diff_days(date,days):
curr_date = datetime.datetime.strptime(date,"%Y-%m-%d")
timedelta = datetime.timedelta(days=-days)
return (curr_date + timedelta).strftime("%Y-%m-%d")
for date,sale_number in date_sale.items():
date7 = get_diff_days(date,7)
sale_number7 = date_sale.get(date7,0)
if sale_number7 == 0:
print(date,sale_number,0)
else:
week_diff = (sale_number - sale_number7) / sale_number7
print(date,sale_number,date7,sale_number7,week_diff)
标签:days,2022,04,sale,35,number,日期,计算,date From: https://www.cnblogs.com/LoLong/p/16908965.html