datetime.timedelta对象代表两个时间之间的时间差,两个date或datetime对象相减就可以返回一个timedelta对象。
利用以下数据进行说明:
如果我们发现时间相关内容的变量为int,float,str等类型,不方便后面的分析,就需要使用该函数转化为常用的时间变量格式:pandas.to_datetime
转换得到的时间单位如下:
如果时间序列格式不统一,pd.to_datetime()的处理方式:
当然,正确的转换是这样的:
第一步:to_datetime()
第二步:astype(datetime64[D]),astype(datetime64[M])
本例中:
order_dt_diff必须是Timedelta('0 days 00:00:00')格式,可能是序列使用了diff()
或者pct_change()。
前者往往要通过'/np.timedelta'去掉单位days。后者其实没有单位。
假如我们要统计某共享单车一天内不同时间点的用户使用数据,例如
还有其他维度的提取,年、月、日、周,参见:
Datetime properties
注意 :.dt的对象必须为pandas.Series,而不可以是Series中的单个元素
python做数据分析时下面就是提取一个月数据的教程1. datetime库
1.1 datetime.date
1) datetime.date.today() 返回今日,输出的类型为date类
import datetime
today = datetime.date.today()
print(today)
print(type(today))
–>输出的结果为:
2020-03-04
<class 'datetime.date'>
将输出的结果转化为常见数据类型(字符串)
print(str(today))
print(type(str(today)))
date = str(today).split('-')
year,month,day = date[0],date[1],date[2]
print('今日的年份是{}年,月份是{}月,日子是{}号'.format(year,month,day))
–>输出的结果为:(转化为字符串之后就可以直接进行操作)
2020-03-04
<class 'str'>
今日的年份是2020年,月份是03月,日子是04号
2) datetime.date(年,月,日),获取当前的日期
date = datetime.date(2020,2,29)
print(date)
print(type(date))
–>输出的结果为:
2020-02-29
<class 'datetime.date'>
1.2 datetime.datetime
1) datetime.datetime.now()输出当前时间,datetime类
now = datetime.datetime.now()
print(now)
print(type(now))
–>输出的结果为:(注意秒后面有个不确定尾数)
2020-03-04 09:02:28.280783
<class 'datetime.datetime'>
可通过str()转化为字符串(和上面类似)
print(str(now))
print(type(str(now)))
–>输出的结果为:(这里也可以跟上面的处理类似分别获得相应的数据,但是也可以使用下面更直接的方法来获取)
2020-03-04 09:04:32.271075
<class 'str'>
2) 通过自带的方法获取年月日,时分秒(这里返回的是int整型数据,注意区别)
now = datetime.datetime.now()
print(now.year,type(now.year))
print(now.month,type(now.month))
print(now.day,type(now.day))
print(now.hour,type(now.hour))
print(now.minute,type(now.minute))
print(now.second,type(now.second))
print(now.date(),type(now.date()))
print(now.date().year,type(now.date().year))
–>输出的结果为:(首先注意输出中倒数第二个还是上面的datetime.date对象,这里是用来做时间对比的,同时除了这里的datetime.datetime有这种方法,datetime.date对象也有。因为此方法获取second是取的整型数据,自然最后的不确定尾数就被取整处理掉了)
2020 <class 'int'>
3 <class 'int'>
4 <class 'int'>
9 <class 'int'>
12 <class 'int'>
55 <class 'int'>
2020-03-04 <class 'datetime.date'>
2020 <class 'int'>