python - 使用语言环境设置将西班牙日期转换为 python pandas datetime 对象
问题描述
我有两个问题:
- 如何使用pandas将西班牙日期时间 'ago122010' 转换为 2010-08-12 。strptime中使用的格式是否正确?
我尝试了以下方法:
import locale
locale.setlocale(locale.LC_ALL, 'es_ES.utf8')
from datetime import datetime as dt
df['date'] = dt.strptime(df['date'], '%b%d%Y')
df['date'] = df['date'].strftime('%Y-%m-%d')
但我收到以下错误:
Error: unsupported locale setting
- 如何使用pandas将此 '20100812' 转换为日期时间。
解决方案
Think the issue is with the locale used. Also, check your formatting.
import locale
locale.setlocale(locale.LC_ALL,'es_ES.UTF-8')
from datetime import datetime as dt
datetime_object = dt.strptime('20100812', '%Y%m%d')
datetime_object
Output:
datetime.datetime(2010, 8, 12, 0, 0)
Let me know if this solves your problem.
Tried few more examples.
# read a spanish datetime format
datetime_object = dt.strptime('martes 12 julio 2016', '%A %d %B %Y')
print(datetime_object.strftime("%B"))
print(datetime_object)
# Change the locale to swede and print the month
locale.setlocale(locale.LC_TIME, "sv_SE")
print(datetime_object.strftime("%B"))
Output:
julio
2016-07-12 00:00:00
Juli
Edited to incorporate the specific details you wanted:
import locale
locale.setlocale(locale.LC_ALL,'es_ES.UTF-8')
from datetime import datetime as dt
datetime_object = dt.strptime('ago122010', '%b%d%Y')
locale.setlocale(locale.LC_ALL,'en_US.UTF-8')
print(datetime_object.strftime("%Y-%m-%d"))
Output
2010-08-12
推荐阅读
- excel - Excel 同一单元格中的两种类型的数据
- c# - VSTO Outlook 加载项:如何检查在重复窗口中标记了哪个单选按钮?
- javascript - AngularJS - 无水绑定
- javascript - momentjs 与时区的时间比较
- mongodb - 获取模板文件中的聚合查询结果(Handlebars)
- python-3.x - AWS:Lambda函数无法使用EC2实例的私有API调用rest api
- record - 为什么记录规则没有按预期运行 Odoo 10?
- node.js - 在 TypeScript 中使用共享项目
- excel - 在 Google 表格中每行只计算一次字符串的出现次数
- javascript - 所选选项值的 jquery 验证警报