本文介绍了将Python日期格式转换为英国的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个CSV文件,该文件的日期列中包含一些脏数据,即以不同格式(美国和英国)存储的日期.我想创建另一个具有转换日期的CSV文件,以便它们始终以UK格式存储,从而使我可以正确地导入到我的SQL数据库中.

I have a CSV file which has a date column with some dirty data i.e. dates stored in different formats (US and UK). I'd like to create another CSV file with the dates converted so they are consistently stored in the UK format enabling me to import correctly into my SQL database.

我希望将日期转换为以下格式:

I'd like the dates to be converted to the following format:

"2017年5月12日"'2017年11月11日''24 -04-1999''28 -01-1987'..

'05-12-2017''07-11-2017''24-04-1999''28-01-1987'..

我尝试了以下代码:

df = F.pd.read_csv('Book1.csv', parse_dates = [0], dayfirst = True)
df['Date'] = df['Date'].apply(F.pd.to_datetime, format = '%m/%d/%Y')
df['date_eu'] = df['Date'].dt.strftime('%m-%d-%Y')
df

,但是在尝试转换美国日期时会抛出错误

, but it throws an error while trying to convert the US dates

ValueError: time data '20/01/2018' does not match format '%m/%d/%Y' (match)

有人可以帮忙吗?

谢谢

推荐答案

您可以使用Try-Parse-Else-Approach:

You could use a Try-Parse-Else-Approach:

from datetime import datetime

def normalizeDateString(ds):
    '''normalizes a date of format "d / d / dddd " to "dd/dd/dddd"'''
    sp = ds.replace(" ","").split("/")
    if len(sp[0])==1:
        sp[0]="0"+sp[0]
    if len(sp[1])==1:
        sp[1]="0"+sp[1]

    return sp[0]+"/"+sp[1]+"/"+sp[2]

def parseDT(dateString):
    ''' parses "dd/dd/yyyy" as US (month/day/year). Fallback: day/month/year on error'''
    try:
        repl =  normalizeDateString(dateString)
        return datetime.strptime(repl, "%m/%d/%Y").date()
    except:
        return datetime.strptime(repl, "%d/%m/%Y").date()


print(parseDT("14/12/2018"))
print(parseDT("2/5/2018")) # ok for US
print(parseDT("22/5/2018")) # not ok for US
print(parseDT("12/2/2018"))
print(parseDT("2/1/2018"))

输出:

2018-12-14
2018-02-05  # US ok
2018-05-22  # EN by except
2018-12-02
2018-02-01

HTH

这篇关于将Python日期格式转换为英国的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 03:31