MySql 到 Python 日期

标签 mysql python-2.7 datetime pyqt4

我尝试将 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/

相关文章:

mysql - 如何在 debian 中安装 mysql-server :buster using script without being asked any configuration questions?

Python-从字符串中获取括号元组列表

python-2.7 - 按值范围分组数据

c# - 如果我的传入日期格式为 YYYYMMDD,则在 .NET 中将字符串转换为日期

sql - 将 Sitecore nvarchar 日期表示形式转换为 SQL 日期时间

java - TextArea 上的断线

python - Mysql AES_DECRYPT() 函数在 Django 原始查询中不起作用

php - GroupBy 和 where 条件 NOT IN 不能同时工作

python - 重新编码这些多个 if 语句的最有效方法

mysql - 返回 3 个月内的所有记录 (MySQL)