【发布时间】:2017-05-22 04:36:40
【问题描述】:
如何仅提取格式化为1900-01-01 00:32:59 的datetime64[ns] 列的时间部分并将其转换为总秒数?
在本例中,我希望最终结果是 1979,以秒为单位,我们距离 1900-01-01 00:00:00 正好 (32*60 + 59) 秒。
【问题讨论】:
标签: pandas datetime string-to-datetime
如何仅提取格式化为1900-01-01 00:32:59 的datetime64[ns] 列的时间部分并将其转换为总秒数?
在本例中,我希望最终结果是 1979,以秒为单位,我们距离 1900-01-01 00:00:00 正好 (32*60 + 59) 秒。
【问题讨论】:
标签: pandas datetime string-to-datetime
您可以使用to_timedelta + strftime + total_seconds + astype:
df = pd.DataFrame({"date": ["1900-01-01 00:32:59"]})
df['date'] = pd.to_datetime(df['date'])
print (df)
date
0 1900-01-01 00:32:59
df['total'] = pd.to_timedelta(df['date'].dt.strftime("%H:%M:%S"))
.dt.total_seconds().astype(int)
print (df)
date total
0 1900-01-01 00:32:59 1979
或floor + total_seconds + astype:
df['total'] = (df['date'] - df['date'].dt.floor('D')).dt.total_seconds().astype(int)
print (df)
date total
0 1900-01-01 00:32:59 1979
或normalize + total_seconds + astype
df['total'] = (df['date'] - df['date'].dt.normalize()).dt.total_seconds().astype(int)
print (df)
date total
0 1900-01-01 00:32:59 1979
【讨论】: