python - 未知的字符串格式。转换日期时间 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
解决方案
如果您pd.to_datetime
通过format
kwarg 提供解析指令,它必须与您的日期/时间字符串中的格式完全匹配,包括空格等。对于给定的示例:
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() 格式代码。
推荐阅读
- kotlin - 具有递增值的 Kotlin 整数常量
- java - 如何防止在 JTable 之上选择新添加的元素?
- apache-spark - 如何有效地对 PySpark 中的多列求和?
- python - 如何在模板上正确转义 Jinja 代码?
- python-3.x - 将数据传递给 Rest API
- c# - 当我击中它时敌人不会被摧毁
- c# - 如何修复错误发布到天蓝色功能
- webpack - 如何将静态资产/图像包含在纤细的组件和 webpack 中?
- php - php:调用来自数组的对象的方法
- augmented-reality - 如何将 a-frame 对象定位到标记的左下角,并使其宽度等于标记的宽度?