python-根据区域设置绘制日期格式

python-plotly date formatting with respect to locale

我正在使用 python plotly 库绘制一些时间序列。我遇到的问题是,不知何故 plotly 不尊重我的语言环境设置。 见以下代码:

import pandas as pd
import numpy as np
import plotly.express as px
from datetime import datetime
import locale


#Get information on the actual locale setting:
print(locale.getlocale())


#Set locale for another country:
locale.setlocale(locale.LC_TIME, 'de_DE.UTF-8') # this sets the date time formats to Germany; there are many other options for currency, numbers etc. 
#for any other locale settings see: https://docs.python.org/3/library/locale.html

d = {'Time': [datetime(2020, k, 15) for k in range(2,7)],
      'value': np.random.rand(5)}
df=pd.DataFrame(d)
print(df)
print(df.info())
print(df["Time"].dt.strftime("%a %H:%M"))

fig = px.line(df, y="value", x="Time")
fig.update_xaxes(
    tickformat="%a\n%H:%M",
)
fig.show()

在控制台上给我以下输出:

('de_DE', 'UTF-8')
        Time     value
0 2020-02-15  0.541681
1 2020-03-15  0.639813
2 2020-04-15  0.127375
3 2020-05-15  0.019197
4 2020-06-15  0.617402
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 5 entries, 0 to 4
Data columns (total 2 columns):
 #   Column  Non-Null Count  Dtype         
---  ------  --------------  -----         
 0   Time    5 non-null      datetime64[ns]
 1   value   5 non-null      float64       
dtypes: datetime64[ns](1), float64(1)
memory usage: 208.0 bytes
None
0    Sa 00:00
1    So 00:00
2    Mi 00:00
3    Fr 00:00
4    Mo 00:00
Name: Time, dtype: object

以及下图:

我已经搜索了很多但没有任何效果(我知道我可以在将时间戳传递给 plotly 之前将它们转换为字符串,但这不是好的风格),所以有人建议出了什么问题以及如何解决它吗?

据我目前所知,Plotly 在更改语言环境时似乎不会更改日期格式等。处理这个问题的唯一方法似乎是转换字符串。这个答案的基础来自community。开发者的评论截止到2021年7月,因此未来可能会对此进行改进。此外,我的回复可能会帮助其他受访者找到解决此问题的方法。

import pandas as pd
import numpy as np
import plotly.express as px
import plotly.graph_objects as go
from datetime import datetime
import locale

#Get information on the actual locale setting:
print(locale.getlocale())

#Set locale for another country:
locale.setlocale(locale.LC_TIME, 'de_DE.UTF-8') 
# this sets the date time formats to Germany; there are many other options for currency, numbers etc.
# for any other locale settings see: https://docs.python.org/3/library/locale.html

d = {'Time': [datetime(2020, k, 15) for k in range(2,7)],
      'value': np.random.rand(5)}
df=pd.DataFrame(d)
print(df)
print(df.info())
print(df["Time"].dt.strftime("%a %H:%M"))

#fig = px.line(df, y="value", x="Time")
# Update
fig = go.Figure(go.Scatter(mode='lines', x=[d.strftime('%a\n%H:%M') for d in df['Time']], y=df['value']))
#fig.update_xaxes(tickformat="%a\n%H:%M",)
fig.show()