我尝试将 MySQl 日期时间转换为 Python 中的相同日期时间。调试时有
ValueError:时间数据 '2001-06-04T11:30:35' 与格式 %Y-%m-%dT%H:%M:%S 不匹配。 在MySQL中,数据中没有“T”。我尝试了带“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
有什么问题吗?
最佳答案
如果示例日期字符串是 2001-06-04T11:30:35
,那么您需要:
birthday = datetime.strptime(str(birthday), "%Y-%m-%dT%H:%M:%S")
关于MySql 到 Python 日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40751387/