将datetime转换为epoch时出错,请加5秒,然后再转换回datetim

2024-09-27 09:33:08 发布

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

我在获取csv文件中的字符串时间以转换为Python内部的epoch时遇到了一个问题。我要做的是从csv中获取datetime,转换成epoch,加上5秒,转换回datetime,然后把它作为一个新变量

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

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格式:datetime,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”','“电子邮件”,'“MSG”,'“电子邮件”] “2019-04-03 09:01:14.000000”

我要找的是2019-04-03 09:01:14.000000到‘epoch’到2019-04-03 09:01:18.000000

谢谢你的帮助


Tags: csvtodatetimenettime格式findchange
2条回答

对于仍在查看的人,我发现格式有问题

问题在CSV文件中。它返回的格式是“2019-04-03 09:01:14.000000”。我们需要的是:“2019-04-03 09:01:14.000000”

注意:格式化时请注意双引号…:)

您需要将字符串转换为datetime元组,然后向原始时间添加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

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

希望有帮助

相关问题 更多 >

    热门问题