2016-11-22 20 views
0

我嘗試MySQL的日期時間轉換爲Python.On調試同樣有MySQL來Python的日期

ValueError異常:實時數據 '2001-06-04T11:30:35' 不匹配格式%Y-% m-%dT%H:%M:%S。 在MySQL中,數據中沒有'T'。我試着格式化爲'T'而沒有。

我看到這篇文章How to convert the following string to python date?

這是代碼:

query = QSqlQuery() 
query.exec_("SELECT birthday FROM vista.user ")  
def countAge(birthday): 
    birthday = datetime.strptime(str(birthday), "%Y-%m-%dT%H:%M:%S.%f") 
    today = date.today() 
    age = today.year - birthday.year 
    if today.month < birthday.month: 
     age -= 1 
    elif today.month == birthday.month and today.day < birthday.day: 
     age -= 1 
    if age >= 0 : 
     return age 
ages = [] 
index = 0 
while (query.next()): 
    print(query.value(index).toString()) 
    ages.append(countAge(query.value(index).toString())) 
    index = index + 1 

什麼是問題?

+0

那麼,什麼是輸出:'打印(query.value(指數)的ToString())'? – ekhumoro

+0

2001-06-04T11:30:35 –

+0

@ekhumoro,它用於測試 –

回答

1

如果一個例子日期字符串是2001-06-04T11:30:35,那麼你需要:

birthday = datetime.strptime(str(birthday), "%Y-%m-%dT%H:%M:%S")