【问题标题】:convert string data type duration to date time format in Pandas在 Pandas 中将字符串数据类型持续时间转换为日期时间格式
【发布时间】:2017-05-22 04:36:40
【问题描述】:

如何仅提取格式化为1900-01-01 00:32:59datetime64[ns] 列的时间部分并将其转换为总秒数?

在本例中,我希望最终结果是 1979,以秒为单位,我们距离 1900-01-01 00:00:00 正好 (32*60 + 59) 秒。

【问题讨论】:

标签: pandas datetime string-to-datetime


【解决方案1】:

您可以使用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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-07
    • 1970-01-01
    相关资源
    最近更新 更多