2010-02-15 36 views
72

我有格式爲'Mon Feb 15 2010'的日期字符串。我想將格式更改爲'15/02/2010'。我怎樣才能做到這一點?解析日期字符串和更改格式

+0

所有這些的副本:http://stackoverflow.com/search?q=%5Bpython%5D+parse+date。這個完全重複的thise:http://stackoverflow.com/questions/1713594/parsing-dates-and-times-from-strings-using-python –

+0

可能的重複[如何將日期字符串轉換爲不同格式的python]( http://stackoverflow.com/questions/14524322/how-to-convert-a-date-string-to-different-format-in-python) – Pureferret

回答

91

datetime模塊可以幫你:

datetime.datetime.strptime(date_string, format1).strftime(format2) 
+1

datetime.datetime(2010年2月15日星期一,「%a%b% d%Y「)。strftime(」%d /%m /%Y「) 它是正確的嗎?但我得到了一個錯誤。 – Nimmy

+1

@nimmyliji:你看到了「字符串」部分,對吧? –

+1

@nimmyliji:在您發表評論前10分鐘已修復。當然你應該把'date_string'作爲一個字符串。 – SilentGhost

20
>>> from_date="Mon Feb 15 2010" 
>>> import time     
>>> conv=time.strptime(from_date,"%a %b %d %Y") 
>>> time.strftime("%d/%m/%Y",conv) 
'15/02/2010' 
37

您可以安裝dateutil庫。它的parse函數可以找出字符串的格式,而不必像datetime.strptime那樣指定格式。

from dateutil.parser import parse 
dt = parse('Mon Feb 15 2010') 
print(dt) 
# datetime.datetime(2010, 2, 15, 0, 0) 
print(dt.strftime('%d/%m/%Y')) 
# 15/02/2010 
+0

dateutil.parse是如果一個更好的選擇法律ISO串的精確格式是未知的。 ISO可能包含或不包含微秒。它可能包含或不包含尾隨的「Z」。 datetime.strptime不夠靈活以適應這一點。 –

+3

請謹慎使用Pase Date。解析('12 .07.2017 ')返回日期時間(2017年,12,7,...),但解析('13 .07.2017')返回.datetime(2017年,7,13,...) – ego2dot0

12

字符串轉換爲DateTime對象

from datetime import datetime 
s = "2016-03-26T09:25:55.000Z" 
f = "%Y-%m-%dT%H:%M:%S.%fZ" 
datetime = datetime.strptime(s, f) 
print(datetime) 
output: 
2016-03-26 09:25:55 
1

剛剛完成的緣故:解析使用strptime()的日期時,日期包含名每天,一個月等,做到心中有數你必須考慮到語言環境。

它在docs中也作爲腳註提及。

舉個例子:

import locale 
print(locale.getlocale()) 

>> ('nl_BE', 'ISO8859-1') 

from datetime import datetime 
datetime.strptime('6-Mar-2016', '%d-%b-%Y').strftime('%Y-%m-%d') 

>> ValueError: time data '6-Mar-2016' does not match format '%d-%b-%Y' 

locale.setlocale(locale.LC_ALL, 'en_US') 
datetime.strptime('6-Mar-2016', '%d-%b-%Y').strftime('%Y-%m-%d') 

>> '2016-03-06' 
3

由於這個問題來的時候,這裏是簡單的解釋。

datetimetime模塊有兩個重要功能。

  • 的strftime - 創建從datetime或時間對象的日期或時間的字符串表示。
  • strptime - 根據字符串創建日期時間或時間對象。

在這兩種情況下,我們都需要一個格式化字符串。它是表示如何在您的字符串中格式化日期或時間。

現在讓我們假設我們有一個日期對象。

>>> from datetime import datetime 
>>> d = datetime(2010, 2, 15) 
>>> d 
datetime.datetime(2010, 2, 15, 0, 0) 

如果我們想在格式'Mon Feb 15 2010'

>>> s = d.strftime('%a %b %d %y') 
>>> print s 
Mon Feb 15 10 

創建從這個日期的字符串讓我們假設我們希望這個s再次轉換爲datetime對象。

>>> new_date = datetime.strptime(s, '%a %b %d %y') 
>>> print new_date 
2010-02-15 00:00:00 

請參閱This記錄關於日期時間的所有格式化指令。