Python pandas 将秒转换为时间 (hh:mm)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44118395/
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:40:00  来源:igfitidea点击:

Python pandas convert seconds to time (hh:mm)

pythonpandas

提问by Joost

Is it possible to convert a pandas dataframe column with total seconds in it to another column with time like hh:mm ?

是否可以将包含总秒数的 Pandas 数据帧列转换为另一列,如 hh:mm ?

In my mysql query I can do something like

在我的 mysql 查询中,我可以做类似的事情

SELECT SEC_TO_TIME(xxxx);

but the output is converted wrong in my pandas Dataframe, so I want to do the convertion from seconds to time with pandas instead of sql... I am playing around with the pd.to_timedelta function:

但是输出在我的 Pandas Dataframe 中转换错误,所以我想用 Pandas 而不是 sql 进行秒到时间的转换......我正在玩 pd.to_timedelta 函数:

df['time'] = pd.Timedelta(Second(df['sec']))

But it is not working.

但它不起作用。

-edit-

-编辑-

Solved it! This was not working:

解决了!这不起作用:

df['time'] = pd.to_datetime(df["sec"], unit='s')

but that was because the dtype of df["sec"] was wrong (it was an object type). I tried converting the column to float first and then the pd.to_datetime function and now I have what I want :) :

但那是因为 df["sec"] 的 dtype 是错误的(它是一个对象类型)。我尝试先将列转换为浮动,然后是 pd.to_datetime 函数,现在我有了我想要的:):

df['sec'] = df['sec'].astype('float64') 
df['time'] = pd.to_datetime(df["sec"], unit='s')

回答by lukess

This will convert the time to the YYYY-MM-DD hh:mm format:

这会将时间转换为 YYYY-MM-DD hh:mm 格式:

df['time'] = pd.to_datetime(df['time'], unit='m')