【问题标题】:How to check if a date is earlier than today's date如何检查日期是否早于今天的日期
【发布时间】:2018-04-05 12:58:00
【问题描述】:

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

程序获取到期日期。我正在使用该到期日期并将其设置为变量 datd

在下面的示例中,我们假设给出的到期日期是 2018 年 1 月 10 日。 (注意: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 年 1 月 10 日早于今天的 2017 年 10 月 24 日。 有没有办法正确更改日期的格式,以便在此程序中正确读取它们?

如果 datd = 1/10/2018,我希望输出显示 “密码未过期”

【问题讨论】:

标签: python python-3.x


【解决方案1】:
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() 将日期时间与每日日期进行比较。

警告:如果您希望 100% 正确且纯粹,请注意时区相关问题。确保在您的 Windows 域等中假定哪个时区。

参考:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-06
    • 2012-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多