Reputation: 177
If someone inserts a string '2021-11-31' that doesn't exist as a date. How to correct the date like '2021-11-30'(last day of month) or '2021-12-01'(first day) with python?
The input date can be '2021-02-34' or '2021-12-35' or many wrong input.. and I want to make it a last day of month or a first day of next month.
The point is
Thank you!
Upvotes: 0
Views: 157
Reputation: 297
As mentioned by Yunnosch in previous comments, you can't be sure the date is "correct".
I guess you're assuming the date format to be YYYY-MM-DD
and want to constrain DD
to be within 1-31 (or 1-28, 1-29, 1-30 depending on the month).
Here is a simple function that does this :
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
Use it like that :
>>> 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'
Upvotes: 2