Convert MMM YY to Date time in python

Viewed 3627

I have a column of dates in MMM YY format and would like to change to datetime

Is it possible to convert Dec 2016 for example to a date in python? So the output would be 01/12/2016?

2 Answers

This should do what you asked for:

import datetime

d = datetime.datetime.strptime('Dec 2016','%b %Y').strftime('%d/%m/%Y')

print(d)

Result:

01/12/2016

Python has built-in module datetime that has strtime and strptime functions that can convert formatted strings from/to datetime objects. Here is the example of these functions usage:

from datetime import datetime

s = 'Dec 2016'

print(datetime.strftime(datetime.strptime(s, '%b %Y'), '%d/%m/%Y'))

Output:

'01/12/2016'


According to strftime() and strptime() format codes:

  • %b is Month as locale’s abbreviated name.
  • %d, %m, %Y is day-month-year in a zero-padded format

Note that %b depends on locale! If you have non-US locale, names will be differ!

%b - Month as locale’s abbreviated name.

Jan, Feb, …, Dec (en_US);

Jan, Feb, …, Dez (de_DE)

Related