TypeError: <class 'cftime._cftime.Datetime360Day'> is not convertible to datetime

Question:

I’m aware similar questions to this have been asked, but none of the previous solutions work for me.

I have a series of dates which are formatted as:

df['time']
0          2010-01-16 00:00:00
1          2010-01-16 00:00:00
2          2010-01-16 00:00:00
3          2010-01-16 00:00:00
4          2010-01-16 00:00:00

These have a 360 day calendar.

I’m wanting to convert them to a datetime object in pandas with:

df['time']=pd.to_datetime(df['time'], format='%Y-%m-%d'

I’m only interested in the date, not the time. However, because the calendar is 360 days I just get the error message
"TypeError: <class 'cftime._cftime.Datetime360Day'> is not convertible to datetime". I’m aware that cftime does not support the 360 day calendar, so I need a manual way of extracting the date, but every method I’ve tried to do this fails on the basis that the input is a "cftme._cftime.Datetime360Day" object and not a string.

Does anyone have any workarounds for this?

Asked By: phytofan

||

Answers:

What about the following solution?

You can use apply function.

Then, if the type of the column is not datetime, you can change it

from datetime import datetime as dt

def convert_to_dt(x):
    return dt.strptime(str(x), '%Y-%m-%d %H:%M:%S')

df['time'] = df.time.apply(convert_to_dt)
Answered By: PicxyB
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.