如果有人插入一個不作為日期存在的字串“2021-11-31”。如何使用 python 更正日期,如“2021-11-30”(一個月的最后一天)或“2021-12-01”(第一天)?
輸入日期可以是 '2021-02-34' 或 '2021-12-35' 或許多錯誤的輸入。我想將其設為本月的最后一天或下個月的第一天。
重點是
- 程式應該知道日期是錯誤的還是正確的
- 然后更正日期
謝謝!
uj5u.com熱心網友回復:
正如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'
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/409571.html
標籤:
