如何在Python中从datetime列中提取HH:MM?

2024-06-25 23:22:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我只想从我的dfHH:MM中提取。我该怎么做

下面是df中列的说明:

count                     810
unique                    691
top       2018-07-25 11:14:00
freq                        5
Name: datetime, dtype: object

字符串值包含一个完整的时间戳。目标是将每一行的HH:MM解析为另一个df,并循环返回,仅将%Y-%m-%d提取为另一个df


Tags: 字符串name目标dfdatetimeobjecttophh
3条回答

通用解决方案(不基于熊猫)

import time
top = '2018-07-25 11:14:00'
time_struct = time.strptime(top, '%Y-%m-%d %H:%M:%S')
short_top = time.strftime('%H:%M', time_struct)
print(short_top)

输出

11:14

假设df看起来像

print(df)

             date_col
0 2018-07-25 11:14:00
1 2018-08-26 11:15:00
2 2018-07-29 11:17:00
#convert from string to datetime
df['date_col'] = pd.to_datetime(df['date_col']) 

#to get date only
print(df['date_col'].dt.date)
0    2018-07-25
1    2018-08-26
2    2018-07-29

#to get time:
print(df['date_col'].dt.time)

0    11:14:00
1    11:15:00
2    11:17:00
#to get hour and minute
print(df['date_col'].dt.strftime('%H:%M'))
0    11:14
1    11:15
2    11:17

首次转换为日期时间:

df['datetime'] = pd.to_datetime(df['datetime'])

然后你可以做:

df2['datetime'] = df['datetime'].dt.strptime('%H:%M')
df3['datetime'] = df['datetime'].dt.strptime('%Y-%m-%d')

相关问题 更多 >