2012-11-08 119 views
1

在瑞典,我們有時使用奇怪的日期格式,例如新年是31/12。如果我將此格式設置爲字符串(可以是1/1到31/12之間的任何日期),並且假設它是今年,那麼如何使用Python進入標準日期格式(格式爲2012-01 -01和2012-12-31),可以作爲日期存儲在mySQL數據庫中。將奇怪的日期格式轉換爲標準日期格式

回答

2

,只需拆分兩個值,它們映射到整數和更新datetime.date()實例:

import datetime 
day, month = map(int, yourvalue.split('/')) 
adate = datetime.date.today().replace(month=month, day=day) 

使用datetime.date.today()我們得到當前年份。

演示:

>>> import datetime 
>>> somevalue = '31/12' 
>>> day, month = map(int, somevalue.split('/')) 
>>> datetime.date.today().replace(month=month, day=day) 
datetime.date(2012, 12, 31) 
>>> someothervalue = '1/1' 
>>> day, month = map(int, someothervalue.split('/')) 
>>> datetime.date.today().replace(month=month, day=day) 
datetime.date(2012, 1, 1) 

或者,你可以使用datetime.strptime() method分析這些日期,但你必須手動更正年之後(這將使用1900作爲默認的,如果沒有一年是解析):

adate = datetime.datetime.strptime(yourvalue, '%d/%m').date() 
adate = adate.replace(year=datetime.date.today().year) 
0

沒有什麼奇怪的格式:)

可以使用datetime模塊:

import datetime 
d = datetime.datetime.strptime('31/12', '%d/%m').date().replace(year=2012) 
print d 

>> datetime.date(2012, 12, 31)