to_datetime 以及 dt.days、dt.months

Series类型的数据,经过 to_datetime 之后就可以用 pandas.Series.dt.days 和 pandas.Series.pd.month。

除了 days 和 month 外,还包括 date、dayofweek、dayofyear、days_in_month、freq、hour、microsecond、minute、month、quarter、second、time、tz、week、weekday、year等。这些是提取 Series 时间数据的常用方法

 

import pandas as pd
a  = pd.Series(['2017-1-2','2017-9-1'])
print(a)
0    2017-1-2
1    2017-9-1
dtype: object

a = pd.to_datetime(a)
print(a)
0   2017-01-02
1   2017-09-01
dtype: datetime64[ns]

b = pd.Series(['2019-8-19', '2019-6-29'])
b = pd.to_datetime(b)
print(b)
0   2019-08-19
1   2019-06-29
dtype: datetime64[ns]

c = (b-a).dt.days
print(c)
0    959
1    666
dtype: int64

import datetime
d = datetime.date(2019,8,19) - a.dt.date
print(d)
d = (datetime.date(2019,8,19) - a.dt.date).dt.days
print(d)
0    959
1    717
dtype: int64
posted @ 2019-08-19 21:10  做梦当财神  阅读(5071)  评论(0编辑  收藏  举报