-3

I have some dates in my json file that look like this:

2020-12-11
2020-5-1
2020-3-21

and I want to convert them to YYYY-MM-DD format. They are already in a similar format, but I want to add leading zeros for single-digit month and day numbers.

The output should look like this:

2020-12-11
2020-05-01
2020-03-21

How can I do this?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65

2 Answers2

1

The parser in datetutil can be used as follows (d1 is original date string):

from dateutil import parser
d2 = parser.parse(d1).date()

produces (datetime format which could be converted to string using strftime() if that is required):

2020-12-11
2020-05-01
2020-03-21

There is also an option (dayfirst = True) to declare day-before-month.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
user19077881
  • 3,643
  • 2
  • 3
  • 14
0

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)
mkrieger1
  • 19,194
  • 5
  • 54
  • 65