pandas 将熊猫日期列转换为经过的秒数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44445336/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 03:45:11  来源:igfitidea点击:

Converting pandas date column into seconds elapsed

pythonpandasdatetimedataframe

提问by Fanylion

I have a pandas dataframe of multiple columns with a column of datetime64[ns] data. Time is in HH:MM:SS format. How can I convert this column of dates into a column of seconds elapsed? Like if the time said 10:00:00 in seconds that would be 36000. The seconds should be in a float64 type format.

我有一个多列的Pandas数据框,其中有一列 datetime64[ns] 数据。时间采用 HH:MM:SS 格式。如何将这一列日期转换为一列经过的秒数?就像如果时间以秒为单位表示 10:00:00 就是 36000。秒应该是 float64 类型的格式。

Example data column

示例数据列

Example data column

示例数据列

回答by piRSquared

New Answer
Convert your text to Timedelta

新答案
将您的文本转换为Timedelta

df['Origin Time(Local)'] = pd.to_timedelta(df['Origin Time(Local)'])
df['Seconds'] = df['Origin Time(Local)'].dt.total_seconds()


Old Answer

旧答案

Consider the dataframe df

考虑数据框 df

df = pd.DataFrame(dict(Date=pd.date_range('2017-03-01', '2017-03-02', freq='2H')))

                  Date
0  2017-03-01 00:00:00
1  2017-03-01 02:00:00
2  2017-03-01 04:00:00
3  2017-03-01 06:00:00
4  2017-03-01 08:00:00
5  2017-03-01 10:00:00
6  2017-03-01 12:00:00
7  2017-03-01 14:00:00
8  2017-03-01 16:00:00
9  2017-03-01 18:00:00
10 2017-03-01 20:00:00
11 2017-03-01 22:00:00
12 2017-03-02 00:00:00


Subtract the most recent day from the timestamps and use total_seconds. total_secondsis an attribute of a Timedelta. We get a series of Timedeltasby taking the difference between two series of Timestamps.

从时间戳中减去最近的一天并使用total_seconds. total_seconds是 a 的一个属性Timedelta。我们Timedeltas通过取 的两个系列之间的差异得到一系列的Timestamps

(df.Date - df.Date.dt.floor('D')).dt.total_seconds()
# equivalent to
# (df.Date - pd.to_datetime(df.Date.dt.date)).dt.total_seconds()

0         0.0
1      7200.0
2     14400.0
3     21600.0
4     28800.0
5     36000.0
6     43200.0
7     50400.0
8     57600.0
9     64800.0
10    72000.0
11    79200.0
12        0.0
Name: Date, dtype: float64


Put it in a new column

把它放在一个新的列

df.assign(seconds=(df.Date - df.Date.dt.floor('D')).dt.total_seconds())

                  Date  seconds
0  2017-03-01 00:00:00      0.0
1  2017-03-01 02:00:00   7200.0
2  2017-03-01 04:00:00  14400.0
3  2017-03-01 06:00:00  21600.0
4  2017-03-01 08:00:00  28800.0
5  2017-03-01 10:00:00  36000.0
6  2017-03-01 12:00:00  43200.0
7  2017-03-01 14:00:00  50400.0
8  2017-03-01 16:00:00  57600.0
9  2017-03-01 18:00:00  64800.0
10 2017-03-01 20:00:00  72000.0
11 2017-03-01 22:00:00  79200.0
12 2017-03-02 00:00:00      0.0

回答by FdMon

it would work:

它会起作用:

df['time'].dt.total_seconds()

regards

问候