python - 比较两个 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"]
]
)
解决方案
主要问题是我假设launchTime
是时区感知的,而datetime.now()
不是(datetime.now().tzinfo == None
)。
有几种方法可以解决这个问题,但最简单的方法是从launchTime
:中删除 tzinfoif launchTime.replace(tzinfo=None) < datetime.datetime.now()-datetime.timedelta(seconds=20)
应该可以解决问题。
或者,您可以将 datetime 对象转换为 Unix 时间戳,然后您就不必处理时区的愚蠢问题。
推荐阅读
- sql-server - 在 SQL Server 中创建公式
- geocode - Geocoder API - 从物理地址获取 Lat,Lng
- java - 使用 System.err.println() 时的奇怪行为
- html - %include% 组件隐藏网页上的其他元素
- python - 输入数据框不是熊猫数据框
- reactjs - 反应路由器:路径='/'的路由不起作用
- html - 如何将图像放在一个部分中?
- html - 当其他元素居中对齐时,使用 Flexbox 将页脚与页面底部对齐
- ios - 具有谓词核心数据搜索的泛型方法不会返回正确的结果
- wordpress - 如何在 WooCommerce 中获得最畅销的产品类别 ID?