【问题标题】:Comparing dates isn't working as expected比较日期没有按预期工作
【发布时间】:2019-11-27 16:12:24
【问题描述】:

我正在创建一个具有以下条件的 if 语句: 如果 date_today >= expiredate: expiredate 是字符串格式的字典输出。 我尝试将其格式化为日期时间,以便检查它是否大于或等于今天:

import datetime
from datetime

date_today = datetime.date.today()

for list in dict: # Getting the data out of a list of dicts    
    expiringdate = list.get('expiredate')  # Retrieving the expiredate strings.
    expiredate = datetime.datetime.strftime(expiringdate, '%Y-%m-%d') # Setting the expiredate variable to a datetime format. 
    if date_today >= expiredate:  # Checking if the date is greater then or equal to the other date.
        print('yeah it worked')
    else:
        print('it didn't work')

我收到以下错误。

expiredate = datetime.datetime.strftime(expiredate, '%Y-%m-%d')
TypeError: descriptor 'strftime' requires a 'datetime.date' object but received a 'str'

我只想检查今天的日期是否大于或等于过期日期。但我想不通。

【问题讨论】:

  • 什么是到期日?

标签: datetime python-3.6 python-3.7


【解决方案1】:

如果expiredate 是字符串则需要使用strptime:

from datetime import datetime as dt

dt.strptime("2019-07-31", "%Y-%m-%d")

【讨论】:

  • 我明白了!非常感谢。我使用了strftime,但我需要使用strptime。
猜你喜欢
  • 2013-01-31
  • 1970-01-01
  • 1970-01-01
  • 2018-01-21
  • 1970-01-01
  • 2020-03-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多