friendlydateparser


Namefriendlydateparser JSON
Version 0.2.3 PyPI version JSON
download
home_pageNone
SummaryA flexible date parsing library that can handle complex natural language expressions, making date manipulation easy and intuitive.
upload_time2024-10-18 17:17:41
maintainerNone
docs_urlNone
authorNone
requires_pythonNone
licenseNone
keywords date parsing natural language calendar flexible dates utility date parser
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # friendlydateparser

This Python module provides methods for parsing text into date, and
datetime objects.

For instance, it can parse expressions like:

    tuesday, october 15, 2024 14:45 Europe/Paris
    2 days before the last day of next month
    1h15m after next sunday at midnight CEST
    the second monday of 2012

The aim is to be able to accept expressions witch, even if complex,
express date references which are common in everyday life.

## API

### `parse_date(text, now=None, month_first=True)`

Parses date information from a given string and returns a date
object. The function can handle different formats including relative
date descriptions (e.g., "next month", "last Friday") or explicit
dates (e.g., "10/3/2017", "15th of July").

- **Parameters**:
  - `text` (str): The text containing date information to be parsed.
  - `now` (datetime.date or datetime.datetime, optional): The
      reference date to use for relative expressions. Defaults to the
      current date if not specified.
  - `month_first` (bool, optional): Indicates whether the month
      appears first in numerical dates (e.g., `10/3` is treated as
      October 3rd if `month_first=True`). Defaults to `True`.

- **Returns**: A `datetime.date` object.

- **Example**:
  ```python
  date_obj = parse_date("the first of next month")
  # Assuming today is 2023-10-10, returns: datetime.date(2023, 11, 1)
  ```

### `parse_datetime(text, now=None, month_first=True, default_tz=None)`

Parses both date and time information from a given string and returns
a datetime object. The function handles a wide range of date and time
formats, including explicit and relative formats.

- **Parameters**:
  - `text` (str): The text containing datetime information to be parsed.
  - `now` (datetime.date or datetime.datetime, optional): The
      reference date to use for relative expressions. Defaults to the
      current date and time if not specified.
  - `month_first` (bool, optional): Indicates whether the month
      appears first in numerical dates (e.g., `10/3` is treated as
      October 3rd if `month_first=True`). Defaults to `True`.
  - `default_tz`: default timezone when the given string doesn't
    specify one. Defaults to None which causes the function to return a
    [naive](https://docs.python.org/3/library/datetime.html#aware-and-naive-objects)
    datetime object when a TZ does not appear explicitly in the given
    text.

- **Returns**: A `datetime.datetime` object.

- **Example**:
  ```python
  datetime_obj = parse_datetime("january 1, 2017 at 14:30")
  # Returns: datetime.datetime(2017, 1, 1, 14, 30)
  ```


## Supported Formats

The module can parse a wide variety of date and time formats, such as:

- **Explicit Dates**: Formats such as `3-october-2017`, `10/3/2017`,
  `2017/12/3`, `march 15, 2017`, `15/july/2023` are accepted, with the
  ability to handle both `mm/dd/yyyy` and `dd/mm/yyyy` formats based
  on the `month_first` parameter.

- **Incomplete dates**: `1 october`, `10/3`, `feb 2020`, `2024`,
  `nov`. The current year is used to fill in missing information on
  the right, while missing values on the left are filled with "ones"
  or "zeros" as appropriate. For instance, `feb 2020` becomes the 1st
  of February of 2020 at 00:00:00, `october` becomes the 1st of
  October of the current year at 00:00:00.

  Note that very ambiguous expressions like `9` are just rejected.

- **Relative Dates**: `the first of next month`, `next week`, `the day
  after tomorrow`, `october 1 last year`.

- **Relative Weekdays**: Phrases like `monday next week`, `last
  monday`, `second sunday of 2023`, `last friday of october`.

- **Year and month week numbers**: `wed week 20 2018`, `week 2 october
  2017`, `last week october`.

- **Time and Timezones**: `today at 12pm`, `last monday 12h40m`,
  `10/2/2022 40:30:12.1 CEST`, `tomorrow at midnight Europe/Paris`.

- **Deltas (before and after)**: `3 weeks before yesterday`, `1d 4h
  after next monday at noon`, `1 month ago`. Time units can be
  abbreviated, for instance, both `days`, `day`, `ds` and `d` are
  accepted as days. On the other hand months can only be given as
  `month` or `months` as `m` and `ms` mean minutes.

  Negative numbers are also accepted: `3 weeks -1 day before today`.

- **Relative references (by)**: in some cases it is useful to
  reference some relative date from another date. For instance, a
  common case is when you want to express an idea like "the last
  Monday including today if today is Monday". We can express that with
  by as `last monday by tomorrow`. Other examples are `this month by
  sunday`, `monday by the first of next month`.

- [**ISO8601**](https://en.wikipedia.org/wiki/ISO_8601):
  `2024-12-31T13:01+02:00`, `2024-W01-8T10:12Z`, `2008-365`.

And some extra considerations:

- The only inflexible rule when parsing is the order of the
  components, which must follow *(delta, date, time, timezone)*.

- Besides that, the module tries to parse anything which makes sense
  without being ambiguous.

- Common particles such as `the`, `of`, commas, dashes,
  slashes, etc. can be included when they are common but also usually
  excluded. For instance, `october the second of 2015`, `october the
  second, 2015`, `october 2nd 2015` are all parsed correctly.

- Space can be included freely everywhere except:
  - Between the digits of a number.
  - In ordinal numbers composed by several words (dashes must be
    used to join them as in `twenty-third`).
  - In timezone names (`Europe/Paris`).

  For instance, valid expressions are `1d-1h before october/23`, `1
  d - 1 h before october / 23`.

  On the other hand, space is required between consecutive words. For
  instance, `fridaynextweek` is not a valid expression.

- Abbreviations for weekdays, month names and units are accepted as
  long as they are unambiguous.

- Ordinals can be written as numbers with the appropriate suffix (1st,
  25th, etc.). Ordinals from 1st to 99th can also be written as words.


**Note: If you think a new format should be supported, just ask for
it!**

## Error Handling

- If the input text is incomplete or not recognizable as a valid
  date/time, a `ValueError` may be raised.

## Example Usage

```python
from friendlydateparser import parse_date, parse_datetime

# Parsing a date
date_obj = parse_date("the last day of next jan")
# Returns: datetime.date(2024, 1, 31)

# Parsing a datetime
datetime_obj = parse_datetime("march 15, 2017 11:59 PM")
# Returns: datetime.datetime(2017, 3, 15, 23, 59)
```

## See Also

- [`datetime`](https://docs.python.org/3/library/datetime.html): For
  working with date and time objects in Python.

- [`time`](https://docs.python.org/3/library/time.html): Provides
  various time-related functions, such as working with timestamps or
  sleep functions. This can be useful in combination with date and
  time parsing.

- [`dateutil.relativedelta`](https://dateutil.readthedocs.io/en/stable/relativedelta.html):
  For relative date calculations, like adding or subtracting months or
  years.

- [`calendar`](https://docs.python.org/3/library/calendar.html): For
  calendar-related functions, such as determining leap years or
  getting the number of days in a month.

- [`pytz`](https://pypi.org/project/pytz/): For handling time zones in
  Python. It can be useful when parsing dates and times that involve
  different time zones or when converting between local times and UTC.

- [`pendulum`](https://pendulum.eustace.io/): A library that provides
  easy-to-use functions for parsing, formatting, and manipulating
  dates and times, with a focus on improved datetime management and
  natural language parsing.

- [`dateparser`](https://dateparser.readthedocs.io/en/latest/): A
  library similar to this module, which parses natural language
  dates, even supporting multiple languages.

- [`Arrow`](https://arrow.readthedocs.io/en/latest/): A `datetime`
  alternative with a focus on usability. The
  [`dehumanize`](https://arrow.readthedocs.io/en/latest/guide.html#dehumanize)
  feature allows one to parse time deltas expressed in natural
  language.

## License

Copyright (c) 2024 Salvador Fandiño García

This project is licensed under the MIT License. See the `LICENSE` file for more details.

            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "friendlydateparser",
    "maintainer": null,
    "docs_url": null,
    "requires_python": null,
    "maintainer_email": null,
    "keywords": "date parsing, natural language, calendar, flexible dates, utility, date, parser",
    "author": null,
    "author_email": "Salvador Fandi\u00f1o Garc\u00eda <sfandino@yahoo.com>",
    "download_url": "https://files.pythonhosted.org/packages/b4/c7/3b2d5fa128471b8d9479f6471b7452c624b8e3ac2fd023eeed35508e7e59/friendlydateparser-0.2.3.tar.gz",
    "platform": null,
    "description": "# friendlydateparser\n\nThis Python module provides methods for parsing text into date, and\ndatetime objects.\n\nFor instance, it can parse expressions like:\n\n    tuesday, october 15, 2024 14:45 Europe/Paris\n    2 days before the last day of next month\n    1h15m after next sunday at midnight CEST\n    the second monday of 2012\n\nThe aim is to be able to accept expressions witch, even if complex,\nexpress date references which are common in everyday life.\n\n## API\n\n### `parse_date(text, now=None, month_first=True)`\n\nParses date information from a given string and returns a date\nobject. The function can handle different formats including relative\ndate descriptions (e.g., \"next month\", \"last Friday\") or explicit\ndates (e.g., \"10/3/2017\", \"15th of July\").\n\n- **Parameters**:\n  - `text` (str): The text containing date information to be parsed.\n  - `now` (datetime.date or datetime.datetime, optional): The\n      reference date to use for relative expressions. Defaults to the\n      current date if not specified.\n  - `month_first` (bool, optional): Indicates whether the month\n      appears first in numerical dates (e.g., `10/3` is treated as\n      October 3rd if `month_first=True`). Defaults to `True`.\n\n- **Returns**: A `datetime.date` object.\n\n- **Example**:\n  ```python\n  date_obj = parse_date(\"the first of next month\")\n  # Assuming today is 2023-10-10, returns: datetime.date(2023, 11, 1)\n  ```\n\n### `parse_datetime(text, now=None, month_first=True, default_tz=None)`\n\nParses both date and time information from a given string and returns\na datetime object. The function handles a wide range of date and time\nformats, including explicit and relative formats.\n\n- **Parameters**:\n  - `text` (str): The text containing datetime information to be parsed.\n  - `now` (datetime.date or datetime.datetime, optional): The\n      reference date to use for relative expressions. Defaults to the\n      current date and time if not specified.\n  - `month_first` (bool, optional): Indicates whether the month\n      appears first in numerical dates (e.g., `10/3` is treated as\n      October 3rd if `month_first=True`). Defaults to `True`.\n  - `default_tz`: default timezone when the given string doesn't\n    specify one. Defaults to None which causes the function to return a\n    [naive](https://docs.python.org/3/library/datetime.html#aware-and-naive-objects)\n    datetime object when a TZ does not appear explicitly in the given\n    text.\n\n- **Returns**: A `datetime.datetime` object.\n\n- **Example**:\n  ```python\n  datetime_obj = parse_datetime(\"january 1, 2017 at 14:30\")\n  # Returns: datetime.datetime(2017, 1, 1, 14, 30)\n  ```\n\n\n## Supported Formats\n\nThe module can parse a wide variety of date and time formats, such as:\n\n- **Explicit Dates**: Formats such as `3-october-2017`, `10/3/2017`,\n  `2017/12/3`, `march 15, 2017`, `15/july/2023` are accepted, with the\n  ability to handle both `mm/dd/yyyy` and `dd/mm/yyyy` formats based\n  on the `month_first` parameter.\n\n- **Incomplete dates**: `1 october`, `10/3`, `feb 2020`, `2024`,\n  `nov`. The current year is used to fill in missing information on\n  the right, while missing values on the left are filled with \"ones\"\n  or \"zeros\" as appropriate. For instance, `feb 2020` becomes the 1st\n  of February of 2020 at 00:00:00, `october` becomes the 1st of\n  October of the current year at 00:00:00.\n\n  Note that very ambiguous expressions like `9` are just rejected.\n\n- **Relative Dates**: `the first of next month`, `next week`, `the day\n  after tomorrow`, `october 1 last year`.\n\n- **Relative Weekdays**: Phrases like `monday next week`, `last\n  monday`, `second sunday of 2023`, `last friday of october`.\n\n- **Year and month week numbers**: `wed week 20 2018`, `week 2 october\n  2017`, `last week october`.\n\n- **Time and Timezones**: `today at 12pm`, `last monday 12h40m`,\n  `10/2/2022 40:30:12.1 CEST`, `tomorrow at midnight Europe/Paris`.\n\n- **Deltas (before and after)**: `3 weeks before yesterday`, `1d 4h\n  after next monday at noon`, `1 month ago`. Time units can be\n  abbreviated, for instance, both `days`, `day`, `ds` and `d` are\n  accepted as days. On the other hand months can only be given as\n  `month` or `months` as `m` and `ms` mean minutes.\n\n  Negative numbers are also accepted: `3 weeks -1 day before today`.\n\n- **Relative references (by)**: in some cases it is useful to\n  reference some relative date from another date. For instance, a\n  common case is when you want to express an idea like \"the last\n  Monday including today if today is Monday\". We can express that with\n  by as `last monday by tomorrow`. Other examples are `this month by\n  sunday`, `monday by the first of next month`.\n\n- [**ISO8601**](https://en.wikipedia.org/wiki/ISO_8601):\n  `2024-12-31T13:01+02:00`, `2024-W01-8T10:12Z`, `2008-365`.\n\nAnd some extra considerations:\n\n- The only inflexible rule when parsing is the order of the\n  components, which must follow *(delta, date, time, timezone)*.\n\n- Besides that, the module tries to parse anything which makes sense\n  without being ambiguous.\n\n- Common particles such as `the`, `of`, commas, dashes,\n  slashes, etc. can be included when they are common but also usually\n  excluded. For instance, `october the second of 2015`, `october the\n  second, 2015`, `october 2nd 2015` are all parsed correctly.\n\n- Space can be included freely everywhere except:\n  - Between the digits of a number.\n  - In ordinal numbers composed by several words (dashes must be\n    used to join them as in `twenty-third`).\n  - In timezone names (`Europe/Paris`).\n\n  For instance, valid expressions are `1d-1h before october/23`, `1\n  d - 1 h before october / 23`.\n\n  On the other hand, space is required between consecutive words. For\n  instance, `fridaynextweek` is not a valid expression.\n\n- Abbreviations for weekdays, month names and units are accepted as\n  long as they are unambiguous.\n\n- Ordinals can be written as numbers with the appropriate suffix (1st,\n  25th, etc.). Ordinals from 1st to 99th can also be written as words.\n\n\n**Note: If you think a new format should be supported, just ask for\nit!**\n\n## Error Handling\n\n- If the input text is incomplete or not recognizable as a valid\n  date/time, a `ValueError` may be raised.\n\n## Example Usage\n\n```python\nfrom friendlydateparser import parse_date, parse_datetime\n\n# Parsing a date\ndate_obj = parse_date(\"the last day of next jan\")\n# Returns: datetime.date(2024, 1, 31)\n\n# Parsing a datetime\ndatetime_obj = parse_datetime(\"march 15, 2017 11:59 PM\")\n# Returns: datetime.datetime(2017, 3, 15, 23, 59)\n```\n\n## See Also\n\n- [`datetime`](https://docs.python.org/3/library/datetime.html): For\n  working with date and time objects in Python.\n\n- [`time`](https://docs.python.org/3/library/time.html): Provides\n  various time-related functions, such as working with timestamps or\n  sleep functions. This can be useful in combination with date and\n  time parsing.\n\n- [`dateutil.relativedelta`](https://dateutil.readthedocs.io/en/stable/relativedelta.html):\n  For relative date calculations, like adding or subtracting months or\n  years.\n\n- [`calendar`](https://docs.python.org/3/library/calendar.html): For\n  calendar-related functions, such as determining leap years or\n  getting the number of days in a month.\n\n- [`pytz`](https://pypi.org/project/pytz/): For handling time zones in\n  Python. It can be useful when parsing dates and times that involve\n  different time zones or when converting between local times and UTC.\n\n- [`pendulum`](https://pendulum.eustace.io/): A library that provides\n  easy-to-use functions for parsing, formatting, and manipulating\n  dates and times, with a focus on improved datetime management and\n  natural language parsing.\n\n- [`dateparser`](https://dateparser.readthedocs.io/en/latest/): A\n  library similar to this module, which parses natural language\n  dates, even supporting multiple languages.\n\n- [`Arrow`](https://arrow.readthedocs.io/en/latest/): A `datetime`\n  alternative with a focus on usability. The\n  [`dehumanize`](https://arrow.readthedocs.io/en/latest/guide.html#dehumanize)\n  feature allows one to parse time deltas expressed in natural\n  language.\n\n## License\n\nCopyright (c) 2024 Salvador Fandi\u00f1o Garc\u00eda\n\nThis project is licensed under the MIT License. See the `LICENSE` file for more details.\n",
    "bugtrack_url": null,
    "license": null,
    "summary": "A flexible date parsing library that can handle complex natural language expressions, making date manipulation easy and intuitive.",
    "version": "0.2.3",
    "project_urls": {
        "Source": "https://github.com/salva/py-friendlydateparser"
    },
    "split_keywords": [
        "date parsing",
        " natural language",
        " calendar",
        " flexible dates",
        " utility",
        " date",
        " parser"
    ],
    "urls": [
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "f67c1289b62c29cf5f3a5ec0989e2c605a6b1c4a2cb16ff28a4889d2072e5f82",
                "md5": "4a2cf113a69b4f7f0869181c915a2695",
                "sha256": "a21a31d0bad72820bf73547ede2a8146a3e505203634687f5cfe2b63299edbd0"
            },
            "downloads": -1,
            "filename": "friendlydateparser-0.2.3-py2.py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "4a2cf113a69b4f7f0869181c915a2695",
            "packagetype": "bdist_wheel",
            "python_version": "py2.py3",
            "requires_python": null,
            "size": 100748,
            "upload_time": "2024-10-18T17:17:38",
            "upload_time_iso_8601": "2024-10-18T17:17:38.528104Z",
            "url": "https://files.pythonhosted.org/packages/f6/7c/1289b62c29cf5f3a5ec0989e2c605a6b1c4a2cb16ff28a4889d2072e5f82/friendlydateparser-0.2.3-py2.py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "b4c73b2d5fa128471b8d9479f6471b7452c624b8e3ac2fd023eeed35508e7e59",
                "md5": "965221426d8864ecd2b19bb7c3025ae8",
                "sha256": "278e5a516667af44939eff66efe10d3b6c1bed18f5c68add5e18f7f666e77500"
            },
            "downloads": -1,
            "filename": "friendlydateparser-0.2.3.tar.gz",
            "has_sig": false,
            "md5_digest": "965221426d8864ecd2b19bb7c3025ae8",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": null,
            "size": 107944,
            "upload_time": "2024-10-18T17:17:41",
            "upload_time_iso_8601": "2024-10-18T17:17:41.015679Z",
            "url": "https://files.pythonhosted.org/packages/b4/c7/3b2d5fa128471b8d9479f6471b7452c624b8e3ac2fd023eeed35508e7e59/friendlydateparser-0.2.3.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-10-18 17:17:41",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "salva",
    "github_project": "py-friendlydateparser",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": false,
    "lcname": "friendlydateparser"
}
        
Elapsed time: 0.42455s