首页 > 解决方案 > 将整数转换为时间格式

问题描述

我有以下数据框:

data = {"hours": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]}
df = pd.DataFrame(data)

我一直在尝试获取以下时间格式:

1:00:00, 2:00:00 ... 12:00:00 etc

所以最后在打字时df.dtypes我也会得到以下格式:datetime64[ns] 但不幸的是我没有成功。我尝试了以下方法:

df['new_hours'] = pd.to_datetime(df['hours'])

但它没有用。

标签: pythonpython-3.xpandasdataframe

解决方案


This works:

import pandas as pd

data = {"hours": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]}
df = pd.DataFrame(data)

df['hours'] = (pd.Timestamp('now').normalize() + (pd.to_timedelta(df['hours'], unit='h'))).dt.time

print(df.head())
#       hours
# 0  01:00:00
# 1  02:00:00
# 2  03:00:00
# 3  04:00:00
# 4  05:00:00

Explanation:

  • df['hours'] = overwrites the Series named 'hours'

  • (pd.Timestamp('now').normalize() creates a datetime'now' and normalize() makes it a midnight datetime (e.g. today 00:00:00)

  • + (pd.to_timedelta(df['hours'],unit='h')) creates a Timedelta object based on the integer in the 'hours' Series, unit parameter ensures its interpreted as hour. Adds this to the previous midnight datetime.

  • ).dt.time takes the time of the datetime that was constructed in the previous 2 bull-its.


推荐阅读