[英]How can I take list of Dates from csv (as strings) and return only the dates/data between a start date and end date?
I have a csv file with dates in format M/D/YYYY from 1948 to 2017. I'm able to plot other columns/lists associated with each date by list index.我有一个 csv 文件,其日期格式为 M/D/YYYY 从 1948 年到 2017 年。我可以通过列表索引 plot 与每个日期关联的其他列/列表。 I want to be able to ask the user for a start date, and an end date, then return/plot the data from only within that period.
我希望能够向用户询问开始日期和结束日期,然后仅在该期间返回/绘制数据。
Problem is, reading dates in from the csv, they are strings so I cannot use if date[x] >= startDate && date[x] <= endDate
because theres no way for me to turn dates in this format to integers.问题是,从 csv 读取日期,它们是字符串,所以我不能使用
if date[x] >= startDate && date[x] <= endDate
因为我无法将这种格式的日期转换为整数。
Here is my csv file 这是我的 csv 文件
I am already able to read in the dates from the csv to its own list.我已经能够阅读从 csv 到它自己的列表的日期。
How can I take the dates in my list and only return the ones within the user specified date range?如何获取列表中的日期并仅返回用户指定日期范围内的日期?
Here is my function for plotting the entire dataset right now:这是我现在绘制整个数据集的 function:
#CSV Plotting function
def CSV_Plot (data,header,column1,column2):
#pyplot.plot([item[column1] for item in data] , [item[column2] for item in data])
pyplot.scatter([item[column1] for item in data] , [item[column2] for item in data])
pyplot.xlabel(header[column1])
pyplot.ylabel(header[column2])
pyplot.show()
return True
CSV_Plot(mycsvdata,data_header,dateIndex,rainIndex)
This is how I am asking the user to input the start and end dates:这就是我要求用户输入开始日期和结束日期的方式:
#Ask user for start date in M/D/YYY format
startDate = input('Please provide the start date (M/D/YYYY) of the period for the data you would like to plot: ')
endDate = input('Please provide the end date (M/D/YYYY) of the period for the data you would like to plot: ')
You need to compare the dates.您需要比较日期。
I would suggest parsing the dates from your CSV into a datetime
object, and also turning the user input value into a datetime
object.我建议将 CSV 中的日期解析为
datetime
时间 object,并将用户输入值转换为datetime
时间 object。
How to create a datetime object from a string?如何从字符串创建日期时间 object? You need to specify the format string and the
strptime()
will parse it for you.您需要指定格式字符串,
strptime()
将为您解析它。 Details here: Converting string into datetime此处的详细信息: 将字符串转换为日期时间
In your case, it could be something like在您的情况下,它可能类似于
from datetime import datetime
# Considering date is in M/D/YYYY format
datetime_object1 = datetime.strptime(date_string, "%m/%d/%Y")
Then you can compare them with a >
or <
operator.然后您可以将它们与
>
或<
运算符进行比较。 Here you can find details of how to compare the dates . 在这里您可以找到有关如何比较日期的详细信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.