Python Partial Date Parser Function

391 views Asked by At

I have a function that takes in a string and converts the value to date through a parser.

Lets call it date converter:

def date_converter(x):
    return dateparser.parse(x).dt.date

So if it took in '2021 jan 21' as a string it would become 2021-01-21

However the function now needs to take in a partial date '21jan' and convert it to 2021-01-what ever the date is. The day does not matter.

How can i set up a parser to know it will be receiving a year and a month assuming all it is going to receive is a string?

2

There are 2 answers

3
constantstranger On BEST ANSWER

Here's what I think you're looking for:

s = "21jan"
import datetime
d = datetime.datetime.strptime(s, "%y%b").date()
print(d)

Output:

2021-01-01
0
Tim Richardson On

this solution uses the very flexible and forgiving datetime.parser module. This is quite slow, but very useful.

import datetime
from dateutil import parser



def date_convertor(x:str)->datetime.date:
    #assuming the day of the month is never present
    date_string_to_parse = x + "01"
    converted_dt = parser.parse(date_string_to_parse,yearfirst=True)
    return converted_dt.date()