熊猫to_datetime将datetime字符串转换为0

时间:2019-06-04 10:19:53

标签: python python-3.x pandas datetime

我在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:2208/06/2007 18:26:1215/08/2007 14:53:25转换为0,而是转换15/06/200708/06/200715/08/2007

2 个答案:

答案 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

希望这也会有所帮助。