【问题标题】:Get current date/time and compare with other date获取当前日期/时间并与其他日期进行比较
【发布时间】:2015-12-05 16:26:33
【问题描述】:

我正在尝试获取当前时间,并将其与从字符串中获取的日期进行比较。 这是我的代码:

import datetime

CurrentDate = str(datetime.datetime.now())
CurrentDate = datetime.strptime(CurrentDate, "%d/%m/%Y %H:%M")
print(CurrentDate)

ExpectedDate = "9/8/2015 4:00"
ExpectedDate = datetime.datetime.strptime(ExpectedDate, "%d/%m/%Y %H:%M")
print(ExpectedDate)

if CurrentDate > ExpectedDate:
    print("Date missed")
else:
    print("Date not missed")

但这是我得到的错误。

CurrentDate = datetime.strptime(CurrentDate, "%d/%m/%Y %H:%M") AttributeError: 'module' 对象没有属性 'strptime'

【问题讨论】:

  • 每个帖子一个问题,不要将日期作为字符串进行比较,请在提问之前尝试一些基本的调试。阅读您的错误行应该很明显您正在调用 strptime 错误,应该通过快速访问文档来纠正。

标签: python python-3.x


【解决方案1】:

datetime.datetime.now() 转换为字符串没有多大意义,只是这样您就可以将其转换回日期时间。保持原样。

import datetime

CurrentDate = datetime.datetime.now()
print(CurrentDate)

ExpectedDate = "9/8/2015 4:00"
ExpectedDate = datetime.datetime.strptime(ExpectedDate, "%d/%m/%Y %H:%M")
print(ExpectedDate)

if CurrentDate > ExpectedDate:
    print("Date missed")
else:
    print("Date not missed")

结果:

2015-09-09 12:25:00.983745
2015-08-09 04:00:00
Date missed

【讨论】:

  • 它可能会在 DST 转换期间失败。您应该使用 UTC 时间或时区感知的日期时间对象。这是possible solutions
【解决方案2】:

在 datetime 模块中,还有一个名为 datetime 的类,您可能知道,因为您在其余代码中正确地使用了它。

你的第三行应该是:

CurrentDate = datetime.datetime.strptime(CurrentDate, "%d/%m/%Y %H:%M")

在两个datetimes 中,只有一个。该行引发错误。 或者,您可以只导入整个类:

from datetime import datetime

并且不需要指定datetime 两次,这更容易一些。

编辑:正如两位炼金术士所指出的(老实说,我没有注意到)是你通过一个字符串比较日期,这不是 去工作 一个好的做法。查看this question 中的各种 sn-ps,了解在 Python 中比较日期而不将它们转换为字符串。

【讨论】:

  • "您正在通过一个不起作用的字符串比较日期。"你能再解释一下吗?为什么不能比较使用strptime 从字符串中提取的两个日期?另外,您对使用提议的更改修改原始代码时出现的错误ValueError: time data '2015-09-09 11:47:34.298745' does not match format '%d/%m/%Y %H:%M' 有何评论?
  • 我的 Python 有点生锈了。显然它确实有效,但在我看来,比较 Date 值而不是日期作为字符串的值是更好的做法。谷歌这个,我错了。我已经编辑了我的答案以反映您指出的内容。关于你的第二个问题,你应该尝试切换 %d 和 %m。我认为它们的顺序不同:)
  • 切换“d”和“m”仍然会产生 ValueError。我很确定这是因为字符串的“秒”部分没有被处理。
  • 嗯,正如所指出的 [docs.python.org/2/library/… 文档),%H 分隔符用于“零填充十进制数”。我相信这是一个解释,因为 ExpectedDate 变量中的日期是“4:00”。尝试将其更改为“04:00”。此外,如果您使用 12 小时制,请使用 %I 分隔符。
  • 但错误发生在CurrentDate 代码中,而不是ExpectedDate 代码中。
【解决方案3】:

我发现这个出色的module 让日期操作变得如此简单:

import arrow

n = arrow.utcnow()
expected = arrow.get("9/8/2015 4:00", "D/M/YYYY H:m")

if n > expected:
    print("Date Missed.")
else:
    print("Date not missed.")

【讨论】:

  • 注意:arrow 假设这里的输入是 UTC 时间(这很好)。但是 OP 使用 datetime.now() 这意味着输入可能是本地时间(可能与 UTC 不同)。
  • 你是对的,但似乎你可以做到:arrow.get(datetime.now()) :)
  • 这也是不正确的。它将输入的原始日期时间对象解释为错误的 UTC 时间(datetime.now() 表示本地时间)。即使Arrow 对象仅用于比较;对于任何具有非固定 UTC 偏移量的本地时区(其中大部分),它都可能失败。
猜你喜欢
  • 2016-07-24
  • 1970-01-01
  • 1970-01-01
  • 2019-09-26
  • 2017-05-15
  • 2017-05-04
  • 2022-01-16
  • 2018-07-22
  • 1970-01-01
相关资源
最近更新 更多