简体   繁体   中英

How to extract date value from a Dataframe object field

I have read a json file and store it in a dataframe.

When I execute

df1.dtypes

I obtain tha the field storing the date is unplug_hourTime object

If I show the forst record using:

df1.unplug_hourTime.head(1)

I obtain:

0    {'$date': '2017-04-01T01:00:00.000+0200'}
Name: unplug_hourTime, dtype: object

I'm not sure how can I extract the date from this structure

I would like to have a variable storing 01/04/2017

I have also tried:

df1['Dia'] = pd.to_datetime(df1.unplug_hourTime)

but error is retrieved:

TypeError: <class 'dict'> is not convertible to datetime

看起来你需要:

df1['Dia'] = pd.to_datetime(df1.unplug_hourTime.apply(lambda x: x['$date'])).dt.date

You need to expand your dict into columns like so:

df = df.join(pd.DataFrame(df.pop("unplug_hourTime").tolist()))

This will result in this being added to your DataFrame:

                          $date
0  2017-04-01T01:00:00.000+0200

Then make the resultant Series a datetime:

df['Dia'] = pd.to_datetime(df['$date'])

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