Home > Mobile >  Python Partial Date Parser Function
Python Partial Date Parser Function

Time:03-20

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?

CodePudding user response:

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
  • Related