按天划分数据

1 投票
4 回答
959 浏览
提问于 2025-04-20 18:13

我有一些数据文件,里面包含时间戳(也就是UNIX时间),我想把这些数据按天分开,放到不同的文件里。比如说,如果数据是90天的,那就应该分成90个文件。我不知道该从哪里开始。有时候我知道有多少天,有时候又不知道,所以我想找个简单的方法,把数据按天分开。Data[0] Data[1] Timeepoch[2] Timeepoch[3]Time_1和Time_2是开始时间和结束时间。

数据:这些只是几行。

Data_1  Data_2  Time_1  Time_2
3436    1174    1756908 1759291
3436    3031    1756908 1759291
3436    1349    1756908 1759291
5372    937     1756913 1756983
4821    937     1756913 1756983
4376    937     1756913 1756983
2684    937     1756913 1756983
3826    896     1756961 1756971
3826    896     1756980 1756997
5372    937     1756983 1757045
4821    937     1756983 1757045
4376    937     1756983 1757045
2684    937     1756983 1757045
3826    896     1757003 1757053
4944    3715    1757009 1757491
4944    4391    1757009 1757491
2539    1431    1757014 1757337
5372    937     1757045 1757104
4821    937     1757045 1757104
4376    937     1757045 1757104
2684    937     1757045 1757104
896     606     1757053 1757064
3826    896     1757064 1757074
5045    4901    1757074 1757085
4921    4901    1757074 1757085
4901    3545    1757074 1757085
4901    3140    1757074 1757085
4901    4243    1757074 1757085
896     606     1757074 1757084

4 个回答

0

datetime.fromtimestamp(timestamp) 这个代码可以把一个时间戳转换成一个日期时间对象。

datetime.fromtimestamp(timestamp).replace(second=0, minute=0, hour=0) 这个代码则可以把这个日期时间对象变成只有日期部分,没有具体的时间(秒、分钟和小时都变成0)。

0

下面的代码会把每一行写入一个名为 output-YYYY-MM-DD 的文件,YYYY-MM-DD 是从 Time_2 这一列提取出来的日期。

from datetime import date
with open('infile.txt', 'r') as f:
    for line in f: 
        fields = line.split()
        with open('output-'+date.fromtimestamp(float(fields[3])).__str__(), 'a') as outf:
            outf.write(line)

这段代码效率不是很高,因为它为每一行都打开一个文件。如果你能保证输入的数据是按照结束时间排序的,那就可以改进这个代码。

1

要从POSIX时间戳找到一个UTC日期,只需要把它加到一个叫做“纪元”的时间上,比如:

>>> from datetime import date, timedelta
>>> date(1970, 1, 1) + timedelta(seconds=1756908)
datetime.date(1970, 1, 21)

接着,创建一个映射关系:日期 -> 文件,然后用这个关系来分割输入文件:

#!/usr/bin/env python
import fileinput
from datetime import date, timedelta

def get_date(line, epoch=date(1970, 1, 1)):
    try:
        timestamp = int(line.split()[2]) # timestamp from 3rd column
        return epoch + timedelta(seconds=timestamp) # UTC date
    except Exception:
        return None # can't parse timestamp

daily_files = {} # date -> file
input_file = fileinput.input()
next(input_file) # skip header
for line in input_file:
    d = get_date(line)
    file = daily_files.get(d)
    if file is None: # file for the given date is not found
       file = daily_files[d] = open(str(d), 'w') # open a new one
    file.write(line)

# close all files
for f in daily_files.values():
    try:
        f.close()
    except EnvironmentError:
        pass # ignore errors
2
import itertools
import datetime

# Extract the date from the timestamp that is the third item in a line
# (Will be grouping by start timestamp)
def key(s):
    return datetime.date.fromtimestamp(int(s.split()[2]))

with open('in.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('{:%Y-%m-%d}.txt'.format(date), 'w') as out_f:
            out_f.writelines(group)

当然可以!不过你没有提供具体的内容。请把你想要翻译的StackOverflow内容发给我,我会帮你用简单易懂的语言解释清楚。

撰写回答