首页 > 解决方案 > 将日期时间转换为纪元时出错,增加 5 秒,然后转换回日期时间

问题描述

我在获取 csv 文件中的字符串时间以转换为 Python 内部的纪元时遇到问题。我长期想做的是从 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,使用 calander 等。都返回格式错误,但我无法破译它抛出的格式。

这是整个代码。注释是我将来尝试使用代码的地方。(CSV 格式:日期时间、IP、Email、Msg、Email)

import datetime, re, time
_global_path = r'C:\Users\DArthur\Documents\ITD 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"', '"EMAIL"', '"MSG"', '"EMAIL"'] "2019-04-03 09:01: 14.000000"

我正在寻找的是 2019-04-03 09:01:14.000000 到 'epoch' 到 2019-04-03 09:01:18.000000。

感谢大家的帮助!

标签: pythoncsvdatetimeepoch

解决方案


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

#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

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

希望有帮助。


推荐阅读