![](https://img.haomeiwen.com/i14058594/2bf6191f49585dad.png)
如果我们发现时间相关内容的变量为int,float,str等类型,不方便后面的分析,就需要转化为常用的时间变量格式:datetime
1.转化为datetime
pandas.to_datetime()
本例中:
'''
此处如果用format='%y%m%d',则只能识别出年份中的两位数,例如1997只能识别成97
'''
pd.to_datetime(df['order_dt'],format='%Y%m%d')
![](https://img.haomeiwen.com/i14058594/99d0b204e82074ab.png)
df.order_dt.astype('datetime64[D]') #转化为datetime64,精度为日
df.order_dt.astype('datetime64[M]') #转化为datetime64,精度为月
![](https://img.haomeiwen.com/i14058594/271b912616519d27.png)
![](https://img.haomeiwen.com/i14058594/1b3ce2be2c820c41.png)
2.差值计算后去掉单位
order_dt_diff/np.timedelta64(1,'D') #此处order_dt_diff为设定的时间单位计算的差值保存变量
#如果不进行操作,会有单位D存在
![](https://img.haomeiwen.com/i14058594/de37ebad92288987.png)
3.时间维度的提取
假如我们要统计某共享单车一天内不同时间点的用户使用数据,例如
![](https://img.haomeiwen.com/i14058594/54868b3fdfb19b82.png)
df['start_time'].dt.hour.unique()
还有其他维度的提取,年、月、日、周,参见:
Datetime properties
网友评论