如何检查日期是否早于今天的d

2024-05-03 18:20:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个运行Windows“net user”命令的程序来获取用户的到期日期。例如:“net user justinb/domain”

程序获取到期日期。我把到期日期设为变量datd

在下面的例子中,我们假设给出的到期日期是2018年10月1日。(注意:Windows不在月前加0)

import time

datd = "1/10/2018"

# places a 0 in front of the month if only 1 digit received for month
d = datd.split("/")
if len(d[0])==1:
    datd="0"+datd
    print("Changed to: " + datd)

myDate = (time.strftime("%m/%d/%Y"))

print ("This is today's date: " + myDate)

if datd <= myDate:    # if datd is is earlier than todays date
    print (" Password expired. ")
else:
    print (" Password not expired. ")

input(" Press Enter to exit.")

现在,如果datd等于2017年的某个日期,它会给我正确的信息。不过,我对2018年及以后的日子感到不快。它告诉我,2018年10月1日在今天2017年10月24日之前。 我有没有办法适当地改变日期的格式,以便在这个程序中正确地读取它们?

我想让输出说明如果datd=1/10/2018,“密码未过期”


Tags: to程序datenetiftimeiswindows
1条回答
网友
1楼 · 发布于 2024-05-03 18:20:37
from datetime import datetime

string_input_with_date = "25/10/2017"
past = datetime.strptime(string_input_with_date, "%d/%m/%Y")
present = datetime.now()
past.date() < present.date()

这应该能帮你完成任务!两个处理日的格式都是前导0或不前导0。

使用.date()将日期时间与每日日期范围进行比较。

警告:如果你想百分之百的正确和纯粹的照顾时区相关的问题。确保在您的windows域中假定时区等

参考:

日期时间strtime-https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior

相关问题 更多 >