修复统计数据时区问题: 使用本地时区(Asia/Shanghai)计算今日和本周统计
问题: 原代码使用SQLite的DATE('now')获取的是UTC时间,不是本地时间
解决: 在Python中使用pytz计算本地时区的今日/本周时间范围,转换为UTC后查询数据库
This commit is contained in:
29
database.py
29
database.py
@@ -312,25 +312,44 @@ class Database:
|
||||
|
||||
def get_statistics(self) -> Dict[str, Any]:
|
||||
"""获取统计信息"""
|
||||
import pytz
|
||||
|
||||
conn = self.get_connection()
|
||||
cursor = conn.cursor()
|
||||
|
||||
# 总短信数
|
||||
# 获取总短信数
|
||||
cursor.execute('SELECT COUNT(*) as total FROM sms_messages')
|
||||
total = cursor.fetchone()['total']
|
||||
|
||||
# 使用本地时区计算今日和本周的 UTC 时间范围
|
||||
local_tz = pytz.timezone(self.timezone)
|
||||
local_now = datetime.now(local_tz)
|
||||
|
||||
# 今日本地时间的开始和结束
|
||||
today_start_local = local_now.replace(hour=0, minute=0, second=0, microsecond=0)
|
||||
today_end_local = today_start_local + timedelta(days=1)
|
||||
|
||||
# 转换为 UTC 时间
|
||||
today_start_utc = today_start_local.astimezone(pytz.UTC)
|
||||
today_end_utc = today_end_local.astimezone(pytz.UTC)
|
||||
|
||||
# 今日短信数
|
||||
cursor.execute('''
|
||||
SELECT COUNT(*) as today FROM sms_messages
|
||||
WHERE DATE(created_at) = DATE('now')
|
||||
''')
|
||||
WHERE created_at >= ? AND created_at < ?
|
||||
''', (today_start_utc.strftime('%Y-%m-%d %H:%M:%S'), today_end_utc.strftime('%Y-%m-%d %H:%M:%S')))
|
||||
today = cursor.fetchone()['today']
|
||||
|
||||
# 本周开始时间(本周一 00:00:00 本地时间)
|
||||
weekday = local_now.weekday()
|
||||
week_start_local = (local_now - timedelta(days=weekday)).replace(hour=0, minute=0, second=0, microsecond=0)
|
||||
week_start_utc = week_start_local.astimezone(pytz.UTC)
|
||||
|
||||
# 本周短信数
|
||||
cursor.execute('''
|
||||
SELECT COUNT(*) as week FROM sms_messages
|
||||
WHERE created_at >= datetime('now', '-7 days')
|
||||
''')
|
||||
WHERE created_at >= ?
|
||||
''', (week_start_utc.strftime('%Y-%m-%d %H:%M:%S'),))
|
||||
week = cursor.fetchone()['week']
|
||||
|
||||
# 签名验证占比
|
||||
|
||||
Reference in New Issue
Block a user