Home > Net >  Combine Date and Time inputs in Streamlit with dataframe time column
Combine Date and Time inputs in Streamlit with dataframe time column

Time:12-29

I have a df that has a column 'Time' in seconds:

Time
1
2
3
4

I want the user to input the date with a timestamp (eg format: 25/09/2022 12:30:00). Then, I need to add a new column 'DateTime' which combines the user input datetime with my 'Time' column. The 'DateTime' column should look like this:

DateTime
25/09/2022 12:30:01
25/09/2022 12:30:02
25/09/2022 12:30:03
25/09/2022 12:30:04

I managed to do this in python, where the user input is on the terminal, however, I would like to have this in Streamlit. From the documentation, there is currently no possibility to input date with a timestamp in Streamlit, unless you enter them separately, as follows:

start_date = st.date_input('Enter start date', value=datetime.datetime(2019,7,6))
start_time = st.time_input('Enter start time', datetime.time(8, 45))

So, this gives the user the possibility to enter the date and time separately, however I don't know how to derive my 'DateTime' column and add it to the df. Appreciate any advice on how to accomplish this.

CodePudding user response:

You can use the .combine() function from pandas to combine your start_date with start_time, after you have accomplished that. Make a new df named DateTime and loop through your Time df to concatenate the seconds to DateTime, after the concatenation, format the DateTime. You can then drop Time column after haven looped through it.

Example:

# Your df that contains "Time" column
df = pd.DataFrame({"Time":[1, 2, 3, 4]})

start_date = st.date_input('Enter start date', value=datetime.datetime(2019,7,6))
start_time = st.time_input('Enter start time', datetime.time(8, 45))

start_datetime = datetime.datetime.combine(start_date, start_time)

df["DateTime"] = [start_datetime   datetime.timedelta(seconds=time) for time in df["Time"]]

df["DateTime"] = [date.strftime("%d/%m/%Y %H:%M:%S") for date in df["DateTime"]]

df = df.drop(columns=["Time"])

st.dataframe(df)

Output:

              DateTime
0  06/07/2019 08:45:01
1  06/07/2019 08:45:02
2  06/07/2019 08:45:03
3  06/07/2019 08:45:04
  • Related