用python3更正约会中的拼写错误



如果有人插入一个不作为日期存在的字符串"2021-11-31"。如何用python更正"2021-11-30"(月的最后一天(或"2021-12-01"(第一天(之类的日期?

输入日期可以是"2021-02-34"或"2021-12-35"或许多错误输入。。我想把它定为一个月的最后一天或下个月的第一天。

重点是

  1. 程序应该知道日期是错误的或正确的
  2. 然后更正日期

谢谢!

正如Yunnosch在之前的评论中所提到的,你不能确定日期是"正确";。

我猜您假设日期格式为YYYY-MM-DD,并希望将DD限制在1-31内(或1-28、1-29、1-30,具体取决于月份(。

这里有一个简单的函数可以做到这一点:

import calendar

def rectify_day(dt: str) -> str:
"""
Rectify the date and month of a date.
If the day part is greater than the last day of this month,
it will constrain the day to be the last day of month.
"""
year_s, month_s, day_s = dt.split("-")   # split the elements of the date
year = int(year_s)                       # convert them to integers
month = int(month_s)
day = int(day_s)
last_day_of_month = calendar.monthrange(year, month)[1] # get the last day of this month
day = min(day, last_day_of_month)        # constrain the day to max possible value
return f"{year}-{month:>02d}-{day:>02d}" # returns a formatted string

这样使用:

>>> rectify_day("2021-01-32")
'2021-01-31'
>>> rectify_day("2021-02-29")
'2021-02-28'
>>> rectify_day("2021-01-10")
'2021-01-10'
>>> rectify_day("2021-12-12")
'2021-12-12'

最新更新