我在df
中有一列,其中包含datetime
个字符串,
inv_date
24/01/2008
15/06/2007 14:55:22
08/06/2007 18:26:12
15/08/2007 14:53:25
15/02/2008
07/03/2007
13/08/2007
我使用了pd.to_datetime
和%d%m%Y
格式,用于将字符串转换为datetime
值;
pd.to_datetime(df.inv_date, errors='coerce', format='%d%m%Y')
我知道了
inv_date
24/01/2008
0
0
0
15/02/2008
07/03/2007
13/08/2007
从inv_date
推断格式为最常见的日期时间格式;我想知道如何不将15/06/2007 14:55:22
,08/06/2007 18:26:12
,15/08/2007 14:53:25
转换为0,而是转换15/06/2007
,08/06/2007
,15/08/2007
。
答案 0 :(得分:2)
使用常规的pd.to_datetime
调用,然后使用.dt.date
:
>>> pd.to_datetime(df.inv_date).dt.date
0 2008-01-24
1 2007-06-15
2 2007-08-06
3 2007-08-15
4 2008-02-15
5 2007-07-03
6 2007-08-13
Name: inv_date, dtype: object
>>>
或者就像@ChrisA所提到的,您也可以使用,只有熊猫格式已经很好,所以跳过这一部分:
>>> pd.to_datetime(df.inv_date.str[:10], errors='coerce')
0 2008-01-24
1 2007-06-15
2 2007-08-06
3 2007-08-15
4 2008-02-15
5 2007-07-03
6 2007-08-13
Name: inv_date, dtype: object
>>>
答案 1 :(得分:1)
您也可以尝试以下方法:
df = pd.read_csv('myfile.csv', parse_dates=['inv_date'], dayfirst=True)
df['inv_date'].dt.strftime('%d/%m/%Y')
0 24/01/2008
1 15/06/2007
2 08/06/2007
3 15/08/2007
4 15/02/2008
5 07/03/2007
6 13/08/2007
希望这也会有所帮助。