Spaces:
Sleeping
Sleeping
File size: 2,952 Bytes
df37f6e |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 |
from datetime import datetime
def extra_time_dialogflow(time: dict) -> list | str | None:
"""
Format time dictionary to string.
Nếu time có ambiguous (past, future) => trả về list [past_time_str, future_time_str]
Nếu time rõ ràng => trả về string "HH:mm"
"""
def is_time_ambiguous(time_obj: dict) -> bool:
return any(time_obj.get(key) for key in ["past", "future", "partial"])
if time is None:
return None
if is_time_ambiguous(time):
past_time = time.get("past", {})
future_time = time.get("future", {})
past_hours = int(past_time.get("hours", 0))
past_minutes = int(past_time.get("minutes", 0))
past_time_str = f"{past_hours:02d}:{past_minutes:02d}"
future_hours = int(future_time.get("hours", 0))
future_minutes = int(future_time.get("minutes", 0))
future_time_str = f"{future_hours:02d}:{future_minutes:02d}"
return sorted([past_time_str, future_time_str])
else:
hours = int(time["hours"])
minutes = int(time["minutes"])
return f"{hours:02d}:{minutes:02d}"
def get_time_range(from_time: datetime = None, to_time: datetime = None):
"""
Chuyển thời gian từ Dialogflow về dạng timestap cho search trip.
Thông thường sẽ truyền vào ngày và trả về thời gian đầu và cuối ngày
Args:
from_time (datetime): Thời gian bắt đầu
to_time (datetime): Thời gian kết thúc
Returns:
from_time (timestamp)
to_time (timestamp)
"""
if to_time is None and from_time is not None:
to_time = from_time.replace(hour=23, minute=59, second=59)
if from_time is None:
today = datetime.today().date()
from_time = datetime.combine(today, datetime.min.time())
to_time = datetime.combine(today, datetime.max.time()) - timedelta(
microseconds=1
)
return int(from_time.timestamp()) * 1000, int(to_time.timestamp()) * 1000
def to_datetime_from_Dialogflow(raw_date: dict) -> datetime:
"""
Convert raw date from Dialogflow to datetime object.
"""
if not raw_date:
return None
year = int(raw_date.get("year", 0))
month = int(raw_date.get("month", 1))
day = int(raw_date.get("day", 1))
return datetime(year, month, day)
def get_weekday_name(date: datetime) -> tuple:
"""
Get the name of the weekday from its number.
:param weekday: Weekday number (0-6).
:return: Name of the weekday.
"""
vietnam_weekdays = {
0: "Thứ hai",
1: "Thứ ba",
2: "Thứ tư",
3: "Thứ năm",
4: "Thứ sáu",
5: "Thứ bảy",
6: "Chủ nhật",
}
weekday_ids = date.weekday()
weekday = (
vietnam_weekdays.get(weekday_ids) if vietnam_weekdays.get(weekday_ids) else ""
)
return date.strftime("%d-%m-%Y"), weekday
|