time.strptime函数的Python时间比较格式问题

时间:2018-11-29 11:04:29

标签: python python-2.7

我正在尝试使用time&datetime lib验证证书在5天后过期:

   print("Got date is >>>>", got_date)
        expiry_date = time.strptime(got_date["Enddate"], "%Y/%m/%d %H")
        print(" Expiry date is >>>>", expiry_date)
        today = datetime.now()
        print(" Today date is >>>", today)
        days_left = today - expiry_date
        print(days_left)
        if days_left > 5:
            print("Cert is expiring", i)
        else:
            print("Cert is not expiring for",i)

但随后出现错误:

*('Got date is >>>>', {'00': '00', 'Enddate': '2019/01/29 00'})*
*Traceback (most recent call last):
  File "C:/Python27/license_check.py", line 44, 
in <module>
    days_left = today - expiry_date
TypeError: unsupported operand type(s) for -: 'datetime.datetime' and 
'time.struct_time'*
**(' Expiry date is >>>>', time.struct_time(tm_year=2019, tm_mon=1, 
tm_mday=29, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=29, 
tm_isdst=-1))**
**(' Today date is >>>', datetime.datetime(2018, 11, 29, 18, 55, 8, 225000))**

我知道我要在这里比较2种不同的格式,但是我不确定如何将到期日和今天的日期都转换为同一格式,因此我可以知道证书是否实际上在5天后过期。 另外,我今天无法使用time.strptime函数转换为与expiry_date相同的变量。

对于使用2.7版的Python来说是新手,请提供帮助。

1 个答案:

答案 0 :(得分:0)

使用datetime.datetime.strptime

例如:

Enddate = '2019/01/29 00'
expiry_date = datetime.datetime.strptime(Enddate, "%Y/%m/%d %H")
today = datetime.datetime.now()

days_left = today - expiry_date
print(days_left)