2012-06-04 46 views
2

我是python新手。我有一個2012年1月11日格式的日期,我需要將其轉換爲2012年1月11日。我需要使用給定字典的過程:month = {1:January,2:February,... etc}。如果我打印(月份,日期字符串),那麼我應該知道。非常感謝您的幫助。將python中的字符串日期轉換爲python中的日月年

+2

請看一看Python標準[DATETIME](http://docs.python.org/library/datetime.html)模塊。 – msvalkon

+1

用[作業]重新標記 – froeschli

回答

2
datestring = '1/11/2012' 
months = {'1':January, ...} 
month, day, year = datestring.split('/') 
print '{} {} {}'.format(day, months[month], year) 
10

不要重新發明輪子。你不需要字典。

>>> import datetime 
>>> datetime.datetime.strptime('1/11/2012', '%m/%d/%Y').strftime('%d %B %Y') 
'11 January 2012' 
1
>>> from datetime import datetime 
>>> import calendar 
>>> mydate = datetime.strptime('1/11/2012','%m/%d/%Y') 
>>> calendar.month_name[mydate.month] 
'January' 
>>> mydate.year 
2012 
相關問題