如何将python中的时间转换成特定的格式?

How to convert time into specific format in python?

我的 pandas DataFrame 中有一列时间包含超过 800,000 行。时间格式是这样的:

08:28:31
08:28:35
08:28:44
08:28:44

我想把这个格式转换成小时制,也就是说如果第一次来08:28:31那么第二次应该按小时来09:28:31等等。我们如何实现这个在 python 使用 DateTime 库

输出数据:

08:28:31
09:28:31
...
23:28:31

08:28:35
09:28:35
...
23:28:35

08:28:44
...
08:28:44
...

使用:

#convert values to datetimes
df['date'] = pd.to_datetime(df['date'])

#count number of repeated values
df = df.loc[df.index.repeat(24 - df['date'].dt.hour)]
#generate hour timedeltas
hours = pd.to_timedelta(df.groupby(level=0).cumcount(), unit='H')

#add to dates and generate times with convert index to default values
s = df['date'].add(hours).dt.time.reset_index(drop=True)
print (s)
0     08:28:31
1     09:28:31
2     10:28:31
3     11:28:31
4     12:28:31
  
59    19:28:44
60    20:28:44
61    21:28:44
62    22:28:44
63    23:28:44
Length: 64, dtype: object