我只想从我的 df 嗯。我该怎么做?
df
下面是对 数据框 :
数据框
count 810 unique 691 top 2018-07-25 11:14:00 freq 5 Name: datetime, dtype: object
字符串值包括一个完整的时间戳。目标是分析每一行的 HH:MM 进入另一个df,循环返回并提取 %Y-%m-%d 进入另一个测向。
HH:MM
%Y-%m-%d
一般解决方案(不基于熊猫)
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['datetime'] = pd.to_datetime(df['datetime'])
然后你可以:
df2['datetime'] = df['datetime'].dt.strptime('%H:%M') df3['datetime'] = df['datetime'].dt.strptime('%Y-%m-%d')
假设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