python+ pymysql + peewee 关于时区问题

开门见山

研究的问题:如果我插入一个 datetime 的 tzinfo 北京时区的,peewee insert 的时候,会帮我转成 utc 再插入吗?

答案:不会


研究过程

我们通过

  • peewee 返回对的 sql
  • peewee 内部的 sql
  • 以及 wireshark 抓包获取的 sql

三者验证判断

from loguru import logger
import settings
from peewee import *
from datetime import datetime, timedelta, timezone
import time
import contextlib


def get_min_utc_timestamp() -> datetime:
    return (datetime(year=1970, month=1, day=1) + timedelta(seconds=1)).replace(tzinfo=timezone.utc)


def get_utc_now_timestamp() -> datetime:
    """ https://blog.csdn.net/ball4022/article/details/101670024 """
    return datetime.utcnow().replace(tzinfo=timezone.utc)


def get_cst_now_timestamp() -> datetime:
    """ https://segmentfault.com/q/1010000043912065 """
    try:
        from zoneinfo import ZoneInfo
        tz = ZoneInfo('Asia/Shanghai')
        return datetime.now(tz)
    except ImportError:
        beijing_offset = timedelta(hours=8)
        current_time = datetime.now(timezone(beijing_offset))
        return current_time


host = settings.MYSQL_CONFIG.host
port = settings.MYSQL_CONFIG.port
username = settings.MYSQL_CONFIG.username
password = settings.MYSQL_CONFIG.password
database_name = settings.MYSQL_CONFIG.database_name

db = MySQLDatabase(
    database=database_name,
    host=host,
    port=port,
    user=username,
    password=password,
    charset='utf8mb4'
)


class User(Model):
    name = CharField(unique=True)
    age = IntegerField(null=True)
    address = CharField(null=True)
    city = CharField(null=True)
    birth = DateTimeField(null=True)

    created_at = DateTimeField(
        null=False,
        constraints=[SQL('DEFAULT CURRENT_TIMESTAMP')],
        help_text='使用数据库时间'
    )
    updated_at = DateTimeField(
        null=False,
        constraints=[
            SQL('DEFAULT CURRENT_TIMESTAMP'),
            SQL('ON UPDATE CURRENT_TIMESTAMP'),
        ]
    )

    class Meta:
        database = db
        table_name = 'user'


model_set = [User]
db.drop_tables(model_set)
db.create_tables(model_set)


d = get_cst_now_timestamp()
print(d)

q = User.select().where(
    User.age == 1,
    User.birth == d
)

print('> sql', str(q))
list(q)


q = User.insert({'created_at': d})
logger.debug(str(q))
q.execute()

然后修改 peewee 的源码:

python+ pymysql + peewee 关于时区问题_第1张图片

然后运行代码

输出如下:

>>> execute_sql sql SELECT table_name FROM information_schema.tables WHERE table_schema = DATABASE() AND table_type != %s ORDER BY table_name
>> execute sql DROP TABLE IF EXISTS `user`
>>> execute_sql sql DROP TABLE IF EXISTS `user`
>>> execute_sql sql SELECT table_name FROM information_schema.tables WHERE table_schema = DATABASE() AND table_type != %s ORDER BY table_name
>> execute sql CREATE TABLE IF NOT EXISTS `user` (`id` INTEGER AUTO_INCREMENT NOT NULL PRIMARY KEY, `name` VARCHAR(255) NOT NULL, `age` INTEGER, `address` VARCHAR(255), `city` VARCHAR(255), `birth` DATETIME, `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP)
>>> execute_sql sql CREATE TABLE IF NOT EXISTS `user` (`id` INTEGER AUTO_INCREMENT NOT NULL PRIMARY KEY, `name` VARCHAR(255) NOT NULL, `age` INTEGER, `address` VARCHAR(255), `city` VARCHAR(255), `birth` DATETIME, `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP)
>> execute sql CREATE UNIQUE INDEX `user_name` ON `user` (`name`)
>>> execute_sql sql CREATE UNIQUE INDEX `user_name` ON `user` (`name`)
2023-06-17 14:26:22.111281+08:00
> sql SELECT `t1`.`id`, `t1`.`name`, `t1`.`age`, `t1`.`address`, `t1`.`city`, `t1`.`birth`, `t1`.`created_at`, `t1`.`updated_at` FROM `user` AS `t1` WHERE ((`t1`.`age` = 1) AND (`t1`.`birth` = '2023-06-17 14:26:22.111281+08:00'))
>> execute sql SELECT `t1`.`id`, `t1`.`name`, `t1`.`age`, `t1`.`address`, `t1`.`city`, `t1`.`birth`, `t1`.`created_at`, `t1`.`updated_at` FROM `user` AS `t1` WHERE ((`t1`.`age` = %s) AND (`t1`.`birth` = %s))
>>> execute_sql sql SELECT `t1`.`id`, `t1`.`name`, `t1`.`age`, `t1`.`address`, `t1`.`city`, `t1`.`birth`, `t1`.`created_at`, `t1`.`updated_at` FROM `user` AS `t1` WHERE ((`t1`.`age` = %s) AND (`t1`.`birth` = %s))
2023-06-17 14:26:22.116 | DEBUG    | __main__::68 - INSERT INTO `user` (`created_at`) VALUES ('2023-06-17 14:26:22.111281+08:00')
>> execute sql INSERT INTO `user` (`created_at`) VALUES (%s)
>>> execute_sql sql INSERT INTO `user` (`created_at`) VALUES (%s)
self._query_type 0
注意,我现在测试的时间,就是北京时间下午2点

查看 wireshark 的时间

python+ pymysql + peewee 关于时区问题_第2张图片

python+ pymysql + peewee 关于时区问题_第3张图片

可以看到,抓包获得的时间,都是下午2点,说明没有发生时区转换

python+ pymysql + peewee 关于时区问题_第4张图片

数据中写入的时间,也是下午两点,说明没错

你可能感兴趣的:(pythonmysql)