在新创建的Di中一次创建和附加多个文件

2024-04-24 09:01:00 发布

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

我有一个数据文件,这是分裂的日期明智的。后来我找到了两列的时差,即col[2] col[3]。我可以很好地得到的结果,当我写一个单独的代码,两者。但现在我必须编写一个代码来按日期拆分数据,并计算时间差。可能两者同时发生。它只创建dir,然后给出下面的错误。如何读取文件并操作它们,然后再次将它们附加到相同的位置和相同的文件中。你知道吗

输入:

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'

Tags: keyinfromimportdatetimedatetimeos
1条回答
网友
1楼 · 发布于 2024-04-24 09:01:00

导入语法有问题。就像你写的那样

import datetime
from datetime import datetime

第二个导入(导致datatime::datetime.datetime)隐藏了第一个导入,并且您不能再使用datatime.date,因为它被读取为datetime.datetime.date

您应该只使用import datetime和(对于datetime的后续使用datetime.datetime),或者使用from datetime import datetime, date并直接使用datetimedata作为类名。您的功能将变为:

def key(s):
    return date.fromtimestamp(int(s.split()[2]))

编辑:

datetime是一个模块,也是该模块的类的名称。它不是Python标准库中最好的设计,但我相信兼容性迫使现在。。。一般来说,从不使用from datetime import datetime(除非您确定不使用模块中的任何其他类…)

相关问题 更多 >