【问题标题】:How can I take list of Dates from csv (as strings) and return only the dates/data between a start date and end date?如何从 csv 获取日期列表(作为字符串)并仅返回开始日期和结束日期之间的日期/数据?
【发布时间】:2021-04-25 17:16:12
【问题描述】:

我有一个 csv 文件,其日期格式为 M/D/YYYY 从 1948 年到 2017 年。我可以通过列表索引绘制与每个日期关联的其他列/列表。我希望能够向用户询问开始日期和结束日期,然后仅返回/绘制该期间内的数据。

问题是,从 csv 中读取日期,它们是字符串,所以我不能使用 if date[x] >= startDate && date[x] <= endDate,因为我无法将这种格式的日期转换为整数。

Here is my csv file

我已经能够将 csv 中的日期读取到它自己的列表中。

如何获取列表中的日期并仅返回用户指定日期范围内的日期?

这是我现在绘制整个数据集的函数:

#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)

这就是我要求用户输入开始和结束日期的方式:

 #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: ')

【问题讨论】:

    标签: python csv date matplotlib plot


    【解决方案1】:

    您需要比较日期。

    我建议将 CSV 中的日期解析为 datetime 对象,并将用户输入值转换为 datetime 对象。

    如何从字符串创建日期时间对象?您需要指定格式字符串,strptime() 将为您解析它。详情在这里: Converting string into datetime

    在你的情况下,它可能是这样的

    from datetime import datetime
    
    # Considering date is in M/D/YYYY format
    datetime_object1 = datetime.strptime(date_string, "%m/%d/%Y")
    

    然后您可以将它们与>< 运算符进行比较。 Here you can find details of how to compare the dates.

    【讨论】:

    • 感谢您的优质回答。你认为在我的绘图函数的列表理解中这样做对我来说会更好,还是应该将整个列表转换为日期时间对象,然后针对它运行我的函数?
    • 这取决于您是否只需要绘制数据,或者您希望保留此过滤范围以进行其他操作。如果您只是过滤它以进行绘图,那么在列表理解中执行它就可以了,如果您对其执行其他操作,那么以某种方式构建您的数据会更好,例如作为一个字典,其中 datetime 是一个键,其余的of value 是一个命名元组。看看geeksforgeeks.org/namedtuple-in-python
    • 在您的情况下,它可能是例如Weather = namedtuple('Weather', ['prcp', 'tmax', 'tmin', 'rain']) 然后您将能够访问例如像这样的雨值:data[datetime1].rain
    • 谢谢 Flip,最后有人可以帮我理解我需要为我的 datetime 对象使用的格式吗?我列表中的日期格式为:'1948-01-01',我收到以下错误:ValueError: time data '1948-01-01' does not match format '%m/%d/%Y'
    • 我认为 '1948-01-01' 的格式可能是 %Y-%m-%d -> 请检查您的数据中的月份或日期是否位于首位。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-05
    • 1970-01-01
    • 2016-05-15
    • 2021-09-14
    • 2019-04-23
    相关资源
    最近更新 更多