2017-04-25 83 views
1

我有這個字符串如何把這個字符串轉換ISO 8601與Python

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

您需要使用%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'

4

根據Python strftime reference%m意味着你的情況「邁」一個月,一天,似乎在當前區域是本月的名字,你就必須使用這個%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

另外,請參閱https://docs.python.org/3.6/library/datetime.html#strftime-and-strptime-behavior的完整列表要放入日期格式的東西。 – supersam654

+0

謝謝你的支持 – parik

+0

僅供參考我的回答是第一個答案。 – dikkini

相關問題