您可以尝试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))