Chandu
Chandu

Reputation: 2129

Convert strings to date format

I have a dataframe with a column of strings indicating month and year (MM-YY) but i need it to be like YYYY,MM,DD e.g 2015,10,01

for i in df['End Date (MM-YY)']:
    print i

    Mar-16
    Nov-16
    Jan-16
    Jan-16

    print type(i)

    <type 'str'>
    <type 'str'>
    <type 'str'>
    <type 'str'>

Upvotes: 1

Views: 361

Answers (3)

Mike Lape
Mike Lape

Reputation: 1

If you are trying to do what I think you are...

Use the datetime.datetime.strptime method! It's a wonderful way to specify the format you expect dates to show up in a string, and it returns a nice datetime obj for you to do with what you will.

You can even turn it back into a differently formatted string with datetime.datetime.strftime!

Upvotes: 0

jezrael
jezrael

Reputation: 862641

I think you can use to_datetime with parameter format:

df = pd.DataFrame({'End Date (MM-YY)': {0: 'Mar-16', 
                                        1: 'Nov-16', 
                                        2: 'Jan-16', 
                                        3: 'Jan-16'}})
print df
  End Date (MM-YY)
0           Mar-16
1           Nov-16
2           Jan-16
3           Jan-16

print pd.to_datetime(df['End Date (MM-YY)'], format='%b-%y')
0   2016-03-01
1   2016-11-01
2   2016-01-01
3   2016-01-01
Name: End Date (MM-YY), dtype: datetime64[ns]

df['date'] = pd.to_datetime(df['End Date (MM-YY)'], format='%b-%y')

If you need convert date column to the last day of month, use MonthEnd:

df['date-end-month'] = df['date'] + pd.offsets.MonthEnd()
print df

  End Date (MM-YY)       date date-end-month
0           Mar-16 2016-03-01     2016-03-31
1           Nov-16 2016-11-01     2016-11-30
2           Jan-16 2016-01-01     2016-01-31
3           Jan-16 2016-01-01     2016-01-31

Upvotes: 1

Annapoornima Koppad
Annapoornima Koppad

Reputation: 1466

You can use Lambda and Map functions, the references for which are here 1 and 2 combined with to_datetime with parameter format.

Can you provide more information on the data that you are using. I can refine my answer further based on that part of information. Thanks!

Upvotes: 0

Related Questions