Search code examples
pythonlocalizationplotlyplotly-python

python-plotly date formatting with respect to locale


I'm using the python plotly lib to plot some timeseries. The problem I have is that somehow plotly doesn't honor my locale setting. See the following code:

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()

gives me the following output on the console:

('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

and the following diagram: plotly failing

I already searched a lot but nothing worked (I know I could convert the timestamps to strings before passing them to plotly, but that's no good style), so has anyone suggestions what's going wrong and how to fix it?


Solution

  • From what I can find at this time, Plotly does not seem to change date formats, etc. when changing locales. The only way to deal with this seems to be to convert strings. The basis for this answer comes from the community. The developer's comments are as of July 2021, so it is possible that this will be improved in the future. Also, my response may help other respondents to get a solution to this issue.

    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()
    

    enter image description here