The usual way to reformat a date string is to use the datetime
module (see How to convert a date string to different format).
Here you want to use the format codes (quoting the descriptions from the documentation)
%Y
- Year with century as a decimal number.
%m
- Month as a zero-padded decimal number.
%d
- Day of the month as a zero-padded decimal number.
According to the footnote (9) in the documentation of datetime
, %m
and %d
accept month and day numbers without leading zeros when used with strptime
, but will output zero-padded numbers when used with strftime
.
So you can use the same format string %Y-%m-%d
to do a round-trip with strptime
and strftime
to add the zero-padding.
from datetime import datetime
def reformat(date_str):
fmt = '%Y-%m-%d'
return datetime.strptime(date_str, fmt).strftime(fmt)