FastAPI-HackathonIn2Mins / src /utils /date_handler.py
utkarsh134's picture
for pushin
233222c
Raw History Blame Contribute Delete
6.46 kB
import re
from datetime import datetime, timedelta, timezone
import pytz
from dateutil import parser
from typing import Optional, Tuple, Dict
from langchain_core.prompts import ChatPromptTemplate
from .core import get_llm
class DateHandler:
def __init__(self, default_timezone: str = "UTC"):
self.default_timezone = pytz.timezone(default_timezone)
self.llm = get_llm()
def parse_date_string(self, date_string: str) -> Optional[datetime]:
"""Parse date string using LLM and fallback to traditional parsing."""
try:
date_prompt = ChatPromptTemplate.from_messages([
("system", f"""
Convert the following natural language date input into a specific date in DD-MM-YYYY format.
Input: {date_string}
Rules:
- If the year is not specified, use the current year
- If month is not specified, use the next occurrence of that date
- For relative dates (tomorrow, next week, etc.), calculate from current date
- Handle phrases like "5th may", "7 march", "next monday", "tomorrow", "next week"
- If input is ambiguous, make a reasonable assumption and pick the next occurrence
- Return ONLY the date in DD-MM-YYYY format or "INVALID" if cannot be interpreted
Current date: {datetime.now().strftime('%d-%m-%Y')}
"""),
("human", "Please convert the date.")
])
response = (date_prompt | self.llm).invoke({})
llm_date = response.content.strip()
if llm_date != "INVALID":
try:
return datetime.strptime(llm_date, "%d-%m-%Y")
except ValueError:
pass
parsed_date = parser.parse(date_string, dayfirst=True, fuzzy=True)
if parsed_date.year == 1900:
current_year = datetime.now().year
parsed_date = parsed_date.replace(year=current_year)
current_date = datetime.now()
if parsed_date.date() < current_date.date():
if parsed_date.month < current_date.month:
parsed_date = parsed_date.replace(year=current_year + 1)
elif parsed_date.month == current_date.month and parsed_date.day < current_date.day:
parsed_date = parsed_date.replace(year=current_year + 1)
return parsed_date
except (ValueError, TypeError):
formats = [
"%d-%m-%Y", "%d/%m/%Y", "%m-%d-%Y", "%m/%d/%Y",
"%Y-%m-%d", "%Y/%m/%d", "%d.%m.%Y", "%m.%d.%Y",
"%d %b %Y", "%d %B %Y", "%b %d %Y", "%B %d %Y"
]
for fmt in formats:
try:
return datetime.strptime(date_string, fmt)
except ValueError:
continue
final_prompt = ChatPromptTemplate.from_messages([
("system", f"""
The user has provided this date input: '{date_string}'
Please interpret this as a future date, considering:
- Current date is {datetime.now().strftime('%d-%m-%Y')}
- If it's a relative date (tomorrow, next week), calculate accordingly
- If it's ambiguous, choose the next occurrence
- Return the date in DD-MM-YYYY format or "INVALID"
"""),
("human", "Please provide the interpreted date.")
])
final_response = (final_prompt | self.llm).invoke({})
final_date = final_response.content.strip()
if final_date != "INVALID":
try:
return datetime.strptime(final_date, "%d-%m-%Y")
except ValueError:
pass
return None
def validate_date(self, date_string: str, timezone_str: str = None) -> Tuple[bool, str, Optional[str]]:
"""Validate the parsed date."""
date_string = re.sub(r'\s+', ' ', date_string.strip())
parsed_date = self.parse_date_string(date_string)
if not parsed_date:
return False, "", "I couldn't understand that date format. Please provide a date like '7 March' or 'next Monday'."
current_date = datetime.now(timezone.utc).replace(hour=0, minute=0, second=0, microsecond=0)
if parsed_date.replace(tzinfo=timezone.utc) < current_date:
return False, "", "The date cannot be in the past. Please provide a future date."
max_future_date = current_date + timedelta(days=730)
if parsed_date.replace(tzinfo=timezone.utc) > max_future_date:
return False, "", "The date cannot be more than 2 years in the future."
formatted_date = parsed_date.strftime("%d-%m-%Y")
return True, formatted_date, None
def get_phase_dates(self, phase_start_date: str, timezone_str: str) -> Dict[str, str]:
tz = pytz.timezone(timezone_str)
phase_start = datetime.strptime(phase_start_date, "%d-%m-%Y")
phase_start = tz.localize(phase_start.replace(hour=0, minute=0, second=0, microsecond=0))
phase_end = phase_start + timedelta(days=15)
drill_registration_start = datetime.now(tz).replace(microsecond=0)
drill_registration_end = phase_start - timedelta(days=1)
return {
"phaseStartDt": phase_start.strftime("%d-%m-%Y"),
"phaseEndDt": phase_end.strftime("%d-%m-%Y"),
"drillRegistrationStartDt": drill_registration_start.strftime("%d-%m-%Y"),
"drillRegistrationEndDt": drill_registration_end.strftime("%d-%m-%Y")
}
def get_timezone_offset(self, timezone_str: str) -> str:
tz = pytz.timezone(timezone_str)
offset = tz.utcoffset(datetime.now())
hours = int(offset.total_seconds() // 3600)
minutes = int((offset.total_seconds() % 3600) // 60)
return f"{'+' if hours >= 0 else '-'}{abs(hours):02d}:{minutes:02d}"