How to remove timestamp from datetime column in pandas Style Object

I have a DataFrame with a Date column that has no timestamp:

date without timestamp

But once I apply style to another column in the df, e.g. :

df = df.style.applymap(colorFunction, subset=['column3'])

The DataFrame becomes a Style Object, and the "Date" column gets a timestamp that it didn't have before, as the following:

enter image description here

I tried the following to strip the timestamp from the Date column:

df['Date'].style.apply(lambda x: x.strftime('%Y-%m-%d'))

I got the following error:

TypeError: 'Styler' object is not subscriptable

Is there any way to remove the time stamp from the Style object?

2 answers

  • answered 2022-01-19 16:49 Peter Leimbigler

    This is just a stopgap solution, but you can manually specify the usual %Y-%m-%d display format for your date column as follows:

    styled = (df.style
                .applymap(colorFunction, subset=['column3'])
                .format({'Date': '{:%Y-%m-%d}'}))
    

    Example

    # Example data
    df = pd.DataFrame({'Date': pd.date_range('2020-01-01', 
                                             '2020-01-05', 
                                             freq='d'),
                       'Value': list(range(-2, 3))})
    
    # Example color function
    def f(v):
        return 'color: red;' if v < 0 else None
    
    # Unexpected addition of H:M:S to date column
    df.style.applymap(f, subset='Value')
    

    Styler with unexpected datetime display format

    # Specify desired date format
    df.style.applymap(f, subset='Value').format({'Date': '{:%Y-%m-%d}'}))
    

    Styler with manually fixed datetime display format

  • answered 2022-01-20 14:02 Samwise

    Besides the good answer provided by @Peter Leimbigler, as an alternative solution, converting the Date column to a string before applying the Style prevents the Styler formatter from adding timestamp.

    df['Date'] = df['Date'].astype(str)
    

    Using Peter's example:

    # Example data
    df = pd.DataFrame({'Date': pd.date_range('2020-01-01', 
                                             '2020-01-05', 
                                             freq='d'),
                       'Value': list(range(-2, 3))})
    
    # Example color function
    def f(v):
        return 'color: red;' if v < 0 else None
    
    # Converting the Date column to a string before applying the Style
    df['Date'] = df['Date'].astype(str)
    
    df.style.applymap(f, subset='Value')
    

    enter image description here

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum