You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Plotly中基于UNIX时间戳按浏览器时区显示日期?

如何让Plotly图表按浏览器时区显示Pandas时间序列数据

我有一个基于UNIX时间戳生成datetime索引的Pandas DataFrame,希望在Plotly图表中自动根据浏览器时区显示日期时间,但尝试了多种方法都没实现预期效果。

已尝试的方法

  • 直接传入Python float类型的UNIX时间戳:图表将其显示为数值(符合预期,但不是日期格式)
  • 使用未本地化或UTC本地化的DataFrame索引:图表始终显示UTC时区的日期时间,无法适配浏览器时区
  • 将UTC本地化的索引转换为指定时区:图表显示固定时区的日期时间,不会随浏览器时区变化

核心疑问

考虑到JavaScript本身采用类UNIX时间戳作为日期时间的内部存储格式,我认为直接将数值型时间戳传给Plotly,让其自动转换为浏览器本地时区的日期格式应该高效可行,但没找到具体实现方式。想请教:

  1. 有没有可行的实现思路?
  2. 还是Plotly目前根本无法实现该需求,必须在服务端明确指定时区?

可复现的示例代码

import calendar
import time
import numpy as np
import pandas as pd
import plotly.graph_objects as go

def ptime(ts: str) -> float:
    return calendar.timegm(time.strptime(ts, '%Y-%m-%dT%H:%M:%SZ'))

columns = [
    'timestamp',
    'value',
]
data = np.array([
    [ptime('2024-01-01T00:00:00Z'), 0.0],
    [ptime('2024-01-01T01:00:00Z'), 1.0],
    [ptime('2024-01-01T02:00:00Z'), 2.0],
    [ptime('2024-01-01T03:00:00Z'), 3.0],
    [ptime('2024-01-01T04:00:00Z'), 4.0],
    [ptime('2024-01-01T05:00:00Z'), 5.0],
])

df = pd.DataFrame(data, columns=columns, index=pd.to_datetime(data[:, 0], unit='s'), dtype=float)

# 示例1:传入UNIX时间戳(显示为数值)
fig = go.Figure()
fig.add_trace(go.Scatter(
    x=df['timestamp'],
    y=df['value'],
))
fig.update_layout(
    title='UNIX timestamps',
    margin=dict(l=10, r=10, t=40, b=10),
)
fig.show(renderer='browser')

# 示例2:传入未本地化的DateTimeIndex(显示UTC时间)
fig = go.Figure()
fig.add_trace(go.Scatter(
    x=df.index,
    y=df['value'],
))
fig.update_layout(
    title='未本地化的Pandas DateTimeIndex',
    margin=dict(l=10, r=10, t=40, b=10),
)
fig.show(renderer='browser')

# 示例3:传入UTC本地化的DateTimeIndex(显示UTC时间)
fig = go.Figure()
fig.add_trace(go.Scatter(
    x=df.index.tz_localize('UTC'),
    y=df['value'],
))
fig.update_layout(
    title='UTC本地化的Pandas DateTimeIndex',
    margin=dict(l=10, r=10, t=40, b=10),
)
fig.show(renderer='browser')

# 示例4:转换为指定时区(显示固定时区时间,为期望的格式但无法跟随浏览器时区)
fig = go.Figure()
fig.add_trace(go.Scatter(
    x=df.index.tz_localize('UTC').tz_convert('US/Pacific'),
    y=df['value'],
))
fig.update_layout(
    title='转换为指定时区的DateTimeIndex',
    margin=dict(l=10, r=10, t=40, b=10),
)
fig.show(renderer='browser')

内容的提问来源于stack exchange,提问作者Philipp Burch

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 08:40:53