How to change date language?

Hi Plotly Community!
I am working with dates and I see all dates are in English format (e.g. Jan 2018), but I would like to configure my layout to use dates in Spanish. I have searched here and in the documentation and I didn’t see something clear about it.

Is there any option to change the language?

Thanks in advance!

Regards

@ivanhercaz,

I don’t know the spanish datetime format, but from this example you can deduce how to define xaxis_tickformat for your dates:

import pandas as pd
import numpy as np
import plotly.graph_objs as go
from datetime import datetime
d = {'date': [datetime(2020, 1, k) for k in range(2,7)],
      'A': np.random.rand(5)}
df=pd.DataFrame(d)
df

date	A
0	2020-01-02	0.139288
1	2020-01-03	0.753301
2	2020-01-04	0.950311
3	2020-01-05	0.569568
4	2020-01-06	0.886100
fig=go.Figure(go.Scatter(x=df['date'], y=df['A']),)
fig.update_xaxes(tickformat='%d-%b-%Y')
fig.update_layout(width=600, height=300)

tickformat

or:

fig.update_xaxes(tickformat='%d-%b-%y')

or

fig.update_xaxes(tickformat='%Y.%d.%b')

Hence tickformat( country datetime specific string) does the job.

3 Likes

@ivanhercaz you can also change the names of days and or months to be displayed in Spanish by using the locale module

import locale
locale.getlocale()
('en_US', 'UTF-8')

locale.setlocale(locale.LC_TIME, 'es_ES') # this sets the date time formats to es_ES, there are many other options for currency, numbers etc. 
'es_ES'

import datetime
today = datetime.datetime.now()
today

datetime.datetime(2020, 2, 14, 10, 33, 56, 487228)

today.strftime('%A %d de %B, %Y')

'viernes 14 de febrero, 2020'

Building on @empet’s example, you just have to format the dates in your DataFrame:

d = {'date': [datetime(2020, 1, k).strftime('%A %d de %B, %Y') for k in range(2,7)],
      'A': np.random.rand(5)}
1 Like

Thank you very much! Both answer are really helpful.

@eliasdabbas, your snippet is very useful! I forget to try to change the language using the locale module. However, it doesn’t works for me. I am working on Jupyter Notebook inside Google Colaboratory and it seems it doesn’t support the es_ES locale. I get this error Error: unsupported locale setting. I will keep in mind your workaround for next issues I will have with language in which is shown the dates.

@empet, thank you for show me tickformat attribute. I finally use it with the format %Y-%m-%d to update, in this case, my yaxis:

fig.update_yaxes(tickformat="%Y-%m-%d")

It isn’t the best format to show, maybe I would prefer something like “12 ene 2019” (Jan 12, 2019), but I can improve it in a near future with a better format. At least this one is clear and easy to understand all around the world.

Again, thank you both for your help! Now I can continue with my Plotly learning path :heart:

@ivanhercaz

Thanks @eliasdabbas for suggesting to set locale to es_ES. It works straightforward when we give simple datetime lists (as in your and my example), but when a Plotly user reads datetimes from a pandas dataframe, usually these are recorded as strings, like this: “2020-02-14”. In this case even if we are setting locale, it doesn’t change the format of ticklabels. One more operation must be performed. Two examples are illustrated in this notebook:
https://plot.ly/~empet/15517

1 Like

Wow! Thank you very much for the notebook you did to illustrate the change of the date language. It is very useful for me because I am using pandas too to read CSV file with data, in which the dates are in the format “year-month-day” (e.g. 2020-02-14).

I am going to bookmark your notebook for future reference!

1 Like

Yes, that’s what I mentioned in my last line, that dates need to be formatted :slight_smile:

d = {'date': [datetime(2020, 1, k).strftime('%A %d de %B, %Y') for k in range(2,7)],
      'A': np.random.rand(5)}

Thanks for the notebook!

1 Like

@eliasdabbas

I referred to datetime read from a pandas dataframe as a string of any type, i.e. the usual mode of recording dates in financial data.
That string must be converted to datetime, again (even if that column was defined as a datetime before saving the df to csv), in order to get locale working.

1 Like

Hi @empet, thanks for your notebook and explanations. I still have one question as I don’t manage to get what I want.

I thought that using pd.to_datetime() was enough to get dates in locale language on the chart. But apparently no. When I only use pd.to_datetime() dates are still plotted in english.

However, when adding the formatting function strftime to format dates, the dates are indeed plotted in my locale language but it looks like my px.bar() chart does not recognizes them as dates, therefore it is not plotting data in a chronological order, and not versus a “time” axis (meaning that data is plotted next to eachother in the same way when there is 1 day between two data or 20 days between them…).

Am I missing something ?

Below you can see the two type of graphs I get, it might help understanding my explanation of the problem… I would need the first graph but with dates in french.


1 Like

Hi @empet

I use to plot directly from numpy arrays retrieved with sqlalchemy command from a database dates are in datatime64[s] format and unfortunately month names stay in english whatever solution I try. Is there a way to change language with the right format ?

today = datetime.datetime.now()
start = str(int(round(today.timestamp())) - 173400)
dateTime DESC LIMIT 288)Var1 ORDER BY datetime ASC'
sql48h = 'SELECT dateTime, inTemp, outTemp, windchill, dewpoint, heatindex  FROM archive WHERE dateTime >= ' + start + ' ORDER BY dateTime ASC '
with engine.connect() as conn:
    result = conn.execute(text(sql48h))
data48h = np.empty((0,6), dtype = 'datetime64[s], float, float, float, float, float')

for row in result.all():
    data48h = np.append(data48h, [[np.datetime64(datetime.datetime.fromtimestamp(row[0]), 's'), 
                        row[1], 
                         row[2], 
                         row[3], 
                         row[4], 
                         row[5]]], axis=0)
dateT48h = data48h[:,0]
inTemp48h = data48h[:,1]
outTemp48h = data48h[:,2]
windchill48h = data48h[:,3]
dewpoint48h = data48h[:,4]
heatindex48h = data48h[:,5]

fig = go.Figure()
fig.add_trace(go.Scatter(x=dateT48h, y=inTemp48h, name='Temp. Intérieure',
                         line=dict(color='darkorange', width=2)))fig.update_layout(title=figTitle + '(48 heures)',
                  height=800,
                  width=1200,
                  paper_bgcolor='lightyellow',
                  xaxis_title='Date',
                  yaxis_title='Temperature (degrés Celsius)',
                  legend=dict(orientation='h',
                              bgcolor='lightblue',
                              x=0.2,
                              y=-0.12,
                              bordercolor='#444',
                              borderwidth=1))
fig.update_xaxes(linecolor='#444',
                 linewidth=1,
                 dtick='10800000',
                 tickformat='%H:%M\n%d/%b',
                 minor_ticklen=3)
fig.show()

Here is the firs line of the numpy array :

[numpy.datetime64('2022-08-26T10:10:00') 24.0500367917587 22.891464311994
 22.891464311994 17.5628838729488 23.1155610743195]

thanks