0

convert MMM yyyy into yyyy-mm in python3

so for a panda dateframe with dd mmm yyyy like

01 Feb 1985

It can be converted into yyyy-mm-dd with the following code

df[["date"]] = df[["date"]].apply(pd.to_datetime)

output:

1985-02-01

But if i have MMM yyyy like

Feb 1985

and I would like to output as

1985-02

How can I do that?

df[["date"]] = df[["date"]].apply(pd.to_datetime)

will output the date which i don't want

1985-02-01 

Any thoughts?

Thanks for some comments. I just realized that there are NaN in the dataframe that I cannot drop. So I am trying to do a function to ingore NaN but the result is still like 1985-02-01. Any thoughts?

def date2int(df):

    for index, row in df.iteritems():

        try:
            t1=row.strftime('%b-%Y')
            return t1
        except ValueError:
            return None

date2int(df["date2"])
Chubaka
  • 2,933
  • 7
  • 43
  • 58
  • a similar question was answered here: https://stackoverflow.com/questions/25146121/extracting-just-month-and-year-separately-from-pandas-datetime-column – emiljoj Feb 25 '20 at 21:34
  • `1985-02-01` is the pandas `__repr__` for the data type (`datetime`). You can force a different format like `df['date'].map('{:%Y-%m}'.format)` – DOOM Feb 25 '20 at 21:37
  • I edited my post with the comment above. Still cannot resolve it after 1 hour of attempt. @DOOM: the solution you kindly provided will hit the error message: ```AttributeError: 'NaTType' object has no attribute 'map'```. ``` def date2int(df): for index, row in df.iteritems(): print(row) if row is None: return None else: t1=row.map('{:%Y-%m}'.format) print(date2int(df["date2"])) ``` – Chubaka Feb 25 '20 at 23:14

1 Answers1

0

ok after an hour and half effort:

df['date2'] = df['date2'].loc[df['date2'].notnull()].apply(lambda x: x.strftime('%Y-%m'))

return the desired output and avoid NaN to throw error messages

1985-02
Chubaka
  • 2,933
  • 7
  • 43
  • 58