简体   繁体   中英

Date Formatting Pandas - Python

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']

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.

这有点丑陋,但是您可以像这样转换为pandas字符串表示形式:

dataframe['duration'].apply(lambda x: str(pd.Timedelta(x)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM