【问题标题】:Deleting all rows if the date is invalid如果日期无效,则删除所有行
【发布时间】:2020-07-03 11:10:52
【问题描述】:

我在数据字典中有 26 个元素,都是列表。我正在提取日期范围内的列表。

  • 如果日期无效,则会引发错误。在 dt_dates 行中,我需要删除所有列表中的无效行,包括日期。
dates = datas['Date']
serials = datas['Serial_No']
dt_dates = [datetime.strptime(date, '%Y-%m-%d %H:%M:%S') for date in dates]
in_between_dates = []
in_between_serial = []
for i,d in enumerate(dt_dates,0):
    if d.date() >= Start_Date.get_date() and d.date() <= End_Date.get_date():
        in_between_dates.append(d)
        in_between_serial.append(serials[i])

【问题讨论】:

  • 请阅读并关注minimal reproducible exampleHow to Ask。你的代码是错误的、不完整的,如果没有你操作的至少一部分数据,整个事情就不清楚了。
  • 我认为现在这个问题看起来很适合回答
  • NameError on:datas, Start_Date, End_Date(并且缺少导入)。 “# 24 lines like this”对我来说毫无意义(除非你以某种方式解析 24 个不同类型的日期格式字符串?) - 请阅读minimal reproducible example

标签: python python-3.x list date dictionary


【解决方案1】:
dates = datas['Date']
serials = datas['Serial_No']

#24 lines like these
print(len(dates))
dt_dates = [datetime.strptime(date, '%Y-%m-%d %H:%M:%S') for date in dates]

#Simulate invalid date here
in_between_dates = []
in_between_serial = []

#24 lines like these
for i,d in enumerate(dt_dates,0):
    try:
        if d.date() >= Start_Date.get_date() and d.date() <= End_Date.get_date():
            in_between_dates.append(d)
            in_between_serial.append(serials[i])
    except:
        print('Invalid date skipped')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多