假设我们有一个格式为“Day Month Year”的日期字符串,其中日期类似于 [1st, 2nd, ..., 30th, 31st],月份是 [Jan, Feb, ... Nov, Dec] 格式和year 是 1900 到 2100 范围内的四位数数值,我们必须将此日期转换为“YYYY-MM-DD”格式。
因此,如果输入类似于 date = "23rd Jan 2021",那么输出将是 2021-01-23
让我们看看以下实现以获得更好的理解 -
def solve(date): Months=["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] string=date.split() year = string[2] day = string[0][:-2] if len(day)<2: day="0"+day month = str(Months.index(string[1])+1) if len(month)<2: month="0"+month return "{0}-{1}-{2}".format(year, month, day) date = "23rd Jan 2021" print(solve(date))
"23rd Jan 2021"输出结果
2021-01-23