查找与fi中的时间戳更接近的时间戳

2024-06-16 10:12:11 发布

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

我编写了一个脚本,在这个脚本中,给定一个时间戳,它在一个文件中查找相同的时间戳,该文件包含以不同格式编写的不同时间戳

代码如下:

import pytz, datetime
import re
from dateutil.parser import parse

local = pytz.timezone ("Europe/Zurich")
naive = datetime.datetime.strptime ("2018-9-13 12:46:00", "%Y-%m-%d %H:%M:%S")
local_dt = local.localize(naive, is_dst=None)
utc_dt = local_dt.astimezone(pytz.utc)
print 'utc_dt = ', utc_dt

utc_fileFormat=utc_dt.isoformat()
print 'utc_dt.isoformat() = ', utc_fileFormat

string=parse(utc_fileFormat)
print string

new_string=string.strftime('%Y-%m-%dT%H:%M:%S')
if new_string.endswith('+00:00'):
    new_string = new_string[:-6]
print new_string

with open('fill_7151_B1_timestamps.txt', 'r') as file:
    for line in file:
        if new_string in line:
            print line
file.close()

现在我想做的是:如果我给出的时间戳与文件中的时间戳不完全对应,我必须找到更接近的时间戳

为了了解文件中的数据,它们如下所示:

0 2018-07-30T15:20:36.524281125
1 2018-07-30T15:21:12.821653375
2 2018-07-30T15:21:29.271170975
3 2018-07-30T15:21:30.381507275
4 2018-07-30T16:13:05.816863525
5 2018-07-30T16:13:06.958256975
6 2018-07-30T16:13:08.082365950
7 2018-07-30T16:13:09.221720400
8 2018-07-30T16:13:10.359005400
9 2018-07-30T16:13:11.487593100
10 2018-07-30T16:13:12.626307750

有人能帮我吗?谢谢


Tags: 文件import脚本newdatetimestringlocalline