Fix Python – How to convert a date string to different format [duplicate]

Question

Asked By – Chamith Malinda

I need to convert date string “2013-1-25” to string “1/25/13” in python.
I looked at the datetime.strptime but still can’t find a way for this.

Now we will see solution for issue: How to convert a date string to different format [duplicate]


Answer

I assume I have import datetime before running each of the lines of code below

datetime.datetime.strptime("2013-1-25", '%Y-%m-%d').strftime('%m/%d/%y')

prints "01/25/13".

If you can’t live with the leading zero, try this:

dt = datetime.datetime.strptime("2013-1-25", '%Y-%m-%d')
print '{0}/{1}/{2:02}'.format(dt.month, dt.day, dt.year % 100)

This prints "1/25/13".

EDIT: This may not work on every platform:

datetime.datetime.strptime("2013-1-25", '%Y-%m-%d').strftime('%m/%d/%y')

This question is answered By – eumiro

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0