python根据给定日期打印出csv数据

时间:2019-04-27 22:41:39

标签: python pandas csv

我有一个将从CSV打印出来的python程序。代码将要求用户输入开始日期和结束日期,并根据此范围程序返回温度。

以下是要求用户输入开始日期和结束日期的代码 (     导入csv     导入日期时间     导入时间     从datetime导入datetime     从日期时间导入timedelta

with open('preiction_system.csv', 'r') as csvFile:
    reader = csv.reader(csvFile)

    for row in reader:
        print(row)


ask=input("Enter start  Date\n")

fromDate = time.strptime(ask, "%Y-%m-%d")
start = time.strptime(time.strftime('%Y-%m-%d'),"%Y-%m-%d")


ask=input("Enter End Date\n")

fromDate = time.strptime(ask, "%Y-%m-%d")
end = time.strptime(time.strftime('%Y-%m-%d'),"%Y-%m-%d")

它根据用户输入的日期从csv返回行。

例如开始日期是2019-12-01,结束日期是2019-12-05

期望输出:

Date          maxtempC  mintempC    tempC
2019/12/01  29.80    25.35          29.80
2019/12/02  29.78    25.34          29.78
2019/12/03  30.61    24.53          30.61
2019/12/04  32.08    24.75          32.08
2019/12/05  30.42    24.74          30.42

1 个答案:

答案 0 :(得分:0)

可以使用pandas

import pandas as pd

df = pd.read_csv('preiction_system.csv')

#start = input("Enter start  Date\n")
#end = input("Enter end  Date\n")

start = "2019/12/02"
end = "2019/12/04"

result = df[ (df['Date'] >= start ) & (df['Date'] <= end) ]

print(result)

result.to_csv('output.csv')

使用csv可以更长

import csv

# ask before `for` loop
#start = input("Enter start  Date\n")
#end = input("Enter end  Date\n")

start = "2019/12/02"
end = "2019/12/04"

result = []

with open('preiction_system.csv', 'r') as csvFile:
    reader = csv.reader(file_object)

    header = next(reader) # get header
    print(header)
    result.append(result)

    for row in reader:
        if start<= row[0] <= end:
            print(row)
            result.append(row)

# TODO: write result in file