首页 > 解决方案 > 未知的字符串格式。转换日期时间 python

问题描述

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

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

标签: pythonpandasdataframedatetime

解决方案


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

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() 和 strptime() 格式代码。


推荐阅读