I have a sample code below that creates a timedelta column.
While it is sortabe in Python, streamlit treats the column as string column, giving invalid sorting results.
#! /usr/bin/env python3
import time
import pandas as pd
import datetime
import streamlit as st
def main():
'Main function'
# Create a Dataframe with random timestamps in last 6 years
now = time.time()
times = [
now - 1, # 1 second ago
now - 2, # 2 seconds ago
now - 5, # 5 seconds ago
now - 60, # 1 minute ago
now - 60 * 2, # 2 minutes ago
now - 60 * 5, # 5 minutes ago
now - 60 * 60, # 1 hour ago
now - 60 * 60 * 2, # 2 hours ago
now - 60 * 60 * 5, # 5 hours ago
]
df = pd.DataFrame({'Delta': times})
df['Delta'] = datetime.datetime.now().astimezone() - pd.to_datetime(
df['Delta'], unit='s', utc=True
)
st.set_page_config(layout='wide')
st.dataframe(df, use_container_width=True)
df.sort_values(by='Delta', inplace=True, ascending=False)
st.dataframe(df, use_container_width=True)
main()
To run
streamlit run --server.runOnSave True --server.port 8501 ./tmp.py
Before sorting (Presorted DF in both ways)
After sorting via UI
I tried exploring other column config types available, but none works.
Is there a way to format the values as it shows in streamlit app while retaining the underlying numeric values for sorting.
Krishna