【问题标题】:Comparing two Python 3 datetime objects returns "can't compare offset-naive and offset-aware datetimes: TypeError"比较两个 Python 3 日期时间对象返回“无法比较 offset-naive 和 offset-aware datetimes: TypeError”
【发布时间】:2018-05-10 04:37:14
【问题描述】:

我正在尝试将日期时间类型的 AWS EC2 实例对象的时间与表示为 datetime.datetime.now 的另一个日期时间进行比较。有问题的代码行看起来像,

if launchTime < datetime.datetime.now()-datetime.timedelta(seconds=20):

其中launchTime 是日期时间类型。但是,当我运行它时,我得到了错误

can't compare offset-naive and offset-aware datetimes: TypeError

而且我不确定如何以可以成功比较它的方式转换 launchTime。

修改了下面的固定代码-------------------------------------------

if launchTime.replace(tzinfo=None) < datetime.datetime.now()-datetime.timedelta(minutes=4):

还有完整的代码,以防将来有人发现它有价值。停止运行“x”时间的 EC2 实例是 Python 3。在这种情况下,如果一个实例运行了五分钟。终止它。 lambda 本身也使用 Cloudwatch 设置为每 4 分钟运行一次。

import boto3
import time
import datetime

#for returning data about our newly created instance later on in fuction
client = boto3.client('ec2')

def lambda_handler(event, context):

response = client.describe_instances()
#for each instance currently running/terminated/stopped
for r in response['Reservations']:
    for i in r['Instances']:
        #if its running then we want to see if its been running for more then 3 hours. If it has then we stop it. 
        if i["State"]["Name"] == "running":
            launchTime = i["LaunchTime"]

            #can change minutes=4 to anything
            if launchTime.replace(tzinfo=None) < datetime.datetime.now()-datetime.timedelta(minutes=4):
                response = client.stop_instances(
                    InstanceIds=[
                        i["InstanceId"]
                    ]
                )

【问题讨论】:

  • launchTime 是一个字符串?能举个例子吗?
  • 一个偏移天真的日期时间没有tzinfo
  • launchTime 不是字符串,在打印 launchTime 时我得到“2018-05-10 03:32:12+00:00”,在打印 launchTime 类型时我得到“"
  • 但是当您打印datetime.datetime.now() 时看到区别了吗?注意没有时区信息?

标签: python python-3.x datetime


【解决方案1】:

主要问题是我假设launchTime 可以识别时区,而datetime.now() 不是(datetime.now().tzinfo == None)。

有几种方法可以解决这个问题,但最简单的方法是从 launchTime 中删除 tzinfo:if launchTime.replace(tzinfo=None) &lt; datetime.datetime.now()-datetime.timedelta(seconds=20) 应该可以解决问题。

或者,您可以将日期时间对象转换为 Unix 时间戳,然后您就不必处理时区的愚蠢问题。

【讨论】:

  • 做到了。非常感谢您的意见
  • 不!请注意,在这种情况下,您需要确保时区匹配。
  • @jelidens 您的 launchTime 有 UTC 时区信息 (+00:00)。那是你的时区吗?
  • @PM 2Ring,不,我认为我不在 (+00:00) 时区?但我也不确定这种情况下的 launchTime 是否基于我所在的位置或 AWS 上的 Lambda 函数所在的位置。
  • @jelidens 我认为您需要阅读有关时区以及我之前链接的 Python 的 tzinfo 的信息。
【解决方案2】:

试试这样,你必须确保安装了pytz:

import pytz

utc=pytz.UTC
launchTime = utc.localize(launchTime) 

【讨论】:

  • 你确定你安装了 pytz 吗?
  • 下面列出了不需要任何其他外部依赖项的修复程序。感谢大家的投入!
猜你喜欢
  • 2017-03-26
  • 2021-03-23
  • 2018-02-27
  • 2012-05-26
  • 2017-09-16
  • 1970-01-01
  • 2013-09-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多