我有一个时间戳列表和一个键时间戳来查找最近的时间戳,它们的格式都是'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'
结束
有没有关于如何克服这个错误的建议
您可以尝试从
datetime
模块strptime()
将字符串转换为datetime对象:输出:
https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior
下面是完整的示例:
相关问题 更多 >
编程相关推荐