未知的字符串格式。转换日期时python

2024-06-02 06:47:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下日期列类型的对象,我想将其格式化为datetime 使用:

import locale
locale.setlocale(locale.LC_TIME, 'spanish_mexico')

df['fecha'] = pd.to_datetime(df['fecha'], format='%d-%m-%y %H:%M:%S') 



date

viernes 8  diciembre  2017 12:00:00 
2019-05-14 7:22:00

并获取错误

ValueError: time data 'viernes 8  julio  2016 11:00:00 ' does not match format '%d-%m-%y %H:%M:%S' (match)

我如何进行转换以获得

2017-12-08 12:00:00
2019-05-14 7:22:00

Tags: 对象importformat类型dfdatetimetimematch
2条回答

如果通过formatkwarg向pd.to_datetime提供解析指令,它必须与日期/时间字符串中的格式(包括空格等)完全匹配。对于给定示例:

import locale
locale.setlocale(locale.LC_ALL, 'es_MX.utf8') # on Ubuntu; just 'es_MX' on Windows

import pandas as pd
df = pd.DataFrame({'fecha': ['viernes| 8 de julio de 2016| 11:00:00 ()',
                             '2019-05-14 7:22:00']})

# clean date/time strings
df['fecha'] = (df['fecha'].str.replace('\||\(|\[|\&|\#|\]|\)|(de)', '', regex=True) # unwanted characters
                          .str.strip() # whitespaces at beginning and end
                          .str.replace(' +', ' ', regex=True)) # more than one space in sequence

# try to infer format first, works well for standard formats
df['datetime'] = pd.to_datetime(df['fecha'], errors='coerce')

# where the conversion resulted in NaT (no value), use the excplicit format
m = df['datetime'].isna()
df.loc[m, 'datetime'] = pd.to_datetime(df['fecha'][m], format="%A %d %B %Y %H:%M:%S")

df['datetime']
0   2016-07-08 11:00:00
1   2019-05-14 07:22:00
Name: datetime, dtype: datetime64[ns]

有关可用指令的概述,请参见strftime() and strptime() Format Codes

对于指定的格式,可以将datetime模块与以下文档一起使用

https://docs.python.org/2.7/library/datetime.html#strftime-and-strptime-behavior

相关问题 更多 >