首页 > 解决方案 > 比较两个 Python 3 日期时间对象返回“无法比较 offset-naive 和 offset-aware datetimes: TypeError”

问题描述

我正在尝试将日期时间类型的 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"]
                    ]
                )

标签: pythonpython-3.xdatetime

解决方案


主要问题是我假设launchTime是时区感知的,而datetime.now()不是(datetime.now().tzinfo == None)。

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

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


推荐阅读