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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM