baoshiwei
2026-01-20 faa25a85c10aa0fa2df824318a4bfa542f6a5a46
app/services/extruder_service.py
@@ -1,19 +1,25 @@
import pandas as pd
from functools import lru_cache
from datetime import timedelta
from app.database.database import DatabaseConnection
class ExtruderService:
    def __init__(self):
        self.db = DatabaseConnection()
        self.timezone_offset = 8  # 默认东八区(北京时间)
    
    def get_extruder_data(self, start_date, end_date):
        """
        查询挤出机数据
        :param start_date: 开始日期
        :param end_date: 结束日期
        :return: 包含挤出机数据的数据框
        :param start_date: 开始日期 (本地时间)
        :param end_date: 结束日期 (本地时间)
        :return: 包含挤出机数据的数据框 (返回本地时间)
        """
        try:
            # 将本地时间转换为UTC时间进行查询
            start_date_utc = start_date - timedelta(hours=self.timezone_offset)
            end_date_utc = end_date - timedelta(hours=self.timezone_offset)
            # 连接数据库
            if not self.db.is_connected():
                if not self.db.connect():
@@ -47,7 +53,11 @@
            """
            
            # 执行查询并转换为DataFrame
            df = pd.read_sql(query, connection, params=(start_date, end_date))
            df = pd.read_sql(query, connection, params=(start_date_utc, end_date_utc))
            # 将查询结果中的UTC时间转换回本地时间
            if not df.empty and 'time' in df.columns:
                df['time'] = pd.to_datetime(df['time']) + timedelta(hours=self.timezone_offset)
            
            return df
        except Exception as e:
@@ -75,9 +85,8 @@
            batch_df['compound_code_shift'] = batch_df['compound_code'].shift(1)
            # 若当前行 compound_code 与前一行不同,则标记为换批(1),否则为 0 ,第一行特殊处理为 0
            batch_df['is_batch_change'] = (batch_df['compound_code'] != batch_df['compound_code_shift']).astype(int)
            batch_df['is_batch_change'].iloc[0] = 0
            # 打印batch_df
            print(batch_df)
            batch_df.loc[batch_df.index[0], 'is_batch_change'] = 0
            # 提取所有换批事件的索引
            change_indices = batch_df[batch_df['is_batch_change'] == 1].index.tolist()