You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
iTi-Flask/iti/applications/common/utils/time.py

57 lines
1.3 KiB
Python

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

"""
时间处理工具
"""
from datetime import datetime
def parse_datetime_string(datetime_str: str) -> datetime:
"""
解析时间字符串为 datetime 对象
优先尝试前端常用的格式 %Y-%m-%d %H:%M:%S然后尝试 ISO 格式
Args:
datetime_str: 时间字符串
Returns:
datetime 对象
Raises:
ValueError: 如果无法解析时间字符串
"""
if not datetime_str:
raise ValueError("时间字符串不能为空")
# 优先尝试常用格式
for fmt in (
"%Y-%m-%d %H:%M:%S",
"%Y-%m-%d %H:%M",
"%Y-%m-%d",
"%Y/%m/%d %H:%M:%S",
"%Y/%m/%d %H:%M",
"%Y/%m/%d",
):
try:
return datetime.strptime(datetime_str, fmt)
except (ValueError, TypeError):
continue
# 尝试 ISO 格式(带时区)
try:
# 处理带 Z 后缀的 ISO 格式
iso_str = datetime_str.replace("Z", "+00:00")
return datetime.fromisoformat(iso_str)
except ValueError:
pass
# 尝试 ISO 格式(不带时区)
try:
return datetime.fromisoformat(datetime_str)
except ValueError:
pass
# 如果所有格式都失败,抛出异常
raise ValueError(f"无法解析时间字符串: {datetime_str}")