我正在阅读一个有时间(小时和分钟)和IP地址的文本文件。然后我想得到时间差异并且每5分钟做一些活动。 以下代码不计算时差。
示例文本文件:
06:03 65.55.215.62
06:04 157.56.92.152
06:04 66.249.74.175
06:05 173.199.116.171
代码:
time_ip = []
for line in open('minutes'):
time_ip.append(line.split(' '))
df = pandas.DataFrame(time_ip)
df['tvalue'] = df[0]
df['delta'] = (df['tvalue']-df['tvalue'])
答案 0 :(得分:1)
您应该使用read_csv
将csv读入DataFrame:
In [1]: df = pd.read_csv(file_name, sep='\s+', header=None, names=['time', 'ip'])
In [2]: df
Out[2]:
time ip
0 06:03 65.55.215.62
1 06:04 157.56.92.152
2 06:04 66.249.74.175
3 06:05 173.199.116.171
Pandas(还)没有任何内置时间对象,在python中执行此操作并不容易...您可以创建时间对象的时间列:
In [3]: df['time'] = df['time'].apply(lambda x: datetime.time(*map(int, x.split(':'))))
In [4]: df
Out[4]:
time ip
0 06:03:00 65.55.215.62
1 06:04:00 157.56.92.152
2 06:04:00 66.249.74.175
3 06:05:00 173.199.116.171
尤其是因为你不能做arithmetic on datetime.time objects。无论如何,我认为你不会因为年/月/日在这里而陷入困境一方面,如何应对午夜?
假设你有一个约会时间......让我们重新开始......
In [5]: df = pd.read_csv(file_name, sep='\s+', header=None, names=['time', 'ip'])
In [6]: df['time'] = pd.to_datetime(df['time']) # let's use todays
In [7]: df
Out[7]:
time ip
0 2013-06-12 06:03:00 65.55.215.62
1 2013-06-12 06:04:00 157.56.92.152
2 2013-06-12 06:04:00 66.249.74.175
3 2013-06-12 06:05:00 173.199.116.171
然后,您可以使用shift
In [8]: df['time'].shift()
Out[8]:
0 NaT
1 2013-06-12 06:03:00
2 2013-06-12 06:04:00
3 2013-06-12 06:04:00
Name: time, dtype: datetime64[ns]
In [9]: d['time'] - df['time'].shift()
Out[9]:
0 NaT
1 00:01:00
2 00:00:00
3 00:01:00
Name: time, dtype: timedelta64[ns]
更容易。 :)
答案 1 :(得分:0)
您可以使用datetime
模块
import datetime
with open('minutes', 'r') as myfile:
times = myfile.read().split()[::2]
dates = [datetime.datetime.strptime(i, '%H:%M') for i in times]
differences = [j-i for i, j in zip(dates[:-1], dates[1:])]
print [divmod(i.seconds, 60)[0] for i in differences]
打印:
[1, 0, 1]
答案 2 :(得分:0)
>>> import datetime
>>> end = datetime.datetime.now()
>>> start = datetime.datetime.now()
>>> diff
datetime.timedelta(0, 7, 424199)
>>> diff = start - end
>>> divmod(diff.days * 86400 + diff.seconds, 60)
(0, 7) # 0 minutes, 7 seconds