【问题标题】:Different dates formatting from ExcelExcel中的不同日期格式
【发布时间】:2017-11-27 14:53:05
【问题描述】:

我需要从 xlsx 文件中读取日期。 起初,我尝试以这种方式加载文件:

df = pd.read_excel('file.xls')

而且“日期”一栏是错误的(我举个例子):

output:
0     2017-03-05
1     2017-03-05
2     2017-03-05
3     2017-03-05
4     2017-03-05
5     2017-03-05
6     2017-03-05
7     2017-03-05
8     2017-03-05
9     2017-03-05
10    2017-03-05
11    2017-03-05
12    2017-03-05
13    2017-05-17
14    2017-05-18
15    2017-05-18
16    2017-05-22
17    2017-05-22

问题是从 0 到 12 的日期不正确,因为它可能不是“2017-03-05”(3 月 5 日),而是“2017-05-03”(5 月 3 日)。 从 13 到 17 是正确的格式 '2017-05-17' (YYYY-MM-DD) 等等。

所以,我尝试以这种方式在 excel 加载期间指定转换:

df = pd.read_excel('file.xls', converters={'Date':str})

python 打印了 Date 列的这个值:

output:
0      2017-03-05 00:00:00
1      2017-03-05 00:00:00
2      2017-03-05 00:00:00
3      2017-03-05 00:00:00
4      2017-03-05 00:00:00
5      2017-03-05 00:00:00
6      2017-03-05 00:00:00
7      2017-03-05 00:00:00
8      2017-03-05 00:00:00
9      2017-03-05 00:00:00
10     2017-03-05 00:00:00
11     2017-03-05 00:00:00
12     2017-03-05 00:00:00
13              05/17/2017
14              05/18/2017
15              05/18/2017
16              05/22/2017
17              05/22/2017

所以 Python 从日期列中读取不同的格式值。

如何将这些不同的格式转换为一种独特的格式“DD/MM/YYYY”?

提前谢谢你。

【问题讨论】:

标签: excel date format


【解决方案1】:

好的,我已经这样做了:

df['DATE'] = df['DATE'].apply(lambda x: datetime.datetime.strptime(x, '%Y-%d-%m %H:%M:%S').strftime('%d/%m/%Y') if x.find(':')!=-1 else datetime.datetime.strptime(x, '%m/%d/%Y').strftime('%d/%m/%Y'))

现在可以了!

【讨论】:

    猜你喜欢
    • 2013-10-21
    • 2013-12-23
    • 1970-01-01
    • 2020-10-01
    • 1970-01-01
    • 2011-11-17
    • 1970-01-01
    • 1970-01-01
    • 2013-03-17
    相关资源
    最近更新 更多