Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent Pandas to_json() from adding time component to date object

I have a dataframe of that contains some date objects. I need to convert to a json for use in JavaScript, which requires YYYY-MM-DD, but to_json() keeps adding a time component. I've seen a number of answers that convert to a string first, but this is part of a loop of about 15 queries each with many columns (simplified it for the SO question) and I don't want to hardcode each column conversion as there are a lot.

import pandas as pd
from datetime import date
df = pd.DataFrame(data=[[date(year=2018, month=1, day=1)]])    
print df.to_json(orient='records', date_format='iso', date_unit='s')

Output:

[{"0":"2018-01-01T00:00:00Z"}]

Desired Output:

[{"0":"2018-01-01"}]
like image 393
user2242044 Avatar asked Dec 23 '22 10:12

user2242044


1 Answers

Pandas does not currently have the feature. There is an open issue about this, you should subscribe to the issue in case more options for the date_format argument are added in a future release (which seems like a reasonable feature request):

No way with to_json to write only date out of datetime #16492

Manually converting the relevant columns to string before dumping out json is likely the best option.

like image 89
wim Avatar answered Dec 26 '22 00:12

wim