Skip to content

How to parse when month or day is missing? #424

Closed

Description

@pengyu

The following only says the year is 2017. But dateparser will fill in the month and day as the today. I don't think that this is the most appropriate behavior.

>>> from dateparser import parse
>>> print(parse('2017'))
2017-06-18 00:00:00

Is there a way to just print the most specific information like the following?

  • '2017' -> '2017'
  • '2017 Jan' -> '2017-01'

Activity

  1. kamilnematli commented on Jul 8, 2019

    @kamilnematli
    Contributor

    It is actually not today's date but the reference date. As default the reference date is the current date. One workaround can be to set the reference date to 1st of January. By this, if the day is missing it will set it to 1st day of month and if day and month missing it will set it to 1st of Jan. But please be careful because there are some other date phrases that are parsed considering reference date, like yesterday.

  2. noviluni commented on May 14, 2020

    @noviluni
    Contributor

    Hi @pengyu, the parse method returns a datetime object (not a str) and you can format the result by using strftime.

    In your examples:

    • print(parse('2017').strftime('%Y'))
    • print(parse('2017 Jan').strftime('%Y-%m'))

    Check this to know how to use it: https://strftime.org/

    As it doesn't exist a datetime object without the day or without the month, it's not technically possible to return less information, so gaps are automatically filled with the reference date (as @kamilnematli explained).

    If you want to automatically (programmatically) format the dates according to the parsed content now it's not possible and I don't think it will be possible in the future, as the result of parse will be always a datetime. However, it could be possible to add another function to get information about what has been parsed (like the info we use when setting STRICT_PARSING=True), but this has only sense in certain circumstances, as when parsing "2017 Jan", but it hasn't sense when parsing strings like "yesterday".

  3. noviluni commented on Jun 26, 2020

    @noviluni
    Contributor

    Just added a PR trying to find a solution for this: #729

    Please, if you have any feedback let me know.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions