从Excel文件中解析pandas中的日期时强制格式

时间:2017-08-19 19:40:45

标签: python excel pandas date

我正在尝试按照给定格式%d/%m/%y从Excel文件中解析日期。我无法设置格式,我总是得到%m/%d/%Y

源格式为%d/%m/%y,因此第一个日期应该是2016年6月的第一个日期。有关如何操作的任何想法吗?

import pandas as pd

url = 'https://www.dropbox.com/s/8gqmq3jx27unsta/example_dates.xlsx?dl=1'

file = pd.ExcelFile(url, parse_date=True, 
       date_parser = (lambda x: pd.to_datetime(x, format ='%d/%m/%y')))

df = file.parse(0)

df
    date    variable
0   2016-01-06  1
1   2016-06-07  2
2   2016-12-10  3
3   2016-12-29  4

这样的事情可能有效,但事实并非如此:

df = file.parse(0, converters={'date' : lambda x: pd.to_datetime(x, dayfirst=True)}

date    variable
0   2016-01-06  1
1   2016-06-07  2
2   2016-12-10  3
3   2016-12-29  4

2 个答案:

答案 0 :(得分:3)

实际上,pandas有一种显示日期时间对象的格式。

因此,在您更改

之前,它将以该格式显示

同时你可以这样做:

df['date1'] = df['date'].dt.strftime('%d/%m/%y')

输出:

        date    variable    date1
0   2016-01-06  1   06/01/16
1   2016-06-07  2   07/06/16
2   2016-12-10  3   10/12/16
3   2016-12-29  4   29/12/16

答案 1 :(得分:2)

您可以使用converters

>>> file.parse(0, parse_dates=True, index_col=0, date_parser=lambda x: pd.to_datetime(x).strftime("%d/%m/%Y"))

     variable
date    
2016-06-01  1
2016-07-06  2
2016-10-12  3
2016-12-29  4