python根据日期打印出csv数据

时间:2017-01-25 20:25:39

标签: python csv

我有一个python程序会打印出csv列“过期日期”和“帐户名称”。如果“到期日期”中的日期距离代码执行时间仅3天,我将如何编写代码以仅打印出帐户列?

csv的例子

到期日期帐户名称 1/2/17 mary 4433 12/25/2018 bob 1244 1/17/2017 david 1234

到目前为止的

代码

import csv
with open('ResellerAccounts-1.csv') as csvfile:
    readCSV = csv.reader(csvfile, delimiter=',')
    accounts = []
    expiries = []
    for row in readCSV:
        account = row[0]
        expire = row[7]
        expiries.append(expire)
        accounts.append(account)
print(accounts)
print(expiries)

谢谢!

2 个答案:

答案 0 :(得分:1)

您可以在当天添加3天,然后将该值与行[0]中的到期日期进行比较(如果它们与打印帐户匹配

    import datetime
import csv
i = datetime.datetime.now()
end_date = i + datetime.timedelta(days=3)
end_date=end_date.strftime("%m/%d/%Y")


with open('ResellerAccounts-1.csv') as csvfile:
    readCSV = csv.reader(csvfile, delimiter=',')
    next(readCSV, None)  # skip the headers
    for row in readCSV:
        #compare the expiration date from row against current date + 3 
        if datetime.datetime.strptime(row[0],"%m/%d/%Y")==datetime.datetime.strptime(end_date,"%m/%d/%Y"):
            print row[2] # should print all rows matching the date 1/28/2017 for today's run

示例输入

1/28/2017, mary, 4433 
12/25/2018, bob, 1244 
1/31/2017, david, 1234

输出

  4433

答案 1 :(得分:0)

使用它以及写入txt文件的数字。谢谢大家的帮助!

import datetime
import csv
from datetime import datetime,timedelta

#date, replace with the number gap you need
days=3
dt=(datetime.now() + timedelta(days)).strftime('%#m/%d/%Y')
text=open("call.txt","w")

with open("ResellerAccounts-1.csv", 'r') as f:
    reader = csv.reader(f)
    next(reader)
    for r in reader:

        if r[7]==dt:
            #print the row mathing the date
            #print (r)
            t=r[0].split(" ")
            number=int(t[1])

            #print the number and the incremented number
            #print (t[1],number)
            text.write(str(number))
            text.write("\n")

print("Done..!!")
text.close()