【问题标题】:Python compare a datetime with a str with the same formatPython将日期时间与具有相同格式的str进行比较
【发布时间】:2016-06-23 16:06:07
【问题描述】:

我得到了这两个值来比较

第一个来自 str 格式的 API,第二个来自函数 datetime.datetime.now()

2016-06-23 11:05:42.0
<class 'str'>

2016-06-23 18:00:03.063287
<class 'datetime.datetime'>

我无法比较它们

    if datetime.datetime.strftime(C[5],'%Y-%m-%d %H:%M:%S.%f') <= now:
        AA.append(C)

但它会引发以下错误

TypeError:描述符“strftime”需要一个“datetime.date”对象,但 收到一个'str'

【问题讨论】:

  • 您可以使用 strptime,但实际上不需要使用 datetime,因为可以安全地比较字符串,因此只需调用 str(now)
  • 不,我无法直接比较它们。但是 strptime 有效。谢谢
  • 你怎么能不呢?时间格式是24小时,日期格式是年月日怎么会失败呢?

标签: python datetime


【解决方案1】:

您将使用 `strptime 并将字符串解析为日期时间对象:

In [27]: s = "2016-06-23 11:05:42.0"

In [28]: datetime.datetime.strptime(s,'%Y-%m-%d %H:%M:%S.%f')
Out[28]: datetime.datetime(2016, 6, 23, 11, 5, 42)

但您实际上并不需要使用 strptime,因为可以安全地按字典顺序比较字符串,因此您只需调用 str(now):

In [23]: "2016-06-23 11:05:42.0" < str(datetime.datetime.now())
Out[23]: True
In [24]: "2016-06-23 17:12:42.0" < str(datetime.datetime.now())
Out[24]: False

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-30
    • 2014-05-03
    • 1970-01-01
    • 2012-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多