【问题标题】:How to compare ISO-8601 dates in python如何在 python 中比较 ISO-8601 日期
【发布时间】:2018-06-12 08:27:55
【问题描述】:

我有一个 ISO-8601 格式的日期

date="2018-03-13T17:22:20.065Z"

我想以iso9621 格式查找当前UTC 时间。 我找到了一些代码 sn-p,例如 datetime.datetime.utcnow().isoformat()

这给了我们以下结果

2018-06-12T08:19:28.954375

我想查看提供的日期是否超过 30 天。

我试图解决它,如图所示 question

import datetime
import dateutil.parser

insertion_date = dateutil.parser.parse('2018-03-13T17:22:20.065Z')
diffretiation=datetime.datetime.utcnow().isoformat() - insertion_date


print diffretiation 
print insertion_date

if diffretiation.days>30:
    print "The insertion date is older than 30 days"

else:
    print "The insertion date is not older than 30 days"

我在这里发现了以下错误

Traceback (most recent call last):
  File "test2.py", line 5, in <module>
    right_now_30_days_ago=datetime.datetime.utcnow().isoformat() - insertion_date
TypeError: unsupported operand type(s) for -: 'str' and 'datetime.datetime'

在这里任何帮助都会很棒

【问题讨论】:

  • 我不明白您为什么要将一个字符串转换为日期,而将另一个日期转换为字符串,然后减去它们。您应该进行字符串->日期转换并保持其他日期不变。
  • 我对这里可以做什么的解决方案感到困惑
  • 停止将diffretiation转换为字符串;删除对isoformat()的调用。

标签: python datetime iso8601


【解决方案1】:

您的datetime.datetime.utcnow() 不知道时区,并使其知道使用pytz

import datetime
import dateutil.parser
import pytz

insertion_date = dateutil.parser.parse('2018-03-13T17:22:20.065Z')
diffretiation = pytz.utc.localize(datetime.datetime.utcnow()) - insertion_date


print diffretiation 
print insertion_date

if diffretiation.days>30:
    print "The insertion date is older than 30 days"

else:
    print "The insertion date is not older than 30 days"
#The insertion date is older than 30 days

附: datetime.datetime.utcnow().isoformat() 返回一个字符串,这就是你遇到的错误。

【讨论】:

    猜你喜欢
    • 2012-11-22
    • 2016-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-14
    • 2013-02-03
    • 2022-10-20
    • 2013-04-21
    相关资源
    最近更新 更多