0

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?

John Dahl
  • 3
  • 1
  • see https://dateparser.readthedocs.io/en/latest/settings.html#settings. it has a section on partial dates and how to handle them, including what to do when the year is missing. – Tim Richardson Mar 18 '22 at 00:22
  • @TimRichardson in this case it's the day that's missing, not the year. – Mark Ransom Mar 19 '22 at 12:13
  • Good point. If you know it is definitely missing the day, append "01" to the string and try this, using a different module, in effect like this: `from dateutil import parser parser.parse("21jan01",yearfirst=True)` after that you will have a datetime and you can do with it whatever you want. – Tim Richardson Mar 20 '22 at 05:59

2 Answers2

0

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
constantstranger
  • 9,176
  • 2
  • 5
  • 19
  • Would this work as well if I passed in jan21? A user with no programing knowledge would enter in a date so it would have to take in both. – John Dahl Mar 19 '22 at 00:47
  • It can be made to work with jan21 as well. For example, this would cover that case: `try: d = strptime(s,"%y%b").date; except: d = strptime(s, "%b%y")`. Hopefully the above answer to your original question points you in the direction of how to answer most variations. The documentation for `datetime.strptime()` and related questions is here: . Happy to help if I can with any additional follow-on clarifications around your question. – constantstranger Mar 19 '22 at 01:46
  • @John Dahl Do you need any more help with your question? If not, and you are satisfied with this answer, feel free to mark it as "accepted". – constantstranger Mar 19 '22 at 18:15
0

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()
Tim Richardson
  • 6,608
  • 6
  • 44
  • 71