python中的最近时间戳

2024-10-05 14:22:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个时间戳列表和一个键时间戳来查找最近的时间戳,它们的格式都是'2019-11-22T11:37:52.338Z'

我已经尝试过这个解决方案Python - Locating the closest timestamp,但是由于我的时间戳在string中,所以导致了一个错误。当我试着按如下所示打字时

def nearest(ts):
s = sorted(timestamp_list)
i = bisect_left(s, ts)
return min(s[max(0, i-1): i+2], key=lambda t: abs(int(ts) - int(t)))

ValueError: invalid literal for int() with base 10: '2019-11-22T11:37:52.338Z'结束

有没有关于如何克服这个错误的建议


Tags: the列表stringdef格式错误时间解决方案
1条回答
网友
1楼 · 发布于 2024-10-05 14:22:15

您可以尝试从datetime模块strptime()将字符串转换为datetime对象:

from datetime import datetime

ts = '2019-07-22T11:37:52.338Z'
datetime_object = datetime.strptime(ts, '%Y-%m-%dT%H:%M:%S.%fZ')

print(datetime_object)

输出:

2019-07-22 11:37:52.338000

https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior


下面是完整的示例:

from bisect import bisect_left
from datetime import datetime


ts_list_str = ['2010-11-22T11:37:52.338Z', '2018-11-22T11:37:52.338Z', '2017-11-22T11:37:52.338Z']
ts_list = [datetime.strptime(ts, '%Y-%m-%dT%H:%M:%S.%fZ') for ts in ts_list_str]

def nearest(ts):
    s = sorted(ts_list)
    i = bisect_left(s, ts)
    return min(s[max(0, i-1): i+2], key=lambda t: abs(ts - t))

ts_str = '2019-07-22T11:37:52.338Z'
ts = datetime.strptime(ts_str, '%Y-%m-%dT%H:%M:%S.%fZ')

print(nearest(ts))

相关问题 更多 >