使用dayfirst,除非yearfirst为true

问题描述 投票:0回答:1

我正在使用dateutil.parser.parse解析文本文件中的日期。

我事先不知道日期是YYYY-MM-DD(ISO样式)还是英国样式DD-MM-YYYY(或在英国情况下为其他分隔符。)

如果使用dayfirst,它将正确解析UK样式,但将ISO样式错误地解析为YYYY-DD-MM

如何指定是第一天除非是第一天?

python python-dateutil
1个回答
0
投票

查看输入的前四位数是否足以确定其是否为ISO格式?

from dateutil.parser import *


def convert_date(date_string):

    if date_string[0:3].isdigit():
        return parse(date_string)
    else:
        return parse(date_string, dayfirst=True)


print(convert_date('2020-06-05'))
# 2020-06-05 00:00:00
print(convert_date('05-06-2020'))
# 2020-06-05 00:00:00
© www.soinside.com 2019 - 2024. All rights reserved.