0

I am using pandas in python and I end up with the following table:

+---------------------+----------------------+-----------------+
|        start        |        finish        |    duration     |
+---------------------+----------------------+-----------------+
| 2013-08-12 12:00:00 | 2013-08-14 16:00:00 | 2 days 04:00:00 |
+---------------------+----------------------+-----------------+

dataframe=dataframe.to_json(orient='records',date_format='iso',double_precision=2,date_unit='s')

return jsonify(data=dataframe)

I send this over using an AJAX request as data, and on the javascript side I end up with data.duration = 1970-01-03T04:00:00Z

How can I format the data frame so that when I call data.duration I get 2 days 04:00:00?

Note that duration is calculating using:

data_frame['duration'] = data_frame['finish'] - data_frame['start']
Outshined
  • 1
  • 2
  • Maybe convert duration to a string with str() for reading in javascript, the simple approach and reached as a concensus some years ago on http://stackoverflow.com/questions/538666/python-format-timedelta-to-string. –  Aug 28 '15 at 04:49

2 Answers2

0

The problem is the duration column uses a type that is not strictly available in Javascript.

Try casting the duration column to String in Python or explicitly replacing the column or creating a new column of formatted strings. I would suspect the current dtype of that column in the pandas dataframe is a Python timedelta or similar.

After serialization to JSON and transport it looks like duration was interpreted as a JavaScript Date because 2 days and 4 hours has been transformed to 2 days and 4 hours after the epoch date of Jan 1, 1970, the "zero" of Unix time that is also the JS time standard. In Javascript Date objects are similar to DateTime in Python.

Paul
  • 26,170
  • 12
  • 85
  • 119
0

It's a bit ugly, but you can cast to the pandas string representation like this:

dataframe['duration'].apply(lambda x: str(pd.Timedelta(x)))
chrisb
  • 49,833
  • 8
  • 70
  • 70