-5

How would I get a function to take the date in terms of YYYY-MM-DD, YYYY/MM/DD and DD.MM.YYYY and return YYYY-MM-DD? I’ve tried a few ways which would work for one of the formats but then not the other

Gamer
  • 1
  • 1

2 Answers2

0

It is difficult to try all with one line, So you can try like this :

from datetime import datetime
dt = "30-4-1994"
for fmt in ('%Y-%m-%d', '%Y/%m/%d', '%d.%m.%Y'):
    try:
        example_time =  datetime.strptime(dt, fmt).date()
        print(example_time)
    except ValueError:
        continue

O/P will be in YYYY-MM-DD format like this :

1994-04-30
Vikas Periyadath
  • 3,088
  • 1
  • 21
  • 33
0

Just switch on the delimiter string in your input to pick a suitable datetime.strptime() format:

from datetime import datetime

FORMATS = {'-': '%Y-%m-%d', '/': '%Y/%m/%d', '.': '%d.%m.%Y'}
def convertdate(ds, outputformat='%Y-%m-%d', _formats=FORMATS):
    for delim, format in _formats.items():
        if delim in ds:
            return datetime.strptime(ds, format).strftime(outputformat)

Demo:

>>> convertdate('2012-03-12')
'2012-03-12'
>>> convertdate('2012/03/12')
'2012-03-12'
>>> convertdate('12.03.2012')
'2012-03-12'
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343