I have a DataFrame with a Date column that has no timestamp:
But once I apply style
to another column in the df, e.g. :
JavaScript
x
2
1
df = df.style.applymap(colorFunction, subset=['column3'])
2
The DataFrame becomes a Style Object, and the “Date” column gets a timestamp that it didn’t have before, as the following:
I tried the following to strip the timestamp from the Date column:
JavaScript
1
2
1
df['Date'].style.apply(lambda x: x.strftime('%Y-%m-%d'))
2
I got the following error:
JavaScript
1
2
1
TypeError: 'Styler' object is not subscriptable
2
Is there any way to remove the time stamp from the Style object?
Advertisement
Answer
This is just a stopgap solution, but you can manually specify the usual %Y-%m-%d
display format for your date column as follows:
JavaScript
1
4
1
styled = (df.style
2
.applymap(colorFunction, subset=['column3'])
3
.format({'Date': '{:%Y-%m-%d}'}))
4
Example
JavaScript
1
13
13
1
# Example data
2
df = pd.DataFrame({'Date': pd.date_range('2020-01-01',
3
'2020-01-05',
4
freq='d'),
5
'Value': list(range(-2, 3))})
6
7
# Example color function
8
def f(v):
9
return 'color: red;' if v < 0 else None
10
11
# Unexpected addition of H:M:S to date column
12
df.style.applymap(f, subset='Value')
13
JavaScript
1
3
1
# Specify desired date format
2
df.style.applymap(f, subset='Value').format({'Date': '{:%Y-%m-%d}'}))
3