2014-07-24 57 views
0

如何解決字符串'2014-03-16 18:28:11'回到datetime.datetime。我想知道下面反向str到Python中的datetime.datetime

>>> datetime.datetime(2014, 3, 16, 18, 28, 11) 
>>> str(datetime.datetime(2014, 3, 16, 18, 28, 11)) 
'2014-03-16 18:28:11' 
>>> complete = str(datetime.datetime(2014, 3, 16, 18, 28, 11)) 
>>> date, time = complete.split(" ") 
>>> [int(x) for x in date.split("-")] 
[2014, 3, 16] 
>>> [int(x) for x in time.split(":")] 
[18, 28, 11] 

如果有比一個更簡單的方法,然後使用每個變量輸入到datetime.datetime

+0

可能重複[如何將字符串日期轉換成日期時間格式在Python?](http://stackoverflow.com/questions/19068269/how-to-convert-a-string-date-into- datetime-format-in-python) – DavidK

回答

3

你想datetime.strptime

date = datetime.datetime.strptime(complete, '%Y-%m-%d %H:%M:%S') 
+0

這看起來不會返回微秒,或者最後一個參數是什麼 –