Apollo Apollo - 2 months ago 11
Python Question

Convert timestring into date - Python

If I have the following timestring:


How would I convert this into the date
May 5, 2015
in Python? So far I've tried:

from datetime import datetime
sd = datetime.strptime('20150504', '%Y%M%d')

But this outputs:

2015-01-04 00:05:00


The capital M denotes minute not month. Use the lowercase m and then call the strftime method to refactor the format:

>>> datetime.strptime('20150504', '%Y%m%d').strftime('%b %d, %Y')
'May 04, 2015'

You can remove the zero padding from the month by using the -d directive in place of d:

%-d Day of the month as a decimal number. (Platform specific)

For longer month names, you can use the directive %B in place of %b to get the full month name.