原始碼: 又臭又長
def parse_time(time_str):
now = datetime.now()
if '剛剛' in time_str:
return now
elif '秒前' in time_str:
seconds = int(time_str.split('秒前')[0])
return now - timedelta(seconds=seconds)
elif '分鐘前' in time_str:
minutes = int(time_str.split('分鐘前')[0])
return now - timedelta(minutes=minutes)
elif '小時前' in time_str:
hours = int(time_str.split('小時前')[0])
return now - timedelta(hours=hours)
elif '今天' in time_str:
return None
# time_format = re.search(r'今天 (\d+:\d+)', time_str).group(1)
# return datetime.strptime(f'{now.year}-{now.month}-{now.day} {time_format}', '%Y-%m-%d %H:%M')
else:
try:
return datetime.strptime(time_str, '%m月%d日 %H:%M')
except ValueError:
try:
return datetime.strptime(time_str, '%Y-%m-%d %H:%M')
except ValueError:
try:
return datetime.strptime(time_str, '%Y年%m月%d日 %H:%M')
except ValueError:
return None
列舉:
class TimeFormat(Enum):
JUST_NOW=(r'剛剛',lambda m:datetime.now())
SECONDS_AGO=(r'(\d+)秒前',lambda m:datetime.now()-timedelta(seconds=int(m.group(1))))
MINUTES_AGO=(r'(\d+)分鐘前',lambda m:datetime.now()-timedelta(minutes=int(m.group(1))))
HOURS_AGO=(r'(\d+)小時前',lambda m:datetime.now()-timedelta(hours=int(m.group(1))))
TODAY=(r'今天',lambda m:None)
MONTH_DAY_TIME = (r'(\d+)月(\d+)日 (\d+:\d+)', lambda m: datetime.strptime(f'{datetime.now().year}-{datetime.now().month}-{datetime.now().day}-{m.group(1)}', '%Y-%m-%d %H:%M:%S'))
YEAR_MONTH_DAY_TIME=(r'(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}))',lambda m:datetime.strptime(f'{datetime.now().year}-{m.group(1)}-{m.group(2)}-{m.group(3)}','%Y-%m-%d %H:%M'))
FULL_DATE_TIME=(r'(\d{4})年(\d{2})月(\d{2})日 (\d{2}):(\d{2}))',lambda m:datetime.strptime(m.group(0),'%Y-%m-%d %H:%M'))
def parse_time(time_str):
for time_format in TimeFormat:
pattern,handler=time_format.value
match=re.search(pattern,time_str)
if match:
return handler(match)
return None