【问题标题】:Date comaprison in python attribute errorpython属性错误中的日期比较
【发布时间】:2021-05-18 12:46:38
【问题描述】:

我有一个日期以"19 May 2021"这种格式存储在文本文件中,我想将此日期与今天的日期进行比较,以查看我们是否已达到此日期(> /

task_overview 中的逾期任务:

# Iterating through the file
from datetime import date as dt

overdue_tasks = overdue_tasks.split(", ")
dates = overdue_tasks[4] # This date is found in this index
date_obj = dt.strptime(dates, "%d %b %Y")
print(date_obj) # Trying to see if the date did convert

这是我得到的错误:

line 27, in <module>
date_obj = dt.strptime(dates, "%m %d %y")
AttributeError:
type object 'datetime.date' has no attribute 'strptime'

【问题讨论】:

  • from datetime import datetime as dt?

标签: python datetime attributeerror strptime


【解决方案1】:

strptime() 方法来自datetime.datetime,而不是datetime.time。请参阅datetime.datetime.strptime() 的文档。

所以你只需要改变

from datetime import date as dt

from datetime import datetime as dt

【讨论】:

  • 好的,我刚刚做了,现在我得到了这些错误:第 27 行,在 date_obj = dt.strptime(dates, "%m %d %y") ,第 568 行,在 _strptime_datetime tt, fraction, gmtoff_fraction = _strptime(data_string, format), line 349, in _strptime raise ValueError("time data %r does not match format %r" % ValueError: time data '20 Oct 2019' does not match format '%m %d %y'
  • @snlonline 你把月份和日期换成了格式。
  • @snlonline 另外,%y 应该是 %Y
  • @snlonline 最后,月份应该是%b
  • 是的,终于成功了,非常感谢,所以现在如果我得到当前日期,它也应该是这种格式?
【解决方案2】:
from datetime import datetime as dt

_your_date = "19 May 2021"

# your date
date_obj = dt.strptime(_your_date, "%d %b %Y")
now_date_obj = dt.now()


if date_obj < now_date_obj:    
    #TO DO
    print('reached')

else:
    #TO DO
    print('not reached')

【讨论】:

    猜你喜欢
    • 2020-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-23
    • 1970-01-01
    • 2023-03-27
    • 2017-06-28
    相关资源
    最近更新 更多