python 中最近的时间戳
Nearest timestamp in 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'
关于如何克服这个错误有什么建议吗?
您可以尝试 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))
我有一个时间戳列表和一个关键时间戳来找到最近的时间戳,两者的格式都是 '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'
关于如何克服这个错误有什么建议吗?
您可以尝试 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))