将日期时间转换为纪元时出错,添加 5 秒,然后转换回日期时间



我在 python 中获取 csv 文件中的字符串时间以转换为纪元时遇到问题。我长期尝试做的是从csv中获取日期时间,转换为纪元,添加5秒,转换回日期时间,然后将其用作新变量。

但是,我尝试的任何方法都只会返回格式错误....

ValueError: time data '"2019-04-03 09:01:14.000000"' does not match format '%Y-%m-%d %I:%M:%S.%f'

任何帮助,不胜感激。

我已经尝试了datetime.datetime,使用日历等。都返回格式错误,但我无法破译它抛出的格式。

这是整个代码。注释掉是我将来尝试使用代码的地方。(CSV 格式:日期时间、IP、电子邮件、消息、电子邮件)

import datetime, re, time
_global_path = r'C:UsersDArthurDocumentsITD Metrics'
with open(_global_path + '/eop_incidents.csv', 'r') as f:
pattern = '%Y-%m-%d %I:%M:%S.%f'
find_last = (f.readlines()[-1].strip().split(','))
net_earliest = find_last[0]  # .replace(':', '-')
#change_to_epoch = int(time.mktime(time.strptime(net_earliest, pattern)))

#temp = change_to_epoch + 5
#temp = datetime.datetime.utcfromtimestamp(temp).strftime(pattern)
#final_earliest = str(temp)

print(pattern)
#print(find_last)
print(net_earliest, type(net_earliest))
#print(change_to_epoch)

#print(temp, type(temp))
#print(final_earliest, type(final_earliest))

这些是我得到的结果(出于安全原因已编辑,抱歉。

%Y-%m-%d %I:%M:%S.%f

['"2019-04-03 09:01:14.000000", "IP", "电子邮件", "味精", "电子邮件"] "2019-04-03 09:01:14.000000"

我正在寻找的是 2019-04-03 09:01:14.000000 到 2019-04-03 09:01:18.0000000 的"纪元"。

感谢大家的帮助!

您需要将字符串转换为日期时间元组,然后将时间增量添加到原始时间。这样:

#original string
string_time='2019-04-03 09:01:14.000000'
#Conversion
tm = datetime.datetime.strptime((string_time),  '%Y-%m-%d %H:%M:%S.%f')
#Add the timedelta
future_or_past_time = tm + datetime.timedelta(seconds=4)
print future_or_past_time
>>> 2019-04-03 09:01:18

在这种情况下,要添加的时间增量可以是秒、小时、天等。

希望有帮助。

对于仍在查看的任何人,我发现了格式问题。

问题出在 CSV 文件中。它返回的格式为"2019-04-03 09:01:14.000000"。需要的是:"2019-04-03 09:01:14.000000"。

注意:格式化时要注意双引号... :)

最新更新