0

我有一个时间戳列表和一个关键时间戳来找到最近的时间戳,两者都采用格式'2019-11-22T11:37:52.338Z'

我已经尝试过这个解决方案Python - 定位最近的时间戳,但由于我的时间戳在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'

有关如何克服此错误的任何建议?

4

1 回答 1

1

您可以尝试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))
于 2021-01-12T07:09:59.953 回答