pythonplotly

How to implement a 24-hour time picker in Dash Plotly without regional time formatting?


I am trying to integrate a time picker in my Dash Plotly application. I have tried using an input with type='time', which works fine, but it picks the regional time format. The requirement is to allow the selection of time in a 24-hour format.

Here's a basic example of what I have tried:

import dash
from dash import dcc, html

app = dash.Dash(__name__)

app.layout = html.Div([
    html.Label('Select Time:'),
    dcc.Input(type='time', id='time-picker', value='12:00'),
])

if __name__ == '__main__':
    app.run_server(debug=True)

Issue:
The above code picks the time format based on regional settings (e.g., 12-hour AM/PM), but I need a 24-hour format consistently.

What I have tried:

Setting type='time' in dcc.Input. Checked browser settings, which affect the display but not the requirement.

Requirement:
I need a time picker that allows selecting time in a 24-hour format without depending on the regional settings of the browser or the operating system.

Any suggestions or alternative components that could help achieve this in Dash Plotly?


Solution

  • You could build your own time picker in Plotly Dash with your desired format. Here is an simple example using the dcc.Dropdown components for input.

    Time Picker with values Time Picker with placeholder

    from dash import Dash, dcc, html
    
    hours = [f"{i:0{2}}" for i in range(24)]
    minutes = [f"{i:0{2}}" for i in range(60)]
    seconds = [f"{i:0{2}}" for i in range(60)]
    
    picker_style = {
        "display": "inline-block",
        "width": "40px",
        "cursor": "pointer",
        "border": "none",
    }
    
    separator = html.Span(":")
    
    app = Dash(__name__)
    
    app.layout = html.Div(
        [
            html.Label("Select Time:"),
            html.Div(
                [
                    dcc.Dropdown(
                        hours,
                        placeholder="HH",
                        style=picker_style,
                    ),
                    separator,
                    dcc.Dropdown(minutes, placeholder="MM",         style=picker_style),
                    separator,
                    dcc.Dropdown(seconds, placeholder="SS", style=picker_style),
                ],
                style={
                    "border": "1px solid gray",
                    "width": "140px",
                    "display": "flex",
                    "align-items": "center",
                },
            ),
        ],
        style={"font-family": "courier"},
    )
    
    if __name__ == "__main__":
        app.run_server(debug=True)