python – How to convert a date string to different format

python – How to convert a date string to different format

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 cant 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)

If you can live with 01 for January instead of 1, then try…

d = datetime.datetime.strptime(2013-1-25, %Y-%m-%d)
print datetime.date.strftime(d, %m/%d/%y)

You can check the docs for other formatting directives.

python – How to convert a date string to different format

Leave a Reply

Your email address will not be published. Required fields are marked *