109 lines
3.5 KiB
Python
109 lines
3.5 KiB
Python
"""
|
|
2월 시간별 데이터 중복 제거 스크립트
|
|
같은 plant_id와 시간대에 중복된 데이터를 정리
|
|
"""
|
|
|
|
import sys
|
|
import os
|
|
from datetime import datetime, timedelta
|
|
from dotenv import load_dotenv
|
|
|
|
load_dotenv()
|
|
|
|
if sys.platform.startswith('win'):
|
|
sys.stdout.reconfigure(encoding='utf-8')
|
|
sys.stderr.reconfigure(encoding='utf-8')
|
|
|
|
current_dir = os.path.dirname(os.path.abspath(__file__))
|
|
sys.path.append(current_dir)
|
|
|
|
from database import get_supabase_client
|
|
|
|
def clean_duplicates(plant_id, plant_name):
|
|
"""중복 데이터 제거 - 같은 시간대에 가장 최신 레코드만 유지"""
|
|
|
|
print(f"\n{'='*70}")
|
|
print(f"🧹 [{plant_name}] 중복 데이터 정리 중...")
|
|
print(f"{'='*70}")
|
|
|
|
client = get_supabase_client()
|
|
if client is None:
|
|
return
|
|
|
|
# 2월 1일부터 27일까지
|
|
start = datetime(2026, 2, 1)
|
|
end = datetime(2026, 2, 27)
|
|
|
|
total_deleted = 0
|
|
|
|
current = start
|
|
while current <= end:
|
|
date_str = current.strftime("%Y-%m-%d")
|
|
|
|
# 해당 날짜의 모든 시간별 데이터 가져오기
|
|
result = client.table("solar_logs") \
|
|
.select("*") \
|
|
.eq("plant_id", plant_id) \
|
|
.gte("created_at", f"{date_str}T00:00:00+09:00") \
|
|
.lt("created_at", f"{(current + timedelta(days=1)).strftime('%Y-%m-%d')}T00:00:00+09:00") \
|
|
.order("created_at", desc=False) \
|
|
.execute()
|
|
|
|
if not result.data:
|
|
current += timedelta(days=1)
|
|
continue
|
|
|
|
# 시간대별로 그룹화 (created_at의 시간 부분으로)
|
|
hour_groups = {}
|
|
for record in result.data:
|
|
# created_at에서 날짜+시간만 추출 (분/초 제거)
|
|
ts = record['created_at']
|
|
hour_key = ts[:13] # 2026-02-01T00 형식
|
|
|
|
if hour_key not in hour_groups:
|
|
hour_groups[hour_key] = []
|
|
hour_groups[hour_key].append(record)
|
|
|
|
# 각 시간대별로 중복 제거 (가장 최근 id만 유지)
|
|
deleted_count = 0
|
|
for hour_key, records in hour_groups.items():
|
|
if len(records) > 1:
|
|
# id 기준으로 정렬 (가장 큰 id가 최신)
|
|
records.sort(key=lambda x: x['id'], reverse=True)
|
|
|
|
# 첫 번째(최신)를 제외한 나머지 삭제
|
|
for old_record in records[1:]:
|
|
try:
|
|
client.table("solar_logs").delete().eq("id", old_record['id']).execute()
|
|
deleted_count += 1
|
|
except Exception as e:
|
|
print(f" ⚠️ 삭제 실패 (id: {old_record['id']}): {e}")
|
|
|
|
if deleted_count > 0:
|
|
print(f" 🧹 {date_str}: {deleted_count}건 중복 제거 (남은 시간대: {len(hour_groups)}개)")
|
|
|
|
total_deleted += deleted_count
|
|
current += timedelta(days=1)
|
|
|
|
print(f"\n✅ [{plant_name}] 총 {total_deleted}건 중복 제거 완료")
|
|
|
|
def main():
|
|
plants = [
|
|
('kremc-05', '5호기'),
|
|
('nrems-09', '9호기')
|
|
]
|
|
|
|
print("\n" + "="*70)
|
|
print("🧹 2월 시간별 데이터 중복 제거 시작")
|
|
print("="*70)
|
|
|
|
for plant_id, plant_name in plants:
|
|
clean_duplicates(plant_id, plant_name)
|
|
|
|
print("\n" + "="*70)
|
|
print("🎉 중복 제거 완료!")
|
|
print("="*70 + "\n")
|
|
|
|
if __name__ == "__main__":
|
|
main()
|