Skip to content

Instantly share code, notes, and snippets.

@smowton
Created July 30, 2020 15:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save smowton/06d0284ae6ca5650b6d07947620e56eb to your computer and use it in GitHub Desktop.
Save smowton/06d0284ae6ca5650b6d07947620e56eb to your computer and use it in GitHub Desktop.
Python to add 7-day rolling sum to a CSV
#!/usr/bin/python
import datetime
import sys
# Adds a 7-day rolling sum to a CSV
# Input: date,cases
# date format: yyyy-mm-dd
# Output: date,cases,last7days
recs = []
for rec in sys.stdin:
rec = rec.strip().split(",")
if len(rec) == 0:
continue
assert len(rec) == 2
date = datetime.datetime.strptime(rec[0], '%Y-%m-%d')
count = int(rec[1])
recs.append((rec[0], date, count))
def last_7_days(end):
start = end - datetime.timedelta(6)
return sum(rec[2] for rec in recs if rec[1] <= end and rec[1] >= start)
for rec in recs:
print ",".join([rec[0], str(rec[2]), str(last_7_days(rec[1]))])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment