2017-06-15 42 views
0

我試圖將12小時格式的時間轉換爲24小時格式。我不知道爲什麼我得到無效的語法錯誤。Python簡單的時間轉換代碼

def timeConversion(s): 
    # Complete this function 
    if s[-2:]=='PM': 
     temp=s[:-2].split(':') 
     print temp 
     if temp[0]=='12': 
      time= str(12)+':'+temp[1]+':'+temp[2] 
     else: 
      time= str(int(temp[0]+12)+':'+temp[1]+':'+temp[2] 

    elif s[-2:]=='AM': 
     temp=s[:-2].split(':') 
     print temp 
     if temp[0]=='12': 
      time= '00:'+temp[1]+':'+temp[2] 
     else: 
      time= temp[0]+':'+temp[1]+':'+temp[2] 

    return time 

timeConversion("07:05:45PM") 

下面是錯誤:

enter image description here

+0

在哪條線上出現錯誤。您使用的是哪種Python版本 –

+1

我認爲在第二行有一個縮進 –

+1

爲什麼不使用'strptime'和'strftime'? –

回答

3

你缺少一個右括號:

 time= str(int(temp[0]) + 12)+':'+temp[1]+':'+temp[2] 
         ^
          here 

return time行的縮進必須甚至與if/elif語句。

或者,你可以完成你正在嘗試做了很多更容易通過strptime字符串加載到一個DateTime對象,然後ouputting所需的格式與strftime

from datetime import datetime 

print datetime.strptime("07:05:45PM", "%I:%M:%S%p").strftime("%H:%M:%S") 
+0

你正確的識別了這個問題,但是位置是錯誤的 - 關閉括號應該在'str(int(temp [0] + 12)'之後立即執行。 –

+0

@HughBothwell好了!修正了 – ILostMySpoon

+0

我認爲正確的代碼是'str (int(temp [0])+ 12)',因爲我們不能將str'temp [0]'和int'12'加在一起。 – zmwang

1

我會後回答因爲我無法發表評論,因爲@ILostMySpoon告訴過你在演員中錯過了一個括號。我想補充的是,通常對於「非法語法」錯誤,您應該關注拋出錯誤的那一行。我認爲這是由於解釋者認爲「elif」這一行是先例的延續,顯然它不理解語法。