Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for Convert Date by brownie57
def is_leap(n):
y = int(n)
if y % 400 == 0:
return 1
if y % 100 == 0:
return 0
return int(y % 4 == 0)
def valid_date(d, m, y):
if m in {"01", "03", "05", "07", "08", "10", "12"}:
return 1 <= int(d) <= 31
if m in {"04", "06", "09", "11"}:
return 1 <= int(d) <= 30
if m == "02":
return 1 <= int(d) <= 28 + is_leap(y)
return False
def convert_date(date: str) -> str:
ERROR = "Error: Invalid date."
dmy = date.split("/")
if len(dmy) != 3:
return ERROR
d, m, y = dmy
if valid_date(d, m, y):
return "-".join([y, m, d])
return ERROR
print("Example:")
print(convert_date("01/01/2023"))
# These "asserts" are used for self-checking
assert convert_date("25/12/2021") == "2021-12-25"
assert convert_date("01/01/2000") == "2000-01-01"
assert convert_date("15/06/1995") == "1995-06-15"
assert convert_date("29/02/2020") == "2020-02-29"
assert convert_date("10/10/2010") == "2010-10-10"
assert convert_date("31/05/1985") == "1985-05-31"
assert convert_date("07/08/1960") == "1960-08-07"
assert convert_date("02/09/1999") == "1999-09-02"
assert convert_date("30/04/1975") == "1975-04-30"
assert convert_date("29/02/2019") == "Error: Invalid date."
assert convert_date("30/04/1975/1") == "Error: Invalid date."
print("The mission is done! Click 'Check Solution' to earn rewards!")
Dec. 28, 2025