0

I want to parse a date string and manipulate the year, month, date in cases where I either get '00' for month or day or in cases where I get a day beyond the possible days of that year/month. Given a '2012-00-00' or a '2020-02-31', I get a ValueError. What I want, is to catch the error and then turn the former into '2012-01-01' and the latter to '2020-02-29'. No results on Google so far.

Clarification: I use try/except/ValueError... what I want is to parse out the year, month, day and fix the day or month when they are having a ValueError... without having to code the parsing and regular expressions myself... which defeats the purpose of using a library to begin with.

# Try dateutjil
blah = dateutil.parser.parse(date_string, fuzzy=True)
print(blah)

# Try datetime
date_object = datetime.strptime(date_string, date_format)
return_date_string = date_object.date().strftime('%Y-%m-%d')
DizzyDawg
  • 1
  • 1
  • 1
    Does this answer your question? [Python 2.7 try and except ValueError](https://stackoverflow.com/questions/5025399/python-2-7-try-and-except-valueerror) – sushanth Jun 04 '20 at 17:57

1 Answers1

0

I know you don't want to parse the date yourself but I think you will probably have to. One option would be to split the incoming string into its component year, month and day parts and check them against valid values, adjusting as required. You can then create a date from that and call strftime to get a valid date string:

from datetime import datetime, date
import calendar

def parse_date(dt):
    [y, m, d] = map(int, dt.split('-'))
    # optional error checking on y
    # ...
    # check month
    m = 1 if m == 0 else 12 if m > 12 else m
    # check day
    last = calendar.monthrange(y, m)[-1]
    d = 1 if d == 0 else last if d > last else d
    return date(y, m, d).strftime('%Y-%m-%d')


print(parse_date('2012-00-00'))
print(parse_date('2020-02-31'))

Output:

2012-01-01
2020-02-29
Nick
  • 138,499
  • 22
  • 57
  • 95