50 lines
2.1 KiB
Python
50 lines
2.1 KiB
Python
import datetime
|
|
import re
|
|
|
|
from log.log_manager import logger
|
|
|
|
|
|
def process_time(time_str):
|
|
"""Processes and converts a time string into a datetime object."""
|
|
current_time = datetime.datetime.now(datetime.timezone.utc)
|
|
if '分钟前' in time_str:
|
|
minutes = int(time_str.split('分钟前')[0])
|
|
occurrence_time = current_time - datetime.timedelta(minutes=minutes)
|
|
elif '小时前' in time_str:
|
|
hours = int(time_str.split('小时前')[0])
|
|
occurrence_time = current_time - datetime.timedelta(hours=hours)
|
|
elif '昨天' in time_str:
|
|
occurrence_time = current_time - datetime.timedelta(days=1)
|
|
elif '天前' in time_str:
|
|
occurrence_time = current_time - datetime.timedelta(days=int(time_str.split('天前')[0]))
|
|
elif '昨天' in time_str:
|
|
# time_str = '昨天HH:mm'
|
|
time_part = time_str.split('昨天')[-1].strip()
|
|
occurrence_time = (current_time - datetime.timedelta(days=1)).replace(
|
|
hour=int(time_part.split(':')[0]),
|
|
minute=int(time_part.split(':')[1]),
|
|
second=0
|
|
)
|
|
elif '前天' in time_str:
|
|
# time_str = '前天HH:mm'
|
|
time_part = time_str.split('前天')[-1].strip()
|
|
occurrence_time = (current_time - datetime.timedelta(days=2)).replace(
|
|
hour=int(time_part.split(':')[0]),
|
|
minute=int(time_part.split(':')[1]),
|
|
second=0
|
|
)
|
|
elif '年' in time_str and '月' in time_str and '日' in time_str:
|
|
time_pattern = r"(\d{4}年\d{1,2}月\d{1,2}日 \d{1,2}:\d{2})"
|
|
match = re.search(time_pattern, time_str)
|
|
time_str = match.group(1)
|
|
occurrence_time = datetime.datetime.strptime(time_str, "%Y年%m月%d日 %H:%M")
|
|
elif '/' in time_str:
|
|
occurrence_time = datetime.datetime.strptime(time_str, "%Y/%m/%d %H:%M:%S")
|
|
else:
|
|
try:
|
|
occurrence_time = datetime.datetime.strptime(time_str, '%Y-%m-%d')
|
|
except ValueError:
|
|
logger.error(f"Unable to parse date: {time_str}")
|
|
occurrence_time = current_time
|
|
|
|
return occurrence_time |