比较EC2实例和当前时间在Python的发射时间时间、实例、Python

2023-09-11 09:16:38 作者:眼泪都在笑我傻

我提取EC2实例launch_time,它返回一个单code字符串是这样的:

I extract the launch_time from EC2 instance, it returns a unicode string like this:

2014-12-22T08:46:10.000Z

2014-12-22T08:46:10.000Z

我用dateutil解析器将其转换为DATETIME与

I use dateutil parser to convert it to datetime with

launch_time = parser.parse(instance.launch_time)

让我得到lunch_time转换后是这样的:

so I get lunch_time after converted like this:

2014年12月22日08:46:10 + 00:00

2014-12-22 08:46:10+00:00

和我想比较这launchtime与当前的时间,看看多久,这种情况已经运行。

And I want to compare this launchtime with current time to see how long this instance has been running.

我得到CURRENT_TIME有:

I get current_time with:

current_time = datetime.datetime.now()

和我得到这样的:

2014年12月22日11:46:10.527010

Python开发者的完美终端工具

2014-12-22 11:46:10.527010

现在我有两个时间戳,我有这个功能

Now I have two timestamps, I have this function

def timeDiff(launch_time, current_time):
    running_time = current_time - launch_time
    return running_time.seconds/60

我预计结果将180分钟(3小时)。但我得到这个错误:

I expect the result would be 180 minutes (3 hours). But I got this error:

类型错误:不能减去偏移天真和偏移感知日期时间

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

我觉得有这两个时间戳之间的明显差异。我需要比较确切的日期和时间才能看到它已经运行了多长时间。我无法找到一个合适的方法来解决这个问题。任何想法AP preciated!

I think there's obvious difference between these two timestamps. I need to compare exactly date and time to see how long it has been running. I couldn't find a proper way to solve this. Any thoughts appreciated!

推荐答案

您现在可以指定所需的时区从()这样的:

You can specify the timezone you want from now() like the following:

CURRENT_TIME = datetime.datetime.now(launch_time.tzinfo)

那么你的减法应该工作,既是时代将时区知道。

Then your subtraction should work, as both of the times will be timezone aware.

编辑:我要指出,你可以把任何时区的对象,你要在 NOW(),它会工作得很好。 NOW()将时间到任何时区传递转换。最重要的部分是简单地保证,如果你加/减datetime对象,它们都具有时区(或它们都缺少时区)。

I should note that you can put whatever timezone object you want in now() and it will work just fine. now() will convert the time to whatever timezone you pass. The important part is to simply ensure that if you're adding/subtracting datetime objects that they both have timezones (or they both lack timezones).

 
精彩推荐
图片推荐