2014-09-02 59 views

回答

4

您可以使用dateutil模塊:

>>> from dateutil.parser import parse 
>>> s = 'Mar 31st, 2014' 
>>> parse(s) 
datetime.datetime(2014, 3, 31, 0, 0) 
+0

謝謝! a = parse(date) released = a.day .__ str __()+「/」+ a.month .__ str __()+「/」+ a.year .__ str __() – 2014-09-02 04:46:48

+0

您的月份不會爲零,如您在所需示例輸出中顯示的那樣。此外,您顯式使用私有方法('__str__')是一個不好的跡象。使用''{0.day} {0:/%m /%Y}'。格式(a)'而不是 – 2014-09-02 05:06:32

+0

爲什麼它在這種特定情況下不好? – 2014-09-02 05:12:03

1

你可以定義自己的函數來做到這一點:

d = {'Jan': '01', 'Feb': '02', 'Mar': '03', 'Apr': '04', 'May': '05', 'Jun': '06', 'Jul': '07', 'Aug': '08', 'Sep': '09', 'Oct': '10', 'Nov': '11', 'Dec': '12'} 


def parser(date): 
    date = date.split() # date = ['Mar', '31st,', '2014'] 
    for i, elem in enumerate(date): 
     if i == 0: 
      month = d[elem] # month = '03' 
     elif i == 1: 
      date = elem[:len(elem) - 3] # date = '31' 
     else: 
      year = elem # year = '2014' 
    return date + "/" + month + "/" + year # '31/03/2014' 

print parser('Mar 31st, 2014') 

這將返回31/03/2014

1

使用標準的模塊的主要問題對於帶有後綴的日子(我的意思是'st','nd','th')沒有格式選項,沒有前導零的情況下沒有任何選項。 至於後綴,你可以安全地刪除它們,因爲它們不會出現在月份名稱中。至於沒有前導零的那天,我們可以通過明確選擇日期部分來構造字符串。

from datetime import datetime 

def convert(dt_string, in_format='%b %d, %Y', out_format='{0.day}{0:/%m/%Y}'): 
    for suffix in ('st', 'nd', 'rd', 'th'): 
     dt_string = dt_string.replace(suffix, '') 
    return out_format.format(datetime.strptime(dt_string, in_format)) 


dates = ['Mar 31st, 2014', 'Aug 13th, 2014', 'Sep 2nd, 2014'] 
print map(convert, dates) 
0

我會用下面的方法。

import datetime 
import re 

# Collect all dates into a list. 
dates = [ 'Mar 31st, 2014', 'Aug 13th, 2014', 'Sep 2nd, 2014' ] 

# Compile a pattern to replace alpha digits in date to empty string. 
pattern = re.compile('(st|nd|rd|th|,)') 

# Itegrate through the list and replace the old format to the new one. 
for offset, date in enumerate(dates): 
    date = pattern.sub('', date) 
    date = datetime.datetime.strptime(date, '%b %d %Y') 
    dates[offset] = str(date.day) + '/' + str(date.month) + '/' + str(date.year) 
    print(dates[offset]); 
相關問題