python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > python pymysql peewee时区

python pymysql peewee关于时区问题分析

作者:ponponon

这篇文章主要为大家介绍了python pymysql peewee关于时区问题分析,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

正文

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

答案:不会

研究过程

我们通过

验证判断

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 的源码

输出如下:

>>> 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__:<module>: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 的时间

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

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

以上就是python pymysql peewee关于时区问题分析的详细内容,更多关于python pymysql peewee时区的资料请关注脚本之家其它相关文章!

您可能感兴趣的文章:
阅读全文