baoxiang/test_time_calculation.py
2025-12-16 18:06:50 +08:00

63 lines
2.1 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/env python3
"""
测试宝箱倒计时计算逻辑
"""
import sys
import os
from datetime import datetime, timedelta
# 添加项目路径
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'backend'))
from backend.app.models.game import Chest
from backend.app.models.game import ChestStatus
def test_time_calculation():
"""测试时间计算逻辑"""
print("=== 宝箱倒计时计算测试 ===")
# 创建一个测试宝箱
chest = Chest()
chest.id = 1
chest.status = ChestStatus.BETTING
chest.countdown_seconds = 300 # 5分钟
# 模拟创建时间为5秒前
chest.created_at = datetime.utcnow() - timedelta(seconds=5)
print(f"宝箱ID: {chest.id}")
print(f"创建时间: {chest.created_at}")
print(f"倒计时设置: {chest.countdown_seconds}")
print(f"当前UTC时间: {datetime.utcnow()}")
# 模拟后端计算逻辑
if isinstance(chest.created_at, str):
# 处理ISO格式字符串假设存储的是UTC时间
if 'T' in chest.created_at:
created_time = datetime.fromisoformat(chest.created_at.replace('Z', '+00:00')).replace(tzinfo=None)
else:
# 处理MySQL datetime格式 (YYYY-MM-DD HH:MM:SS)
created_time = datetime.strptime(chest.created_at, '%Y-%m-%d %H:%M:%S')
else:
# 如果是从数据库获取的datetime对象确保转换为naive datetime
created_time = chest.created_at.replace(tzinfo=None) if chest.created_at.tzinfo else chest.created_at
# 使用UTC时间进行计算
now = datetime.utcnow()
elapsed = (now - created_time).total_seconds()
time_remaining = max(0, int(chest.countdown_seconds - elapsed))
print(f"已过去时间: {elapsed:.2f}")
print(f"剩余时间: {time_remaining}")
print(f"格式化显示: {format_time(time_remaining)}")
return time_remaining
def format_time(seconds):
"""格式化时间显示"""
mins = seconds // 60
secs = seconds % 60
return f"{int(mins):02d}:{int(secs):02d}"
if __name__ == "__main__":
test_time_calculation()