从日期时间对象中提取日期和月份

时间:2018-07-30 23:51:45

标签: python python-3.x pandas datetime

我有一列的日期为字符串格式'2017-01-01'。有没有办法使用熊猫从中提取日期和月份。

我已将列转换为datetime dtype,但没有弄清楚后面的部分:

df['Date'] =  pd.to_datetime(df['Date'], format='%Y-%m-%d')

df.dtypes : 
Date        datetime64[ns]

print (df)

         Date
0   2017-05-11
1   2017-05-12
2   2017-05-13 

4 个答案:

答案 0 :(得分:5)

使用dt.daydt.month --- Series.dt

df = pd.DataFrame({'date':pd.date_range(start='2017-01-01',periods=5)})
df.date.dt.month
Out[164]: 
0    1
1    1
2    1
3    1
4    1
Name: date, dtype: int64

df.date.dt.day
Out[165]: 
0    1
1    2
2    3
3    4
4    5
Name: date, dtype: int64

也可以使用dt.strftime

df.date.dt.strftime('%m')
Out[166]: 
0    01
1    01
2    01
3    01
4    01
Name: date, dtype: object

答案 1 :(得分:2)

使用dt获取列的datetime属性。

In [60]: df = pd.DataFrame({'date': [datetime.datetime(2018,1,1),datetime.datetime(2018,1,2),datetime.datetime(2018,1,3),]})

In [61]: df
Out[61]:
        date
0 2018-01-01
1 2018-01-02
2 2018-01-03

In [63]: df['day'] = df.date.dt.day

In [64]: df['month'] = df.date.dt.month

In [65]: df
Out[65]:
        date  day  month
0 2018-01-01    1      1
1 2018-01-02    2      1
2 2018-01-03    3      1

对提供的方法进行计时:

使用apply

In [217]: %timeit(df['date'].apply(lambda d: d.day))
The slowest run took 33.66 times longer than the fastest. This could mean that an intermediate result is being cached.
1000 loops, best of 3: 210 µs per loop

使用dt.date

In [218]: %timeit(df.date.dt.day)
10000 loops, best of 3: 127 µs per loop

使用dt.strftime

In [219]: %timeit(df.date.dt.strftime('%d'))
The slowest run took 40.92 times longer than the fastest. This could mean that an intermediate result is being cached.
1000 loops, best of 3: 284 µs per loop

我们可以看到dt.day是最快的

答案 2 :(得分:1)

这应该做到:

df['day'] = df['Date'].apply(lambda r:r.day)
df['month'] = df['Date'].apply(lambda r:r.month)

答案 3 :(得分:0)

一种简单的形式:

df['MM-DD'] = df['date'].dt.strftime('%m-%d')