2

The dateparser library set missing parts of a date to today's values.

Example:

>>> import dateparser
>>> dateparser.parse("2015")
datetime.datetime(2015, 2, 14, 0, 0)

How to know which parts a date really contains?

(and thus which parts were set to today's values by the library)?

This is what I've come up with.

Is there a more efficient way?

date_str = input('Type a date: ')

settings = {"REQUIRE_PARTS": ["year"]}
res = dateparser.parse(date_str, settings=settings)
if res is None:
    print("Invalid Date")
    return

settings = {"REQUIRE_PARTS": ["year", "month"]}
res = dateparser.parse(date_str, settings=settings)
if res is None:
    print("Date has year only")
    return
    
settings = {"REQUIRE_PARTS": ["year", "month", "day"]}
res = dateparser.parse(date_str, settings=settings)
if res is None:
    print("Date has year and month")
    return

print("Date has year, month and day")
robertspierre
  • 3,218
  • 2
  • 31
  • 46
  • not sure but I doubt the parser keeps track of the contained parts? It would be more straight-forward if you could use explicit formats, so you could use a simple mapping of 'contains' vs. format. – FObersteiner Feb 14 '22 at 19:44
  • @FObersteiner what does it mean "use explicit formats"? – robertspierre Feb 14 '22 at 23:45
  • Sorry, that wasn't clear. By "format" I meant parsing directive. – FObersteiner Feb 15 '22 at 06:31
  • @FObersteiner doesn't that imply discarding the `dateparser` library altogether? – robertspierre Feb 15 '22 at 06:34
  • yes, I know that's kind of a blunt suggestion - totally depends on the scope of your program if it's an option or not. If dateparser has no option to return what you need, you can still look at the [source code](https://github.com/scrapinghub/dateparser) and see if that gives you any idea how to implement it? – FObersteiner Feb 15 '22 at 07:04

0 Answers0