zbparse/flask_app/general/format_date.py

166 lines
5.9 KiB
Python
Raw Normal View History

2024-10-25 14:00:31 +08:00
import datetime
import re
def format_chinese_date(date_str):
"""
将包含中文字符的日期字符串格式化为标准的 'YYYY-MM-DD HH:MM:SS' 格式
参数:
date_str (str): 输入的中文日期字符串例如 "20 19 年7 月18日 09 30整"
返回:
str: 格式化后的日期字符串例如 "2019-07-18 09:30:00"
如果格式错误返回 None 并打印错误信息
"""
2024-10-25 17:50:20 +08:00
# 检查输入类型
if not isinstance(date_str, str):
print(f"输入类型错误: 期望字符串类型,实际类型为 {type(date_str)}")
return None
2024-10-25 14:00:31 +08:00
# print("------------")
# print(f"原始输入: {date_str}")
2024-11-01 17:55:26 +08:00
# 预处理:删除第一个数字之前的所有字符
date_str = re.sub(r'^[^\d]*', '', date_str)
2024-10-25 14:00:31 +08:00
# 1. 删除所有空格
date_str = ''.join(date_str.split())
# 1.5 删除括号及其内容(中文括号)
date_str = re.sub(r'.*?', '', date_str)
# 2. 使用正则表达式移除所有非数字和非必要的中文字符
# 只保留数字、年、月、日、时、分、秒、冒号、减号
2024-10-25 18:12:12 +08:00
date_str = re.sub(r'[^\d年月日时分秒点:\-]', '', date_str)
2024-10-25 14:00:31 +08:00
# print(f"去除多余字符后: {date_str}")
# 3. 替换全角冒号为半角冒号
date_str = date_str.replace('', ':')
# 4. 替换'年'和'月'为 '-', '日'为 ' ',确保日期和时间之间有一个空格
date_str = date_str.replace('', '-').replace('', '-').replace('', ' ')
# 替换'时'、'分'为 ':',并移除'秒'
2024-10-25 18:12:12 +08:00
date_str = date_str.replace('', ':').replace('',':').replace('', ':').replace('', '')
2024-10-25 14:00:31 +08:00
# print(f"替换分隔符后: {date_str}")
# 5. 处理时间部分
if ' ' not in date_str:
# 如果没有时间部分,添加默认时间
date_str += ' 00:00:00'
else:
# 分割日期和时间部分
parts = date_str.split(' ', 1)
if len(parts) != 2:
# Unexpected format
print(f"日期格式错误: 分割后部分数不正确 - {date_str}")
return None
date_part, time_part = parts
if not time_part:
# 时间部分为空,设置为默认时间
time_part = '00:00:00'
else:
# 如果时间部分只有小时和分钟,添加秒
time_components = time_part.split(':')
if len(time_components) == 1:
# 只有小时
time_part = f"{time_components[0]:0>2}:00:00"
elif len(time_components) == 2:
# 小时和分钟
time_part = f"{time_components[0]:0>2}:{time_components[1]:0>2}:00"
elif len(time_components) == 3:
# 小时、分钟和秒
time_part = f"{time_components[0]:0>2}:{time_components[1]:0>2}:{time_components[2]:0>2}"
else:
# 超过3个部分格式错误
print(f"日期格式错误: 时间部分格式不正确 - {time_part}")
return None
# 补齐日期部分中的月和日为双数字
date_parts = date_part.split('-')
if len(date_parts) != 3:
print(f"日期格式错误: 日期部分格式不正确 - {date_part}")
return None
year, month, day = date_parts
month = month.zfill(2)
day = day.zfill(2)
date_part = f"{year}-{month}-{day}"
date_str = f"{date_part} {time_part}"
# print(f"最终处理后字符串: {date_str}")
# 6. 定义输入字符串的格式
input_format = "%Y-%m-%d %H:%M:%S"
try:
# 解析字符串为 datetime 对象
dt = datetime.datetime.strptime(date_str, input_format)
# 格式化为所需的输出格式
formatted_date = dt.strftime("%Y-%m-%d %H:%M:%S")
return formatted_date
except ValueError as e:
print(f"日期格式错误: {e} - 处理后的字符串: '{date_str}'")
return None
# 示例使用
if __name__ == "__main__":
input_dates = [
# 完整的日期和时间
2024-11-01 17:55:26 +08:00
"开标日期是2021年 6月 18日 15点 00分",
2024-10-25 14:00:31 +08:00
"2019年7月18日0930",
"20 19 年7 月18日 09 30整北京时间",
"2020年02月05日12时30分45秒",
"2021年3月15日16:45:30",
"2022年6月30日23时59分59秒",
"2023年01月01日00时00分00秒",
"2024年12月31日23:59:59",
# 仅有日期,没有时间
"2020年12月5日",
"2021年5月1日",
"2022年02月29日", # 闰年
"2023年04月31日", # 无效日期
"2021年13月1日", # 无效月份
"2021年00月10日", # 无效月份
"2021年05月00日", # 无效日期
"2021年05月32日", # 无效日期
# 日期和部分时间
"2020年2月5日12时",
"2020年2月5日12时30分",
"2021年3月15日16:",
"2023年01月01日0000",
"2021年5月1日07时5分5秒",
"2021年5月1日07:5:5",
# 带有不同中文字符和额外内容
"2020年02月05日12:30整",
"2021年3月15日16:45上午",
"2022年6月30日23:59:59夜间",
"2023年01月01日00:00凌晨",
"2024年02月29日00:00:00闰年",
# 不同的时间表示方式
"2022年6月30日235959",
"2023年01月01日0000",
"2021年3月15日16时45分",
"2020年02月05日123045",
# 无效的日期字符串
"无效日期字符串",
"2021年5月1日25时00分00秒", # 无效小时
"2021年5月1日23时60分00秒", # 无效分钟
"2021年5月1日23时59分60秒", # 无效秒
]
for input_date in input_dates:
formatted = format_chinese_date(input_date)
print(type(formatted))
print(f"原始输入: {input_date} -> 格式化后: {formatted}\n")
if not formatted:
print("error!")