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
Asked
Active
Viewed 41 times
-5
-
try to parse all 3 formats using datetime and catch the exceptions. – Jean-François Fabre Apr 18 '18 at 09:15
-
@Jean-FrançoisFabre: the formats are trivially detectable by their delimiter though. – Martijn Pieters Apr 18 '18 at 09:18
-
@MitchWheat: I fail to see how that dupe applies here. There is zero parsing going on in that question or any of the answers. – Martijn Pieters Apr 18 '18 at 18:32
2 Answers
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