Python:迭代日期列表并选择财政周的第一天

时间:2016-07-14 16:19:20

标签: python list loops pandas

我在Python中有一个日期和财政周的列表。我使用以下代码从CSV中提取它们并加载到列表中:

import csv

with open('Fiscal3.csv', 'rb') as csvfile:
    reader = csv.reader(csvfile)
    reader2 = list(reader)

这是列表的样子:

for a, b in reader2:
print a,b

结果:

1/13/2020 50
1/14/2020 50
1/15/2020 50
1/16/2020 50
1/17/2020 50
1/18/2020 50
1/19/2020 50
1/20/2020 51
1/21/2020 51
1/22/2020 51
1/23/2020 51
1/24/2020 51
1/25/2020 51
1/26/2020 51

我可以使用哪些代码来获取一周的第一天,然后在一周中的每一天打印它,如下面的输出结果?

输出我希望得到:

[each day]   [first day of week]

1/13/2020 50 1/13/2020
1/14/2020 50 1/13/2020
1/15/2020 50 1/13/2020
1/16/2020 50 1/13/2020
1/17/2020 50 1/13/2020
1/18/2020 50 1/13/2020
1/19/2020 50 1/13/2020
1/20/2020 51 1/20/2020
1/21/2020 51 1/20/2020
1/22/2020 51 1/20/2020
1/23/2020 51 1/20/2020
1/24/2020 51 1/20/2020
1/25/2020 51 1/20/2020
1/26/2020 51 1/20/2020

2 个答案:

答案 0 :(得分:0)

不确定这是否是您可以获得的最佳解决方案。 在这里,我假设你的第一行永远是你的第一个财政日


import csv
from datetime import datetime, timedelta, MINYEAR

with open ('Fiscal3.csv','rb') as csvfile: r = csv.reader(csvfile) first_day = datetime(1, 1,MINYEAR) for i in r: date_value = [ int(x) for x in i[0].split(' ')[0].split('/') ] value_as_datetime = datetime(date_value[2], date_value[0], date_value[1])

# if the difference is greater than a week, we want to update our first_day value if value_as_datetime - first_day >= timedelta(weeks=1): first_day = value_as_datetime print value_as_datetime, first_day

结果:

2020-01-13 00:00:00 2020-01-13 00:00:00
2020-01-14 00:00:00 2020-01-13 00:00:00
2020-01-15 00:00:00 2020-01-13 00:00:00
2020-01-16 00:00:00 2020-01-13 00:00:00
2020-01-17 00:00:00 2020-01-13 00:00:00
2020-01-18 00:00:00 2020-01-13 00:00:00
2020-01-19 00:00:00 2020-01-13 00:00:00
2020-01-20 00:00:00 2020-01-20 00:00:00
2020-01-21 00:00:00 2020-01-20 00:00:00
2020-01-22 00:00:00 2020-01-20 00:00:00
2020-01-23 00:00:00 2020-01-20 00:00:00
2020-01-24 00:00:00 2020-01-20 00:00:00
2020-01-25 00:00:00 2020-01-20 00:00:00
2020-01-26 00:00:00 2020-01-20 00:00:00

您还应该查看https://docs.python.org/2/library/datetime.html

答案 1 :(得分:0)

from datetime import datetime, timedelta


res=[]
dates=[('1/13/2020', 50),('1/13/2020', 49),('1/13/2020', 52)]
for a, b in dates :
    dt = datetime.strptime(a, '%m/%d/%Y')
    start = dt - timedelta(days=dt.weekday())
    end = start + timedelta(days=6)
    res.append((a,b, str(start)[:10]))


print res

输入:

dates=[('1/13/2020', 50),('1/13/2020', 49),('1/13/2020', 52)]

输出:

[('1/13/2020', 50, '2020-01-13'), ('1/13/2020', 49, '2020-01-13'), ('1/13/2020', 52, '2020-01-13')]