我正在创建具有以下条件的if语句: 如果date_today> =过期日期: 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'
我只想检查今天的日期是否大于或等于到期日期。但是我无法弄清楚。
答案 0 :(得分:1)
如果expiredate
是字符串,则需要使用strptime:
from datetime import datetime as dt
dt.strptime("2019-07-31", "%Y-%m-%d")