Created
August 21, 2024 02:25
-
-
Save douglasmiranda/d841a42a60289953f781bfbb14aed675 to your computer and use it in GitHub Desktop.
python - extract date from string (and return the format of matching)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from dataclasses import dataclass | |
from datetime import datetime | |
# This is basically a draft | |
# it works, it's just very simplistic | |
# looks for a single occurrence; match; return | |
# The main goal it's just parse the date and have control of | |
# the format I matched. | |
# Example: read autocomplete field and trigger a search when | |
# the search term match at least the dd/mm (%d/%m) format. | |
# if format_key == "day_month": search database for day month | |
# if format_key == "day_month_year": search database for day month year | |
def extract_date(text, formats=None): | |
"""Try to parse a date from a string given a list of formats. | |
>>> extract_date("22/06") | |
>>> extract_date.<locals>.Date(day=22, month=6, year=1900, format_key='day_month') | |
>>> date = extract_date("22/06") | |
>>> date.day | |
>>> 22 | |
>>> date.month | |
>>> 6 | |
>>> date.year | |
>>> 1900 | |
>>> date.date() | |
>>> datetime.date(1900, 6, 22) | |
>>> date.format_key | |
>>> 'day_month' | |
>>> if date and date.format_key == "day_month": | |
print("filter by day and month only") | |
filter by day and month only | |
""" | |
@dataclass | |
class Date: | |
day: int | |
month: int | |
year: int = None | |
format_key: str = None | |
def date(self): | |
return datetime(self.year, self.month, self.day).date() | |
if not formats: | |
formats = {"day_month": "%d/%m", "day_month_year": "%d/%m/%Y"} | |
for key in formats.keys(): | |
try: | |
date = datetime.strptime(text.strip(), formats[key]) | |
return Date(date.day, date.month, date.year, key) | |
except ValueError: | |
pass | |
return None |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment