Python代码运行时图表随机显示UTC/IST时间戳问题求助
问题分析
你的问题根源在于:
- Supabase默认存储的
created_at是UTC时区的时间戳,但你仅做了字符串分割,未明确转换为IST时区 - 本地生成的
today是系统本地时间(IST),但Plotly解析无时区标记的时间字符串时,会自动推断时区,导致有时显示UTC、有时显示IST的随机问题
解决方案
需要统一将所有时间转换为带时区信息的IST时间,确保Plotly能正确识别。修改后的代码如下:
from supabase import create_client import pandas as pd import streamlit as st import plotly.express as px from datetime import datetime, timedelta import pytz # 导入时区处理库 # 初始化Supabase客户端 supabase = create_client(API_URL, API_KEY) supabaseList = supabase.table('Water Level').select('*').execute().data # 定义IST时区 ist = pytz.timezone('Asia/Kolkata') # 生成带时区的时间范围(IST) today = datetime.now(ist) present_date = today.strftime("%Y-%m-%d %X") hrs48 = today - timedelta(days=2) back_date = hrs48.strftime("%Y-%m-%d %X") df = pd.DataFrame() for row in supabaseList: # 解析Supabase的UTC时间戳,转换为IST utc_time = datetime.fromisoformat(row["created_at"].split(".")[0]).replace(tzinfo=pytz.utc) ist_time = utc_time.astimezone(ist) # 存储标准化的IST时间 row["DateTime"] = ist_time.strftime("%Y-%m-%d %X") row["date"] = ist_time.strftime("%Y-%m-%d") row["time"] = ist_time.strftime("%X") df = df.append(row, ignore_index=True) # 页面标题(修复原HTML标签错误) orignal_title = '<h1 style="font-family:Helvetica; color:Black; font-size: 45px; text-align: center">[Redacted]</h1>' st.markdown(orignal_title, unsafe_allow_html=True) st.text("") custom_range = [back_date, present_date] st.write(custom_range) fig = px.area(df, x="DateTime", y="water_level", title='', markers=False) fig.update_layout( title={ 'text': "Water level in %", 'y':0.9, 'x':0.5, 'xanchor': 'center', 'yanchor': 'top'}) fig.update_layout(yaxis_range=[0,120]) fig.update_layout(xaxis_range=custom_range) # 添加水泵触发水平线 fig.add_hline(y=80, line_width=3, line_color="black", annotation_text="Pump Start Level", annotation_position="top left", annotation_font_size=15, annotation_font_color="black" ) st.plotly_chart(fig, use_container_width=True)
关键修改点说明
- 引入
pytz库专门处理时区转换,彻底解决UTC与IST的混淆问题 - 将Supabase返回的UTC时间明确转换为IST时区,避免Plotly自动推断出错
- 本地时间生成时直接使用
datetime.now(ist),确保时间范围与数据时区统一 - 修复原代码中HTML标签不匹配的错误(
<h1>对应</h1>而非</p>)
内容的提问来源于stack exchange,提问作者Vedant Mhatre
相关产品推荐
相关产品推荐

