从日期时间格式的列中仅选择日期

时间:2018-04-27 22:09:50

标签: python pandas datetime

                  A
2002-01-03 12:00:00
2002-01-04 12:00:00
2002-01-05 12:00:00

我需要从df['A']中提取日期,该日期具有datetime64 [ns]格式。

df['A']输出应为:

         A
2002-01-03
2002-01-04
2002-01-05

我试过了:

datetime.strftime(df.A, '%y%m%d')

1 个答案:

答案 0 :(得分:3)

目前尚不清楚您是想要datetime还是str输出。要么可能:

import pandas as pd

df = pd.DataFrame({'A': ['2002-01-03 12:00:00',
                         '2002-01-04 12:00:00',
                         '2002-01-05 12:00:00']})

df['A'] = pd.to_datetime(df['A'])

df['B'] = df['A'].dt.normalize()

df['C'] = df['A'].dt.strftime('%Y-%m-%d')

print(df)

                    A          B           C
0 2002-01-03 12:00:00 2002-01-03  2002-01-03
1 2002-01-04 12:00:00 2002-01-04  2002-01-04
2 2002-01-05 12:00:00 2002-01-05  2002-01-05

print(df.dtypes)

A    datetime64[ns]
B    datetime64[ns]
C            object
dtype: object