Python - 将datetime列转换为秒

时间:2016-12-06 10:23:18

标签: python pandas

我有一个日期栏(称为'时间'),其中包含天/小时/分钟等(timedelta)。我在我的数据框架中创建了一个新列,我想转换时间'将列放入秒并将其放入每行的新列中。

有没有人有任何指针?我在互联网上可以找到的是如何转换列,而不是创建新列并转换另一列。

提前谢谢!

2 个答案:

答案 0 :(得分:18)

我认为你需要total_seconds

print (df['col'].dt.total_seconds())

样品:

df = pd.DataFrame({'date1':pd.date_range('2015-01-01', periods=3),
                   'date2':pd.date_range('2015-01-01 02:00:00', periods=3, freq='23H')})

print (df)
       date1               date2
0 2015-01-01 2015-01-01 02:00:00
1 2015-01-02 2015-01-02 01:00:00
2 2015-01-03 2015-01-03 00:00:00

df['diff'] = df['date2'] - df['date1']
df['seconds'] = df['diff'].dt.total_seconds()

print (df)
       date1               date2     diff  seconds
0 2015-01-01 2015-01-01 02:00:00 02:00:00   7200.0
1 2015-01-02 2015-01-02 01:00:00 01:00:00   3600.0
2 2015-01-03 2015-01-03 00:00:00 00:00:00      0.0
df['diff'] = df['date2'] - df['date1']
df['diff'] = df['diff'].dt.total_seconds()

print (df)
       date1               date2    diff
0 2015-01-01 2015-01-01 02:00:00  7200.0
1 2015-01-02 2015-01-02 01:00:00  3600.0
2 2015-01-03 2015-01-03 00:00:00     0.0

如果需要转发到int

df['diff'] = df['date2'] - df['date1']
df['diff'] = df['diff'].dt.total_seconds().astype(int)

print (df)
       date1               date2  diff
0 2015-01-01 2015-01-01 02:00:00  7200
1 2015-01-02 2015-01-02 01:00:00  3600
2 2015-01-03 2015-01-03 00:00:00     0

答案 1 :(得分:3)

我们假设您的DataFrame名称为df

如果要使用秒创建新列,则应执行以下操作:

df['newColumn'] = df['Time'].dt.total_seconds()