2016-11-15 93 views
0

下面是蟒蛇代碼,我在2.7試過,如何從「03 - 11月-2016」的日期格式更改爲2016年11月3日

def date_format_change(): 
    DB_date = "03-NOV-2016" 
    split2 = DB_date.split('-') 
    print split2[0] 
    M_date = float(round(split2[0]),2) 
    print M_date 
    Month = {'JAN': '1', 'FEB': '2', 'MAR': '3', 'APR': '4', 'MAY': '5','JUN': '6', 'JUL': '7', 'AUG': '8', 'SEP': '9', 
    'OCT': '10', 'NOV': '11', 'DEC': '12'} 
    DB_Month = str(split2[1]) 
    print DB_Month 
    M_Month = int(Month[DB_Month]) 
    M_year = split2(2) 
    print M_year 
    Changed_format = str(M_Month) +"/"+ str(M_date)+"/"+ str(M_year) 
    print Changed_format 

date_format_change() 

,但我得到錯誤說:

Traceback (most recent call last): 
    File "C:/Users/aannam002c/workspace/Website/Century/views.py", line 17, in <module> 
03 
    date_format_change() 
    File "C:/Users/aannam002c/workspace/Website/Century/views.py", line 5, in date_format_change 
    M_date = float(round(split2[0]),2) 
TypeError: a float is required 

Process finished with exit code 1 

任何人都可以幫忙嗎?

+0

'split2'保持字符串 - 你需要'INT( 「03」)'將文本轉換爲數字。 – furas

回答

1

浮動()需要一個參數,你給,也float型的日期並不好看。 int會完成這項工作。另外,round需要一個數字,而split2[0]是一個字符串。

這可能是你想要什麼:

def date_format_change(): 
    DB_date = "03-NOV-2016" 
    split2 = DB_date.split('-') 
    M_date = int(split2[0]) 
    Month = {'JAN': '1', 'FEB': '2', 'MAR': '3', 'APR': '4', 'MAY': '5','JUN': '6', 'JUL': '7', 'AUG': '8', 'SEP': '9', 
    'OCT': '10', 'NOV': '11', 'DEC': '12'} 
    print (M_date) 
    DB_Month = split2[1] 
    print (DB_Month) 
    M_Month = int(Month[DB_Month]) 
    M_year = split2[2] 
    print (M_year) 
    Changed_format = str(M_Month) +"/"+ str(M_date)+"/"+ str(M_year) 
    print (Changed_format) 

date_format_change() 

它返回:

3 
NOV 
2016 
11/3/2016 
+1

感謝Mahdi它幫助和工作! –

2

這裏是你的問題的一個簡單的解決方案:

from datetime import datetime 
DB_date = "03-NOV-2016" 
print datetime.strptime(DB_date, '%d-%b-%Y').strftime('%m/%d/%Y') 

希望這有助於。

+0

根據要求,這個結果是'11/03/2016',而不是'11/3/2016'。 –

+0

是的,我的月份需要是「3」而不是「03」格式。無論如何,非常感謝您的看法。 –

0

我特別喜歡的dateparser包。它使解析日期的第一步變得非常輕鬆。只要在它上面添加一個字符串,有點類似於日期或時間參考,它會將它轉換爲datetime

$ pip install dateparser 

一旦它被安裝:所以你不能圓的文字 「03」

import dateparser 
from datetime import datetime 

DB_date = "03-NOV-2016" 
date = dateparser.parse(DB_date) 

print datetime.datetime.strftime(date, '%m/%-d/%Y') 

# Output: 11/3/2016 
相關問題