熊猫read_csv解析国外日期

时间:2018-09-05 20:49:26

标签: python pandas

我正在尝试在包含日期列的.csv文件中使用read_csv。问题在于日期列是外语(罗马尼亚语),其条目为:

'2017年9月26日'

'13 iulie 2017'

等如何将其很好地解析为具有美国日期格式的熊猫数据框?

3 个答案:

答案 0 :(得分:3)

您可以为该列传递一个转换器:

df = pd.read_csv(myfile, converters={'date_column': foreign_date_converter})

但是首先,您必须定义转换器以执行所需的操作。这种方法使用语言环境操作:

def foreign_date_converter(text):
    # Resets locale to "ro_RO" to parse romanian date properly
    # (non thread-safe code)
    loc = locale.getlocale(locale.LC_TIME)
    locale.setlocale(locale.LC_TIME, 'ro_RO')
    date = datetime.datetime.strptime(text '%d %b %Y').date()
    locale.setlocale(locale.LC_TIME, loc) # restores locale
    return date

答案 1 :(得分:1)

使用dateparser模块。

import dateparser
df = pd.read_csv('yourfile.csv', parse_dates=['date'], date_parser=dateparser.parse)

parse_dates参数中输入日期列名称。我只是假设它为date

您可能会有这样的输出:

      date
0   2017-09-26    
1   2017-07-13      

如果要更改格式,请使用strftime strftime

df['date'] = df.date.dt.strftime(date_format = '%d %B %Y')

输出:

      date
0   26 September 2017
1        13 July 2017

答案 2 :(得分:0)

最简单的解决方案是使用str.replace(old, new)函数的12倍。

虽然不漂亮,但是如果您刚刚构建了函数:

def translater(date_string_with_exatly_one_date):
    date_str = date_string_with_exatly_one_date
    date_str = date_str.replace("iulie", "july")
    date_str = date_str.replace("septembrie", "september")
    #do this 10 more times with the right translation
    return date_str

现在,您只需为每个条目调用它。之后,您可以像处理美国日期字符串一样处理它。这不是很有效,但是可以完成工作,您不必搜索特殊的库。

相关问题