Py学习  »  Python

Pandas-如何从Python的datetime列中提取HH:MM?

uncle-junky • 4 年前 • 732 次点击  

我只想从我的 df 嗯。我该怎么做?

下面是对 数据框 :

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

字符串值包括一个完整的时间戳。目标是分析每一行的 HH:MM 进入另一个df,循环返回并提取 %Y-%m-%d 进入另一个测向。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/49612
 
732 次点击  
文章 [ 3 ]  |  最新文章 4 年前
balderman
Reply   •   1 楼
balderman    5 年前

一般解决方案(不基于熊猫)

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
WhiteHat
Reply   •   2 楼
WhiteHat    5 年前

第一次转换为日期时间:

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

然后你可以:

df2['datetime'] = df['datetime'].dt.strptime('%H:%M')
df3['datetime'] = df['datetime'].dt.strptime('%Y-%m-%d')
anky_91
Reply   •   3 楼
anky_91    5 年前

假设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