比较两个 Python 3 日期时间对象返回“无法比较偏移天真和偏移感知日期时间:TypeError”

jel*_*ens 5 python datetime python-3.x

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

if launchTime < datetime.datetime.now()-datetime.timedelta(seconds=20):
Run Code Online (Sandbox Code Playgroud)

其中launchTime 是datetime 类型。但是,当我运行它时,我收到错误

can't compare offset-naive and offset-aware datetimes: TypeError
Run Code Online (Sandbox Code Playgroud)

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

编辑下面的固定代码 -----------------------------------------

if launchTime.replace(tzinfo=None) < datetime.datetime.now()-datetime.timedelta(minutes=4):
Run Code Online (Sandbox Code Playgroud)

还有完整的代码,以防将来有人发现它有价值。Python 3 可以停止已运行“x”时间的 EC2 实例。在这种情况下,如果实例运行了五分钟。终止它。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"]
                    ]
                )
Run Code Online (Sandbox Code Playgroud)

Dem*_*cht 7

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

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

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

  • 哦!请注意,在这种情况下,您需要确保时区匹配。 (3认同)

Vik*_*dar 5

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

import pytz

utc=pytz.UTC
launchTime = utc.localize(launchTime) 
Run Code Online (Sandbox Code Playgroud)