0

I'd like to convert this list of strings of various unknown date formats to a python datetime object. For example:

strings = ["today", "tomorrow", "next Friday", "June 4th", "04/11/2022"]

convert_to_date(strings[0])
>>> 2022-04-08

convert_to_date(strings[1])
>>> 2022-04-09

convert_to_date(strings[3])
>>> 2022-04-15

I tried several methods but found that:

  • dateutil.parser only works for dates like 04/11/2022
  • time.strptime and arrow both require me to specify the format
  • regex would be too complicated and may not work for all scenarios

Is there any library or function that would allow me to do something like this?

  • Does this answer your question? [Convert "unknown format" strings to datetime objects?](https://stackoverflow.com/questions/13258554/convert-unknown-format-strings-to-datetime-objects) – Omar Tammam Apr 10 '22 at 14:28

1 Answers1

0

I don't think there is any library or function to do the thing you're asking to.

Here's some sample code to help you out (in python)

import datetime

def crazyDateToStandard(crazyDate):
    today = datetime.date.today()
    if(crazyDate=='today'):
        print("Today's date:",today)
    elif(crazyDate=='tomorrow'):
        tomorrow = today + datetime.timedelta(days=1)
        print("Tommorow's date:",tomorrow)

#shows today's date
crazyDateToStandard('today')
#shows tommorow's date
crazyDateToStandard('tomorrow')

I have implemented a basic functionality here, its now up to you to figure this code out and ask yourself.

  • What does each of these functions do?
  • How i can use it?
  • How can i implement it to my algorithm?
moken
  • 3,227
  • 8
  • 13
  • 23
theWizard
  • 1
  • 1
  • 1
    I can't tell if this answer is a "troll" answer or not. But there's already a library called [date-util](https://dateutil.readthedocs.io/en/stable/) which has a parser module which can achieve what the question is asking. – Rehan Rajput Jul 13 '23 at 14:19