修改时间时区问题

This commit is contained in:
dxc
2026-02-05 14:36:36 +08:00
parent 0bc47d306d
commit 4f90e02dcf
4 changed files with 40 additions and 16 deletions

View File

@ -1,5 +1,5 @@
import uuid
from datetime import datetime
from datetime import datetime, timezone, timedelta # [修改] 引入 timezone 和 timedelta
from sqlalchemy import or_
from app.extensions import db
from app.models.outbound import TransOutbound
@ -16,8 +16,15 @@ class OutboundService:
@staticmethod
def generate_outbound_no():
"""生成出库单号: OUT-yyyyMMdd-随机码"""
date_str = datetime.now().strftime('%Y%m%d')
"""
生成出库单号: OUT-yyyyMMdd-随机码
[修改] 强制使用北京时间生成日期前缀
"""
# 获取北京时间
beijing_tz = timezone(timedelta(hours=8))
current_time = datetime.now(beijing_tz)
date_str = current_time.strftime('%Y%m%d')
short_uuid = uuid.uuid4().hex[:6].upper()
return f"OUT-{date_str}-{short_uuid}"
@ -143,6 +150,12 @@ class OutboundService:
stock_item.stock_quantity = float(stock_item.stock_quantity) - quantity
stock_item.available_quantity = float(stock_item.available_quantity) - quantity
# [新增] 计算北京时间
beijing_tz = timezone(timedelta(hours=8))
# replace(tzinfo=None) 是为了让存入数据库的时间变为 naive time (不带时区信息的本地时间)
# 这样数据库看起来就是 "2023-10-27 15:00:00" 而不是 UTC 时间
current_time = datetime.now(beijing_tz).replace(tzinfo=None)
# 5. 创建出库记录
new_outbound = TransOutbound(
outbound_no=OutboundService.generate_outbound_no(),
@ -154,6 +167,10 @@ class OutboundService:
quantity=quantity,
consumer_name=data.get('consumer_name'),
signature_path=data.get('signature_path'), # 存储签名的 URL
# [关键] 显式设置北京时间,覆盖 Model 中的 default=datetime.now (UTC)
outbound_time=current_time,
operator_name=operator_name,
remark=data.get('remark')
)