如何使用Python将此字符串转换为iso 8601

时间:2017-04-25 14:40:24

标签: python datetime iso8601

我有这个字符串

14 Mai 2014

我想将其转换为 iso 8601

我阅读了this answerthis one

首先我尝试将字符串转换为日期,然后在i中将其转换为iso格式:

test_date = datetime.strptime("14 Mai 2014", '%d %m %Y')
iso_date = test_date.isoformat()

我收到了错误

ValueError: time data '14 Mai 2014' does not match format '%d %m %Y'

2 个答案:

答案 0 :(得分:4)

根据Python strftime reference %m表示每月的日期和您的情况" Mai"似乎是当前语言环境中的月份名称,您必须使用此%b格式。所以你的代码应该是这样的:

test_date = datetime.strptime("14 Mai 2014", '%d %b %Y')
iso_date = test_date.isoformat()

并且不要忘记设置区域设置。

对于英语语言环境,它有效:

>>> from datetime import datetime
>>> test_date = datetime.strptime("14 May 2014", '%d %b %Y')
>>> print(test_date.isoformat())
2014-05-14T00:00:00

答案 1 :(得分:2)

您需要使用%b代币而不是%m 要使用%b令牌,您必须设置区域设置 Python Documentation

import datetime
import locale

locale.setlocale(locale.LC_ALL, 'fr_FR')
test_date = datetime.datetime.strptime("14 Mai 2014", '%d %b %Y')
iso_date = test_date.isoformat()

结果将是'2014-05-14T00:00:00'

相关问题