我有一个数据文件,可以在日期分割。后来我发现2列的时差,即col[2] col[3]
。当我为两者编写单独的代码时,我可以很好地得到结果。但是现在我必须编写一个代码来按日期分割数据并计算时间差。可能两者同时。它只创建目录,然后给出下面的错误。如何读取文件并进行操作并再次将它们附加到相同的位置和相同的文件中。
输入:
3545 3140 1736190 1736241
4602 183 1736227 1738507
3545 3140 1736241 1736257
4945 3545 1737037 1737370
4945 3545 1737387 1737661
4391 2814 1737629 1737645
4945 3545 1737661 1738047
5045 4921 1740400 1803478
5045 3545 1740832 1741728
4921 3545 1740832 1741728
5045 1683 1743140 1744248
4921 1683 1743140 1744248
5454 4391 1746616 1750777
5454 5070 1748022 1750777
5070 4391 1748022 1750957
1158 305 1749609 1749610
代码:
import os, sys
import itertools
import datetime
from datetime import datetime
from time import mktime
# Extract the date from the timestamp that is the third item in a line
# (Will be grouping by start timestamp)
if not os.path.isfile("testdir") and not os.path.isdir("testdir"):
os.mkdir("testdir")
def key(s):
return datetime.date.fromtimestamp(int(s.split()[2]))
with open('input.txt') as in_f:
for date, group in itertools.groupby(in_f, key=key):
# Output to file that is named like "1970-01-01.txt"
with open(os.path.join("testdir",'{:%Y-%m-%d}.txt'.format(date)),'w') as out_f:
out_f.writelines(group)
#Below we calculate the time epoch difference from col[2] col[3]
with open(os.path("testdir",'{:%Y-%m-%d}.txt'.format(date)),'a+') as a_f:
for rows in a_f:
node_one, node_two, time_epoch_one, time_epoch_two = line.split()
epoch_datetime_one = datetime.fromtimestamp(int(time_epoch_one))
epoch_datetime_two = datetime.fromtimestamp(int(time_epoch_two))
contact_duraction_time = abs(mktime(epoch_datetime_one.timetuple()) - mktime(epoch_datetime_two.timetuple()))
duration = datetime.fromtimestamp(contact_duraction_time).strftime('%Y-%m-%d %H:%M:%S')
a_f.write("%s %s %s\n" % (node_one, node_two, contact_duraction_time))
错误:
Traceback (most recent call last):
File "time_split.py", line 15, in <module>
for date, group in itertools.groupby(in_f, key=key):
File "time_split.py", line 12, in key
return datetime.date.fromtimestamp(int(s.split()[2]))
AttributeError: 'method_descriptor' object has no attribute 'fromtimestamp'
答案 0 :(得分:0)
导入语法有问题。正如你写的那样
import datetime
from datetime import datetime
第二次导入(导致datatime
:: datetime.datetime
)隐藏第一次导入,您无法再使用datatime.date
,因为它被视为datetime.datetime.date
您应该只使用import datetime
和(使用datetime.datetime
进行 class datetime
的后续使用)或使用from datetime import datetime, date
并直接使用{ {1}}和datetime
作为类名。然后你的功能变成:
data
编辑:
datetime是一个模块,也是该模块的类的名称。它不是Python标准库中的最佳设计,但我相信兼容力现在......作为一般规则从不使用def key(s):
return date.fromtimestamp(int(s.split()[2]))
(除非您确定不使用任何其他类来自模块...)