├── LICENSE ├── README.md ├── date_convert.py └── 时间表达式.xlsx /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # XiYan-DateResolver 2 | 为了解决通用大模型在时间感知方面所面临的挑战,我们开发了一套解析处理文本中的时间和日期信息的流程XiYan-DateResolver,并将其转换为准确的真实时间。在覆盖的时间范围内实现了超过95%的准确率,支持包括年、月、日、周、季度、半年及时间段等在内的100多种时间表达方式。 3 | 4 | 示例:(假设今天为2024年12月6日,星期五) 5 | 6 | ```python 7 | 输入:上周三的销量是多少? 8 | 输出:上周星期3=2024年11月27日。 9 | 10 | 输入:公司在不包含今天的近三天内处理的订单数有多少? 11 | 输出:不包含今天的近3天=2024年12月3日至2024年12月5日。 12 | ``` 13 | 14 | ## 流程介绍 15 | 16 | XiYan-DateResolver包含以下两个步骤: 17 | 18 | ### 1、时间表达式抽取 19 | 20 | 模型文件:基于`Qwen2-7B-Instruct`微调的checkpoint,用于从输入的文本中抽取时间表达式,并将其转化成本方案定义的标准格式。 21 | 22 | 模型地址:[ModelScope](https://www.modelscope.cn/models/XGenerationLab/DateResolver-Qwen2-7B-Instruct) 23 | 24 | 示例: 25 | 26 | ```python 27 | 输入:本年度的销量是多少? 28 | 模型输出:["今年"] 29 | 30 | 输入:上周周五比周三的订单数多多少? 31 | 模型输出:["上周星期5", "上周星期3"] 32 | ``` 33 | 34 | 35 | ### 2、时间表达式推理 36 | 37 | 日期后处理脚本`date_convert.py`,自动获取当前日期,完成从标准的时间表达式到真实时间的推理。 38 | 39 | 示例:(假设今天为2024年12月6日,星期五) 40 | 41 | ```python 42 | 输入:["今年"] 43 | 输出:["今年=2024年"] 44 | 45 | 输入:["上周星期5", "上周星期3"] 46 | 输出:["上周星期5=2024年11月29日", "上周星期3=2024年11月27日"] 47 | ``` 48 | 49 | ## Requirements 50 | * python>=3.9 51 | * transformers>4.37.0 52 | * modelscope>=1.17.0 53 | 54 | ## 使用方式 55 | ### 1、时间表达式抽取 56 | 57 | 首先从modelscope加载模型: 58 | ```python 59 | from modelscope import AutoModelForCausalLM, AutoTokenizer 60 | device = "cuda" 61 | 62 | model_name = "XGenerationLab/DateResolver-Qwen2-7B-Instruct" 63 | model = AutoModelForCausalLM.from_pretrained( 64 | model_name, 65 | torch_dtype="auto", 66 | device_map="auto" 67 | ) 68 | tokenizer = AutoTokenizer.from_pretrained(model_name) 69 | ``` 70 | 71 | LLM从输入的文本中解析出时间表达式: 72 | ```python 73 | question = "上周三和上周五的销量是多少?" 74 | prompt = "给你一个用户的问题,请你提取出该用户所提问的时间,结果以list格式输出。\n\n【用户问题】\n{question}\n\n【回答】\n".format(question=question) 75 | messages = [ 76 | {"role": "system", "content": "You are a helpful assistant."}, 77 | {"role": "user", "content": prompt} 78 | ] 79 | text = tokenizer.apply_chat_template( 80 | messages, 81 | tokenize=False, 82 | add_generation_prompt=True 83 | ) 84 | model_inputs = tokenizer([text], return_tensors="pt").to(device) 85 | 86 | generated_ids = model.generate( 87 | model_inputs.input_ids, 88 | max_new_tokens=512 89 | ) 90 | generated_ids = [ 91 | output_ids[len(input_ids):] for input_ids, output_ids in zip(model_inputs.input_ids, generated_ids) 92 | ] 93 | 94 | response = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0] 95 | list_output = eval(response) 96 | ``` 97 | 98 | ### 2、时间表达式推理 99 | ```python 100 | from date_convert import DateTimeUtil 101 | DateTimeUtil.run(list_output) 102 | ``` 103 | 104 | ## 适用范围 105 | 106 | + 语言:中文为主 107 | + 时间表达式:一百多种常用的时间表达式,完整的时间表达式列表及对应的计算逻辑请查看:[时间表达式](https://github.com/XGenerationLab/XiYan-DateResolver/blob/main/%E6%97%B6%E9%97%B4%E8%A1%A8%E8%BE%BE%E5%BC%8F.xlsx) 108 | 109 | 110 | 111 | 更多XiYan-SQL相关内容请访问:https://github.com/XGenerationLab/XiYan-SQL 112 | -------------------------------------------------------------------------------- /date_convert.py: -------------------------------------------------------------------------------- 1 | import re 2 | import calendar 3 | from datetime import datetime, timedelta, date 4 | from typing import List 5 | from dateutil.relativedelta import relativedelta 6 | 7 | 8 | class DateTimeUtil: 9 | SPECIFIC_YEAR_MONTH_DAY_PATTERN = re.compile(r'\d{4}年\d{2}月\d{2}日') 10 | GENERAL_YEAR_MONTH_DAY_PATTERN = re.compile(r'(今年|去年|前年|明年|后年)(\d{2}月\d{2}日)') 11 | GENERAL_MONTH_DAY_PATTERN = re.compile(r'(本月|上月|上上月|下月)(\d{2}日)') 12 | GENERAL_DAY_PATTERN = re.compile(r'(今天|昨天|前天|明天|后天|上月今天|上上月今天)') 13 | # 每周从周一开始算 14 | WEEK_DAY_PATTERN = re.compile(r'本周第(\d)天') 15 | GENERAL_MONTH_LAST_DAY_PATTERN = re.compile(r'(本月|上月)最后一天') 16 | GENERAL_YEAR_MONTH_LAST_DAY_PATTERN = re.compile(r'(今年)(\d{2})月最后一天') 17 | SPECIFIC_YEAR_MONTH_PATTERN = re.compile(r'\d{4}年\d{2}月') 18 | GENERAL_YEAR_MONTH_PATTERN = re.compile(r'(今年|去年|前年|明年|后年)(\d{2}月)') 19 | GENERAL_MONTH_PATTERN = re.compile(r'(本月|上月|上上月|下月|去年本月)') 20 | SPECIFIC_YEAR_PATTERN = re.compile(r'(\d{4})年') 21 | GENERAL_YEAR_PATTERN = re.compile(r'(今年|去年|前年|明年|后年)') 22 | SPECIFIC_YEAR_QUARTER_PATTERN = re.compile(r'\d{4}年第\d季度') 23 | # 今年第1季度 = 2024年第1季度 24 | GENERAL_YEAR_QUARTER_PATTERN = re.compile(r'(今年|去年|前年|明年|后年)(第\d季度)') 25 | GENERAL_QUARTER_PATTERN = re.compile(r'(本季度|上季度|下季度|去年本季度)') 26 | GENERAL_WEEK_SPECIFIC_DAY_PATTERN = re.compile(r'(本周|上周|上上周|下周|下下周)星期(\d)') 27 | GENERAL_WEEK_PATTERN = re.compile(r'(本周|上周|上上周|下周|下下周)') 28 | SPECIFIC_YEAR_WEEK_PATTERN = re.compile(r'(\d{4})年第(\d{2})周') 29 | # 今年第54周会输出一个错的,第53周是对的,会截取到今天 30 | GENERAL_YEAR_WEEK_PATTERN = re.compile(r'(今年|去年|前年)第(\d{2})周') 31 | # 和上面同理 32 | GENERAL_MONTH_WEEK_PATTERN = re.compile(r'(本月|上月)第(\d)周') 33 | SPECIFIC_YEAR_MONTH_LAST_WEEK_PATTERN = re.compile(r'(\d{4})年(\d{2})月最后一周') 34 | GENERAL_MONTH_LAST_WEEK_PATTERN = re.compile(r'(本月|上月|上上月)最后一周') 35 | SPECIFIC_YEAR_MONTH_WEEK_PATTERN = re.compile(r'(\d{4})年(\d{2})月第(\d)周') 36 | GENERAL_YEAR_MONTH_WEEK_PATTERN = re.compile(r'(今年|去年|前年)(\d{2})月第(\d)周') 37 | SPECIFIC_YEAR_MONTH_COMPLETE_WEEK_PATTERN = re.compile(r'(\d{4})年(\d{2})月第(\d)个完整周') 38 | GENERAL_YEAR_COMPLETE_WEEK_PATTERN = re.compile(r'(今年|去年|前年)第(\d{2})个完整周') 39 | SPECIFIC_YEAR_COMPLETE_WEEK_PATTERN = re.compile(r'(\d{4})年第(\d{2})个完整周') 40 | GENERAL_YEAR_MONTH_COMPLETE_WEEK_PATTERN = re.compile(r'(今年|去年|前年)(\d{2})月第(\d)个完整周') 41 | GENERAL_MONTH_COMPLETE_WEEK_PATTERN = re.compile(r'(本月|上月)第(\d)个完整周') 42 | # GENERAL_MONTH_LAST_COMPLETE_WEEK_PATTERN = re.compile(r'(本月|上月|上上月)最后一个完整周') 43 | RECENT_N_YEAR_PATTERN = re.compile(r'近(\d+)年') 44 | RECENT_N_MONTH_PATTERN = re.compile(r'近(\d+)个月') 45 | RECENT_N_WEEK_PATTERN = re.compile(r'近(\d+)周') 46 | RECENT_N_DAY_PATTERN = re.compile(r'近(\d+)天') 47 | RECENT_N_COMPLETE_YEAR_PATTERN = re.compile(r'近(\d+)个完整年') 48 | RECENT_N_COMPLETE_QUARTER_PATTERN = re.compile(r'近(\d+)个完整季度') 49 | RECENT_N_COMPLETE_MONTH_PATTERN = re.compile(r'近(\d+)个完整月') 50 | RECENT_N_COMPLETE_WEEK_PATTERN = re.compile(r'近(\d+)个完整周') 51 | RECENT_N_DAY_WITHOUT_TODAY_PATTERN = re.compile(r'不包含今天的近(\d+)天') 52 | RECENT_N_QUARTER_WITH_CURRENT_PATTERN = re.compile(r'包含当前季度的近(\d+)个季度') 53 | SPECIFIC_YEAR_HALF_YEAR_PATTERN = re.compile(r'(\d{4})年(上|下)半年') 54 | GENERAL_YEAR_HALF_YEAR_PATTERN = re.compile(r'(今年|去年)(上|下)半年') 55 | HALF_YEAR_PATTERN = re.compile(r'(上|下)半年') 56 | 57 | @staticmethod 58 | def build_date_time_comment(expressions: List[str]) -> list: 59 | now = datetime.now() 60 | year = now.year 61 | month = now.month 62 | day = now.day 63 | quarter = (month - 1) // 3 + 1 64 | today_comment = f"今天是{year}年{month:02d}月{day:02d}日,是{year}年的第{quarter}季度" 65 | 66 | date_time_comment_list = DateTimeUtil.build_date_expressions(expressions, now) 67 | final_expression = [today_comment, "需要计算的时间是:"] + date_time_comment_list 68 | return date_time_comment_list 69 | 70 | @staticmethod 71 | def build_date_expressions(expressions: List[str], now: date) -> List[str]: 72 | date_time_comment_list = [] 73 | 74 | for expression in expressions: 75 | if DateTimeUtil.SPECIFIC_YEAR_HALF_YEAR_PATTERN.match(expression): 76 | year_ex = int(DateTimeUtil.SPECIFIC_YEAR_HALF_YEAR_PATTERN.match(expression).group(1)) 77 | half_year_ex = DateTimeUtil.SPECIFIC_YEAR_HALF_YEAR_PATTERN.match(expression).group(2) 78 | comment = DateTimeUtil.get_specific_year_half_year_ex(now, year_ex, half_year_ex) 79 | date_time_comment_list.append(f"{expression}={comment}") 80 | continue 81 | 82 | if DateTimeUtil.GENERAL_YEAR_HALF_YEAR_PATTERN.match(expression): 83 | year_ex = DateTimeUtil.GENERAL_YEAR_HALF_YEAR_PATTERN.match(expression).group(1) 84 | half_year_ex = DateTimeUtil.GENERAL_YEAR_HALF_YEAR_PATTERN.match(expression).group(2) 85 | comment = DateTimeUtil.get_general_year_half_year_ex(now, year_ex, half_year_ex) 86 | date_time_comment_list.append(f"{expression}={comment}") 87 | continue 88 | 89 | if DateTimeUtil.HALF_YEAR_PATTERN.match(expression): 90 | half_year_ex = DateTimeUtil.HALF_YEAR_PATTERN.match(expression).group(1) 91 | comment = DateTimeUtil.get_specific_year_half_year_ex(now, now.year, half_year_ex) 92 | date_time_comment_list.append(f"{expression}={comment}") 93 | continue 94 | 95 | if DateTimeUtil.SPECIFIC_YEAR_MONTH_COMPLETE_WEEK_PATTERN.match(expression): 96 | year_ex = int(DateTimeUtil.SPECIFIC_YEAR_MONTH_COMPLETE_WEEK_PATTERN.match(expression).group(1)) 97 | month_ex = int(DateTimeUtil.SPECIFIC_YEAR_MONTH_COMPLETE_WEEK_PATTERN.match(expression).group(2)) 98 | week_ex = int(DateTimeUtil.SPECIFIC_YEAR_MONTH_COMPLETE_WEEK_PATTERN.match(expression).group(3)) 99 | comment = DateTimeUtil.get_specific_year_month_complete_week_ex(now, year_ex, month_ex, week_ex) 100 | date_time_comment_list.append(f"{expression}={comment}") 101 | continue 102 | 103 | if DateTimeUtil.GENERAL_YEAR_MONTH_COMPLETE_WEEK_PATTERN.match(expression): 104 | year_ex = DateTimeUtil.GENERAL_YEAR_MONTH_COMPLETE_WEEK_PATTERN.match(expression).group(1) 105 | month_ex = int(DateTimeUtil.GENERAL_YEAR_MONTH_COMPLETE_WEEK_PATTERN.match(expression).group(2)) 106 | week_ex = int(DateTimeUtil.GENERAL_YEAR_MONTH_COMPLETE_WEEK_PATTERN.match(expression).group(3)) 107 | comment = DateTimeUtil.get_general_year_month_complete_week_ex(now, year_ex, month_ex, week_ex) 108 | date_time_comment_list.append(f"{expression}={comment}") 109 | continue 110 | 111 | if DateTimeUtil.SPECIFIC_YEAR_COMPLETE_WEEK_PATTERN.match(expression): 112 | year_ex = int(DateTimeUtil.SPECIFIC_YEAR_COMPLETE_WEEK_PATTERN.match(expression).group(1)) 113 | week_ex = int(DateTimeUtil.SPECIFIC_YEAR_COMPLETE_WEEK_PATTERN.match(expression).group(2)) 114 | comment = DateTimeUtil.get_specific_year_complete_week_ex(now, year_ex, week_ex) 115 | date_time_comment_list.append(f"{expression}={comment}") 116 | continue 117 | 118 | if DateTimeUtil.GENERAL_YEAR_COMPLETE_WEEK_PATTERN.match(expression): 119 | year_ex = DateTimeUtil.GENERAL_YEAR_COMPLETE_WEEK_PATTERN.match(expression).group(1) 120 | week_ex = int(DateTimeUtil.GENERAL_YEAR_COMPLETE_WEEK_PATTERN.match(expression).group(2)) 121 | comment = DateTimeUtil.get_general_year_complete_week_ex(now, year_ex, week_ex) 122 | date_time_comment_list.append(f"{expression}={comment}") 123 | continue 124 | 125 | if DateTimeUtil.GENERAL_MONTH_COMPLETE_WEEK_PATTERN.match(expression): 126 | month_ex = DateTimeUtil.GENERAL_MONTH_COMPLETE_WEEK_PATTERN.match(expression).group(1) 127 | week_ex = int(DateTimeUtil.GENERAL_MONTH_COMPLETE_WEEK_PATTERN.match(expression).group(2)) 128 | comment = DateTimeUtil.get_general_month_complete_week_ex(now, month_ex, week_ex) 129 | date_time_comment_list.append(f"{expression}={comment}") 130 | continue 131 | 132 | if DateTimeUtil.GENERAL_MONTH_WEEK_PATTERN.match(expression): 133 | month_ex = DateTimeUtil.GENERAL_MONTH_WEEK_PATTERN.match(expression).group(1) 134 | week_ex = int(DateTimeUtil.GENERAL_MONTH_WEEK_PATTERN.match(expression).group(2)) 135 | comment = DateTimeUtil.get_general_month_week_ex(now, month_ex, week_ex) 136 | date_time_comment_list.append(f"{expression}={comment}") 137 | continue 138 | 139 | if DateTimeUtil.SPECIFIC_YEAR_MONTH_DAY_PATTERN.match(expression): 140 | date_time_comment_list.append(f"{expression}={expression}") 141 | continue 142 | 143 | if DateTimeUtil.GENERAL_YEAR_MONTH_DAY_PATTERN.match(expression): 144 | year_ex = DateTimeUtil.GENERAL_YEAR_MONTH_DAY_PATTERN.match(expression).group(1) 145 | comment = DateTimeUtil.get_year_ex(now, year_ex) + DateTimeUtil.GENERAL_YEAR_MONTH_DAY_PATTERN.match( 146 | expression).group(2) 147 | date_time_comment_list.append(f"{expression}={comment}") 148 | continue 149 | 150 | if DateTimeUtil.GENERAL_MONTH_DAY_PATTERN.match(expression): 151 | month_ex = DateTimeUtil.GENERAL_MONTH_DAY_PATTERN.match(expression).group(1) 152 | comment = DateTimeUtil.get_month_ex(now, month_ex) + DateTimeUtil.GENERAL_MONTH_DAY_PATTERN.match( 153 | expression).group(2) 154 | date_time_comment_list.append(f"{expression}={comment}") 155 | continue 156 | 157 | if DateTimeUtil.GENERAL_YEAR_MONTH_LAST_DAY_PATTERN.match(expression): 158 | year_ex = DateTimeUtil.GENERAL_YEAR_MONTH_LAST_DAY_PATTERN.match(expression).group(1) 159 | month_ex = DateTimeUtil.GENERAL_YEAR_MONTH_LAST_DAY_PATTERN.match(expression).group(2) 160 | comment = DateTimeUtil.get_general_year_month_last_day_ex(now, year_ex, int(month_ex)) 161 | date_time_comment_list.append(f"{expression}={comment}") 162 | continue 163 | 164 | if DateTimeUtil.GENERAL_MONTH_LAST_DAY_PATTERN.match(expression): 165 | month_ex = DateTimeUtil.GENERAL_MONTH_LAST_DAY_PATTERN.match(expression).group(1) 166 | comment = DateTimeUtil.get_month_last_day_ex(now, month_ex) 167 | date_time_comment_list.append(f"{expression}={comment}") 168 | continue 169 | 170 | if DateTimeUtil.WEEK_DAY_PATTERN.match(expression): 171 | week_day = int(DateTimeUtil.WEEK_DAY_PATTERN.match(expression).group(1)) 172 | comment = DateTimeUtil.get_week_day_ex(now, week_day) 173 | date_time_comment_list.append(f"{expression}={comment}") 174 | continue 175 | 176 | if DateTimeUtil.GENERAL_WEEK_SPECIFIC_DAY_PATTERN.match(expression): 177 | week_ex = DateTimeUtil.GENERAL_WEEK_SPECIFIC_DAY_PATTERN.match(expression).group(1) 178 | day = int(DateTimeUtil.GENERAL_WEEK_SPECIFIC_DAY_PATTERN.match(expression).group(2)) 179 | comment = DateTimeUtil.get_general_week_day_ex(now, week_ex, day) 180 | date_time_comment_list.append(f"{expression}={comment}") 181 | continue 182 | 183 | if DateTimeUtil.SPECIFIC_YEAR_QUARTER_PATTERN.match(expression): 184 | date_time_comment_list.append(f"{expression}={expression}") 185 | continue 186 | 187 | if DateTimeUtil.GENERAL_YEAR_QUARTER_PATTERN.match(expression): 188 | year_ex = DateTimeUtil.GENERAL_YEAR_QUARTER_PATTERN.match(expression).group(1) 189 | quarter_ex = DateTimeUtil.GENERAL_YEAR_QUARTER_PATTERN.match(expression).group(2) 190 | comment = DateTimeUtil.get_year_ex(now, year_ex) + quarter_ex 191 | date_time_comment_list.append(f"{expression}={comment}") 192 | continue 193 | 194 | if DateTimeUtil.GENERAL_QUARTER_PATTERN.match(expression): 195 | quarter_ex = DateTimeUtil.GENERAL_QUARTER_PATTERN.match(expression).group(1) 196 | comment = DateTimeUtil.get_quarter_ex(now, quarter_ex) 197 | date_time_comment_list.append(f"{expression}={comment}") 198 | continue 199 | 200 | if DateTimeUtil.GENERAL_WEEK_PATTERN.match(expression): 201 | week_ex = DateTimeUtil.GENERAL_WEEK_PATTERN.match(expression).group(1) 202 | comment = DateTimeUtil.get_week_ex(now, week_ex) 203 | date_time_comment_list.append(f"{expression}={comment}") 204 | continue 205 | 206 | if DateTimeUtil.SPECIFIC_YEAR_WEEK_PATTERN.match(expression): 207 | year_ex = int(DateTimeUtil.SPECIFIC_YEAR_WEEK_PATTERN.match(expression).group(1)) 208 | week_ex = int(DateTimeUtil.SPECIFIC_YEAR_WEEK_PATTERN.match(expression).group(2)) 209 | comment = DateTimeUtil.get_specific_year_week_ex(now, year_ex, week_ex) 210 | date_time_comment_list.append(f"{expression}={comment}") 211 | continue 212 | 213 | if DateTimeUtil.GENERAL_YEAR_WEEK_PATTERN.match(expression): 214 | year_ex = DateTimeUtil.GENERAL_YEAR_WEEK_PATTERN.match(expression).group(1) 215 | week_ex = int(DateTimeUtil.GENERAL_YEAR_WEEK_PATTERN.match(expression).group(2)) 216 | comment = DateTimeUtil.get_general_year_week_ex(now, year_ex, week_ex) 217 | date_time_comment_list.append(f"{expression}={comment}") 218 | continue 219 | 220 | if DateTimeUtil.SPECIFIC_YEAR_MONTH_WEEK_PATTERN.match(expression): 221 | year_ex = int(DateTimeUtil.SPECIFIC_YEAR_MONTH_WEEK_PATTERN.match(expression).group(1)) 222 | month_ex = int(DateTimeUtil.SPECIFIC_YEAR_MONTH_WEEK_PATTERN.match(expression).group(2)) 223 | week_ex = int(DateTimeUtil.SPECIFIC_YEAR_MONTH_WEEK_PATTERN.match(expression).group(3)) 224 | comment = DateTimeUtil.get_specific_year_month_week_ex(now, year_ex, month_ex, week_ex) 225 | date_time_comment_list.append(f"{expression}={comment}") 226 | continue 227 | 228 | if DateTimeUtil.GENERAL_YEAR_MONTH_WEEK_PATTERN.match(expression): 229 | year_ex = DateTimeUtil.GENERAL_YEAR_MONTH_WEEK_PATTERN.match(expression).group(1) 230 | month_ex = int(DateTimeUtil.GENERAL_YEAR_MONTH_WEEK_PATTERN.match(expression).group(2)) 231 | week_ex = int(DateTimeUtil.GENERAL_YEAR_MONTH_WEEK_PATTERN.match(expression).group(3)) 232 | comment = DateTimeUtil.get_general_year_month_week_ex(now, year_ex, month_ex, week_ex) 233 | date_time_comment_list.append(f"{expression}={comment}") 234 | continue 235 | 236 | if DateTimeUtil.SPECIFIC_YEAR_MONTH_LAST_WEEK_PATTERN.match(expression): 237 | year_ex = int(DateTimeUtil.SPECIFIC_YEAR_MONTH_LAST_WEEK_PATTERN.match(expression).group(1)) 238 | month_ex = int(DateTimeUtil.SPECIFIC_YEAR_MONTH_LAST_WEEK_PATTERN.match(expression).group(2)) 239 | comment = DateTimeUtil.get_specific_year_month_last_week(now, year_ex, month_ex) 240 | date_time_comment_list.append(f"{expression}={comment}") 241 | continue 242 | 243 | if DateTimeUtil.GENERAL_MONTH_LAST_WEEK_PATTERN.match(expression): 244 | month_ex = DateTimeUtil.GENERAL_MONTH_LAST_WEEK_PATTERN.match(expression).group(1) 245 | comment = DateTimeUtil.get_general_month_last_week(now, month_ex) 246 | date_time_comment_list.append(f"{expression}={comment}") 247 | continue 248 | 249 | # if DateTimeUtil.GENERAL_MONTH_LAST_COMPLETE_WEEK_PATTERN.match(expression): 250 | # month_ex = DateTimeUtil.GENERAL_MONTH_LAST_COMPLETE_WEEK_PATTERN.match(expression).group(1) 251 | # comment = DateTimeUtil.get_general_month_last_complete_week_ex(now, month_ex) 252 | # date_time_comment_list.append(f"{expression}={comment}") 253 | # continue 254 | 255 | if DateTimeUtil.RECENT_N_YEAR_PATTERN.match(expression): 256 | n = int(DateTimeUtil.RECENT_N_YEAR_PATTERN.match(expression).group(1)) 257 | comment = DateTimeUtil.get_recent_n_year(now, n) 258 | date_time_comment_list.append(f"{expression}={comment}") 259 | continue 260 | 261 | if DateTimeUtil.RECENT_N_MONTH_PATTERN.match(expression): 262 | n = int(DateTimeUtil.RECENT_N_MONTH_PATTERN.match(expression).group(1)) 263 | comment = DateTimeUtil.get_recent_n_month(now, n) 264 | date_time_comment_list.append(f"{expression}={comment}") 265 | continue 266 | 267 | if DateTimeUtil.RECENT_N_WEEK_PATTERN.match(expression): 268 | n = int(DateTimeUtil.RECENT_N_WEEK_PATTERN.match(expression).group(1)) 269 | comment = DateTimeUtil.get_recent_n_week(now, n) 270 | date_time_comment_list.append(f"{expression}={comment}") 271 | continue 272 | 273 | if DateTimeUtil.RECENT_N_DAY_WITHOUT_TODAY_PATTERN.match(expression): 274 | n = int(DateTimeUtil.RECENT_N_DAY_WITHOUT_TODAY_PATTERN.match(expression).group(1)) 275 | comment = DateTimeUtil.get_recent_n_day_without_today(now, n) 276 | date_time_comment_list.append(f"{expression}={comment}") 277 | continue 278 | 279 | if DateTimeUtil.RECENT_N_DAY_PATTERN.match(expression): 280 | n = int(DateTimeUtil.RECENT_N_DAY_PATTERN.match(expression).group(1)) 281 | comment = DateTimeUtil.get_recent_n_day(now, n) 282 | date_time_comment_list.append(f"{expression}={comment}") 283 | continue 284 | 285 | if DateTimeUtil.RECENT_N_COMPLETE_YEAR_PATTERN.match(expression): 286 | n = int(DateTimeUtil.RECENT_N_COMPLETE_YEAR_PATTERN.match(expression).group(1)) 287 | comment = DateTimeUtil.get_recent_n_complete_year(now, n) 288 | date_time_comment_list.append(f"{expression}={comment}") 289 | continue 290 | 291 | if DateTimeUtil.RECENT_N_COMPLETE_QUARTER_PATTERN.match(expression): 292 | n = int(DateTimeUtil.RECENT_N_COMPLETE_QUARTER_PATTERN.match(expression).group(1)) 293 | comment = DateTimeUtil.get_recent_n_complete_quarter(now, n) 294 | date_time_comment_list.append(f"{expression}={comment}") 295 | continue 296 | 297 | if DateTimeUtil.RECENT_N_COMPLETE_MONTH_PATTERN.match(expression): 298 | n = int(DateTimeUtil.RECENT_N_COMPLETE_MONTH_PATTERN.match(expression).group(1)) 299 | comment = DateTimeUtil.get_recent_n_complete_month(now, n) 300 | date_time_comment_list.append(f"{expression}={comment}") 301 | continue 302 | 303 | if DateTimeUtil.RECENT_N_COMPLETE_WEEK_PATTERN.match(expression): 304 | n = int(DateTimeUtil.RECENT_N_COMPLETE_WEEK_PATTERN.match(expression).group(1)) 305 | comment = DateTimeUtil.get_recent_n_complete_week(now, n) 306 | date_time_comment_list.append(f"{expression}={comment}") 307 | continue 308 | 309 | if DateTimeUtil.RECENT_N_QUARTER_WITH_CURRENT_PATTERN.match(expression): 310 | n = int(DateTimeUtil.RECENT_N_QUARTER_WITH_CURRENT_PATTERN.match(expression).group(1)) 311 | comment = DateTimeUtil.get_recent_n_quarter_with_current(now, n) 312 | date_time_comment_list.append(f"{expression}={comment}") 313 | continue 314 | 315 | if DateTimeUtil.SPECIFIC_YEAR_MONTH_PATTERN.match(expression): 316 | date_time_comment_list.append(f"{expression}={expression}") 317 | continue 318 | 319 | if DateTimeUtil.GENERAL_YEAR_MONTH_PATTERN.match(expression): 320 | year_ex = DateTimeUtil.GENERAL_YEAR_MONTH_PATTERN.match(expression).group(1) 321 | comment = DateTimeUtil.get_year_ex(now, year_ex) + DateTimeUtil.GENERAL_YEAR_MONTH_PATTERN.match(expression).group(2) 322 | date_time_comment_list.append(f"{expression}={comment}") 323 | continue 324 | 325 | if DateTimeUtil.GENERAL_DAY_PATTERN.match(expression): 326 | day_ex = DateTimeUtil.GENERAL_DAY_PATTERN.match(expression).group(1) 327 | comment = DateTimeUtil.get_day_ex(now, day_ex) 328 | date_time_comment_list.append(f"{expression}={comment}") 329 | continue 330 | 331 | if DateTimeUtil.GENERAL_MONTH_PATTERN.match(expression): 332 | month_ex = DateTimeUtil.GENERAL_MONTH_PATTERN.match(expression).group(1) 333 | comment = DateTimeUtil.get_month_ex(now, month_ex) 334 | date_time_comment_list.append(f"{expression}={comment}") 335 | continue 336 | 337 | if DateTimeUtil.SPECIFIC_YEAR_PATTERN.match(expression): 338 | year_ex = int(DateTimeUtil.SPECIFIC_YEAR_PATTERN.match(expression).group(1)) 339 | comment = f"{year_ex}年" 340 | date_time_comment_list.append(f"{expression}={comment}") 341 | continue 342 | 343 | if DateTimeUtil.GENERAL_YEAR_PATTERN.match(expression): 344 | year_ex = DateTimeUtil.GENERAL_YEAR_PATTERN.match(expression).group(1) 345 | comment = DateTimeUtil.get_year_ex(now, year_ex) 346 | date_time_comment_list.append(f"{expression}={comment}") 347 | continue 348 | 349 | 350 | 351 | 352 | return date_time_comment_list 353 | 354 | @staticmethod 355 | def get_year_ex(now: datetime, year_ex: str) -> str: 356 | year = now.year 357 | if year_ex == "今年": 358 | year = now.year 359 | elif year_ex == "去年": 360 | year = now.year - 1 361 | elif year_ex == "前年": 362 | year = now.year - 2 363 | elif year_ex == "明年": 364 | year = now.year + 1 365 | elif year_ex == "后年": 366 | year = now.year + 2 367 | return f"{year}年" 368 | 369 | @staticmethod 370 | def get_month_ex(now: datetime, month_ex: str) -> str: 371 | date_format = "%Y年%m月" 372 | if month_ex == "本月": 373 | return now.strftime(date_format) 374 | elif month_ex == "上月": 375 | last_month = now - timedelta(days=30) 376 | return last_month.strftime(date_format.replace("%Y", "%Y").replace("%m", "%m").replace("30", "01")) 377 | elif month_ex == "上上月": 378 | last_month = now - timedelta(days=60) 379 | return last_month.strftime(date_format.replace("%Y", "%Y").replace("%m", "%m").replace("30", "01")) 380 | elif month_ex == "下月": 381 | next_month = now + timedelta(days=30) 382 | return next_month.strftime(date_format.replace("%Y", "%Y").replace("%m", "%m").replace("30", "01")) 383 | elif month_ex == "去年本月": 384 | last_year = now.replace(year=now.year - 1) 385 | return last_year.strftime(date_format) 386 | return "" 387 | 388 | @staticmethod 389 | def get_day_ex(now: datetime, day_ex: str) -> str: 390 | date_format = "%Y年%m月%d日" 391 | comment = "" 392 | try: 393 | if day_ex == "今天": 394 | comment = now.strftime(date_format) 395 | elif day_ex == "昨天": 396 | comment = (now - timedelta(days=1)).strftime(date_format) 397 | elif day_ex == "前天": 398 | comment = (now - timedelta(days=2)).strftime(date_format) 399 | elif day_ex == "明天": 400 | comment = (now + timedelta(days=1)).strftime(date_format) 401 | elif day_ex == "后天": 402 | comment = (now + timedelta(days=2)).strftime(date_format) 403 | elif day_ex == "上月今天": 404 | previous_month = now + relativedelta(months=-1) 405 | comment = (previous_month.replace(day=now.day)).strftime(date_format) 406 | elif day_ex == "上上月今天": 407 | two_months_ago = now + relativedelta(months=-2) 408 | comment = (two_months_ago.replace(day=now.day)).strftime(date_format) 409 | 410 | except Exception as e: 411 | print(f"Error convert dayEx: {day_ex}, {e}") 412 | 413 | return comment 414 | 415 | @staticmethod 416 | def get_week_day_ex(now: datetime, x: int) -> str: 417 | # 计算本周第一天(周一)的日期 418 | monday = now - timedelta(days=now.weekday()) 419 | # 通过加上(x - 1)天来得到本周第x天的日期 420 | desired_day = monday + timedelta(days=x - 1) 421 | return desired_day.strftime("%Y年%m月%d日") 422 | 423 | @staticmethod 424 | def get_general_week_day_ex(now: datetime, week_ex: str, day: int) -> str: 425 | this_monday = now - timedelta(days=now.weekday()) 426 | desired_day = this_monday + timedelta(days=day - 1) 427 | 428 | if week_ex == "上周": 429 | desired_day -= timedelta(weeks=1) 430 | elif week_ex == "上上周": 431 | desired_day -= timedelta(weeks=2) 432 | elif week_ex == "下周": 433 | desired_day += timedelta(weeks=1) 434 | elif week_ex == "下下周": 435 | desired_day += timedelta(weeks=2) 436 | 437 | return desired_day.strftime("%Y年%m月%d日") 438 | 439 | @staticmethod 440 | def get_week_ex(now: datetime, week_ex: str) -> str: 441 | desire_monday = now - timedelta(days=now.weekday()) 442 | desire_sunday = desire_monday + timedelta(days=6) 443 | 444 | if week_ex == "上周": 445 | desire_monday -= timedelta(weeks=1) 446 | desire_sunday -= timedelta(weeks=1) 447 | elif week_ex == "上上周": 448 | desire_monday -= timedelta(weeks=2) 449 | desire_sunday -= timedelta(weeks=2) 450 | elif week_ex == "下周": 451 | desire_monday += timedelta(weeks=1) 452 | desire_sunday += timedelta(weeks=1) 453 | elif week_ex == "下下周": 454 | desire_monday += timedelta(weeks=2) 455 | desire_sunday += timedelta(weeks=2) 456 | 457 | return f"{desire_monday.strftime('%Y年%m月%d日')}至{desire_sunday.strftime('%Y年%m月%d日')}" 458 | 459 | @staticmethod 460 | def get_specific_year_week_ex(now: datetime, year: int, week: int) -> str: 461 | first_day_of_year = datetime(year, 1, 1) 462 | target_week_first_day = first_day_of_year + timedelta(weeks=week - 1) 463 | target_week_last_day = target_week_first_day + timedelta(days=6) 464 | last_day_of_year = first_day_of_year.replace(month=12, day=31) 465 | 466 | if last_day_of_year < target_week_last_day: 467 | target_week_last_day = last_day_of_year 468 | 469 | return f"{target_week_first_day.strftime('%Y年%m月%d日')}至{target_week_last_day.strftime('%Y年%m月%d日')}" 470 | 471 | @staticmethod 472 | def get_general_year_week_ex(now: datetime, year_ex: str, week: int) -> str: 473 | year = now.year 474 | if year_ex == "去年": 475 | year -= 1 476 | elif year_ex == "前年": 477 | year -= 2 478 | elif year_ex == "明年": 479 | year += 1 480 | elif year_ex == "后年": 481 | year += 2 482 | return DateTimeUtil.get_specific_year_week_ex(now, year, week) 483 | 484 | @staticmethod 485 | def get_specific_year_month_week_ex(now: datetime, year: int, month: int, week: int) -> str: 486 | first_day_of_month = datetime(year, month, 1) 487 | target_week_first_day = first_day_of_month + timedelta(weeks=week - 1) 488 | target_week_last_day = target_week_first_day + timedelta(days=6) 489 | last_day_of_month = first_day_of_month + relativedelta(months=1, days=-1) 490 | 491 | if last_day_of_month < target_week_last_day: 492 | target_week_last_day = last_day_of_month 493 | 494 | return f"{target_week_first_day.strftime('%Y年%m月%d日')}至{target_week_last_day.strftime('%Y年%m月%d日')}" 495 | 496 | @staticmethod 497 | def get_general_year_month_week_ex(now: datetime, year_ex: str, month: int, week: int) -> str: 498 | year = now.year 499 | if year_ex == "去年": 500 | year -= 1 501 | elif year_ex == "前年": 502 | year -= 2 503 | elif year_ex == "明年": 504 | year += 1 505 | elif year_ex == "后年": 506 | year += 2 507 | return DateTimeUtil.get_specific_year_month_week_ex(now, year, month, week) 508 | 509 | @staticmethod 510 | def get_general_month_week_ex(now: datetime, month_ex: str, week: int) -> str: 511 | year = now.year 512 | month = now.month 513 | 514 | if month_ex == "上月": 515 | month -= 1 516 | if month <= 0: 517 | year -= 1 518 | month = 12 519 | elif month_ex == "上上月": 520 | month -= 2 521 | if month <= 0: 522 | year -= 1 523 | month += 12 524 | elif month_ex == "下月": 525 | month += 1 526 | if month > 12: 527 | year += 1 528 | month -= 12 529 | 530 | first_day_of_month = datetime(year, month, 1) 531 | target_week_first_day = first_day_of_month + timedelta(weeks=week - 1) 532 | target_week_last_day = target_week_first_day + timedelta(days=6) 533 | last_day_of_month = first_day_of_month + relativedelta(months=1, days=-1) 534 | 535 | if last_day_of_month < target_week_last_day: 536 | target_week_last_day = last_day_of_month 537 | 538 | return f"{target_week_first_day.strftime('%Y年%m月%d日')}至{target_week_last_day.strftime('%Y年%m月%d日')}" 539 | 540 | @staticmethod 541 | def get_specific_year_month_complete_week_ex(now: datetime, year: int, month: int, week: int) -> str: 542 | first_day_of_month = datetime(year, month, 1) 543 | first_monday = first_day_of_month + timedelta(days=(-first_day_of_month.weekday()) % 7) 544 | target_start_date = first_monday + timedelta(weeks=week - 1) 545 | target_end_date = target_start_date + timedelta(days=6) 546 | last_day_of_month = first_day_of_month + relativedelta(months=1, days=-1) 547 | 548 | if last_day_of_month < target_end_date: 549 | return "" # Return empty string as per the original Java method behavior 550 | 551 | return f"{target_start_date.strftime('%Y年%m月%d日')}至{target_end_date.strftime('%Y年%m月%d日')}" 552 | 553 | @staticmethod 554 | def get_general_year_month_complete_week_ex(now: datetime, year_ex: str, month: int, week: int) -> str: 555 | year = now.year 556 | if year_ex == "去年": 557 | year -= 1 558 | elif year_ex == "前年": 559 | year -= 2 560 | elif year_ex == "明年": 561 | year += 1 562 | elif year_ex == "后年": 563 | year += 2 564 | return DateTimeUtil.get_specific_year_month_complete_week_ex(now, year, month, week) 565 | 566 | @staticmethod 567 | def get_general_month_complete_week_ex(now: datetime, month_ex: str, week: int) -> str: 568 | year = now.year 569 | month = now.month 570 | 571 | if month_ex == "上月": 572 | month -= 1 573 | if month <= 0: 574 | year -= 1 575 | month = 12 576 | elif month_ex == "上上月": 577 | month -= 2 578 | if month <= 0: 579 | year -= 1 580 | month += 12 581 | elif month_ex == "下月": 582 | month += 1 583 | if month > 12: 584 | year += 1 585 | month -= 12 586 | 587 | return DateTimeUtil.get_specific_year_month_complete_week_ex(now, year, month, week) 588 | 589 | @staticmethod 590 | def get_specific_year_complete_week_ex(now: datetime, year: int, week: int) -> str: 591 | first_day_of_year = datetime(year, 1, 1) 592 | first_monday = first_day_of_year + timedelta(days=(-first_day_of_year.weekday()) % 7) 593 | target_start_date = first_monday + timedelta(weeks=week - 1) 594 | target_end_date = target_start_date + timedelta(days=6) 595 | last_day_of_year = first_day_of_year + relativedelta(years=1, days=-1) 596 | 597 | if last_day_of_year < target_end_date: 598 | return "" 599 | 600 | return f"{target_start_date.strftime('%Y年%m月%d日')}至{target_end_date.strftime('%Y年%m月%d日')}" 601 | 602 | @staticmethod 603 | def get_general_year_complete_week_ex(now: datetime, year_ex: str, week: int) -> str: 604 | year = now.year 605 | if year_ex == "去年": 606 | year -= 1 607 | elif year_ex == "前年": 608 | year -= 2 609 | elif year_ex == "明年": 610 | year += 1 611 | elif year_ex == "后年": 612 | year += 2 613 | return DateTimeUtil.get_specific_year_complete_week_ex(now, year, week) 614 | 615 | @staticmethod 616 | def get_specific_year_month_last_week(now: datetime, year: int, month: int) -> str: 617 | last_day_of_month = calendar.monthrange(year, month)[1] 618 | last_date = datetime(year, month, last_day_of_month) 619 | last_day_of_month = datetime(year, month, last_day_of_month) 620 | while last_date.weekday() != 0: 621 | last_date -= timedelta(days=1) 622 | return f"{last_date.strftime('%Y年%m月%d日')}至{last_day_of_month.strftime('%Y年%m月%d日')}" 623 | 624 | @staticmethod 625 | def get_general_month_last_week(now: datetime, month_ex: str) -> str: 626 | year = now.year 627 | month = now.month 628 | 629 | if month_ex == "上月": 630 | month -= 1 631 | if month <= 0: 632 | year -= 1 633 | month = 12 634 | elif month_ex == "上上月": 635 | month -= 2 636 | if month <= 0: 637 | year -= 1 638 | month += 12 639 | elif month_ex == "下月": 640 | month += 1 641 | if month > 12: 642 | year += 1 643 | month -= 12 644 | 645 | return DateTimeUtil.get_specific_year_month_last_week(now, year, month) 646 | 647 | @staticmethod 648 | def get_specific_year_month_last_complete_week_ex(now: datetime, year: int, month: int) -> str: 649 | first_day_of_month = datetime(year, month, 1) 650 | last_sunday = first_day_of_month + relativedelta(months=1, days=-1) 651 | last_monday = last_sunday - timedelta(days=6) 652 | return f"{last_monday.strftime('%Y年%m月%d日')}至{last_sunday.strftime('%Y年%m月%d日')}" 653 | 654 | @staticmethod 655 | def get_general_month_last_complete_week_ex(now: datetime, month_ex: str) -> str: 656 | year = now.year 657 | month = now.month 658 | 659 | if month_ex == "上月": 660 | month -= 1 661 | if month <= 0: 662 | year -= 1 663 | month = 12 664 | elif month_ex == "上上月": 665 | month -= 2 666 | if month <= 0: 667 | year -= 1 668 | month += 12 669 | elif month_ex == "下月": 670 | month += 1 671 | if month > 12: 672 | year += 1 673 | month -= 12 674 | 675 | return DateTimeUtil.get_specific_year_month_last_complete_week_ex(now, year, month) 676 | 677 | @staticmethod 678 | def get_quarter_ex(now: datetime, quarter_ex: str) -> str: 679 | current_quarter = (now.month - 1) // 3 + 1 680 | last_quarter = 4 if current_quarter == 1 else current_quarter - 1 681 | next_quarter = 1 if current_quarter == 4 else current_quarter + 1 682 | current_year = now.year 683 | year_of_last_quarter = current_year if current_quarter != 1 else current_year - 1 684 | year_of_next_quarter = current_year + (1 if current_quarter == 4 else 0) 685 | year_of_same_quarter_last_year = current_year - 1 686 | comment = "" 687 | 688 | if quarter_ex == "本季度": 689 | comment = f"{current_year}年第{current_quarter}季度" 690 | elif quarter_ex == "上季度": 691 | comment = f"{year_of_last_quarter}年第{last_quarter}季度" 692 | elif quarter_ex == "下季度": 693 | comment = f"{year_of_next_quarter}年第{next_quarter}季度" 694 | elif quarter_ex == "去年本季度": 695 | comment = f"{year_of_same_quarter_last_year}年第{current_quarter}季度" 696 | 697 | return comment 698 | 699 | @staticmethod 700 | def get_recent_n_year(now: datetime, n: int) -> str: 701 | start_date = now - relativedelta(years=n) 702 | return f"{start_date.strftime('%Y年%m月%d日')}至{now.strftime('%Y年%m月%d日')}" 703 | 704 | @staticmethod 705 | def get_recent_n_month(now: datetime, n: int) -> str: 706 | start_date = now - relativedelta(months=n) 707 | return f"{start_date.strftime('%Y年%m月%d日')}至{now.strftime('%Y年%m月%d日')}" 708 | 709 | @staticmethod 710 | def get_recent_n_week(now: datetime, n: int) -> str: 711 | start_date = now - timedelta(weeks=n) 712 | return f"{start_date.strftime('%Y年%m月%d日')}至{now.strftime('%Y年%m月%d日')}" 713 | 714 | @staticmethod 715 | def get_recent_n_day(now: datetime, n: int) -> str: 716 | start_date = now - timedelta(days=n) 717 | return f"{start_date.strftime('%Y年%m月%d日')}至{now.strftime('%Y年%m月%d日')}" 718 | 719 | @staticmethod 720 | def get_recent_n_complete_year(now: datetime, n: int) -> str: 721 | if now.month == 12 and now.day == 31: 722 | end_date = now 723 | else: 724 | end_date = datetime(now.year, 12, 31) - relativedelta(years=1) 725 | start_date = end_date - relativedelta(years=n) + timedelta(days=1) 726 | return f"{start_date.strftime('%Y年%m月%d日')}至{end_date.strftime('%Y年%m月%d日')}" 727 | 728 | @staticmethod 729 | def get_recent_n_complete_month(now: datetime, n: int) -> str: 730 | current_month = now.month 731 | current_year = now.year 732 | if current_month > 2: 733 | start_month = current_month - 2 734 | start_year = current_year 735 | else: 736 | start_month = 12 + (current_month - 2) 737 | start_year = current_year - 1 738 | 739 | start_date = datetime(start_year, start_month, 1) 740 | 741 | end_month = current_month - 1 742 | end_year = current_year 743 | 744 | if end_month == 0: 745 | end_month = 12 746 | end_year -= 1 747 | 748 | end_date = datetime(end_year, end_month, calendar.monthrange(end_year, end_month)[1]) 749 | 750 | return f"{start_date.strftime('%Y年%m月%d日')}至{end_date.strftime('%Y年%m月%d日')}" 751 | 752 | @staticmethod 753 | def get_recent_n_complete_quarter(now: datetime, n: int) -> str: 754 | if now.month % 3 == 0 and now.day == 31: 755 | end_date = now 756 | else: 757 | if now.month < 4: 758 | end_date = datetime(now.year - 1, 12, 31) 759 | elif now.month < 7: 760 | end_date = datetime(now.year, 3, 31) 761 | elif now.month < 10: 762 | end_date = datetime(now.year, 6, 30) 763 | else: 764 | end_date = datetime(now.year, 9, 30) 765 | 766 | start_date = end_date - relativedelta(months=n * 3) + timedelta(days=2) 767 | return f"{start_date.strftime('%Y年%m月%d日')}至{end_date.strftime('%Y年%m月%d日')}" 768 | 769 | @staticmethod 770 | def get_recent_n_complete_week(now: datetime, n: int) -> str: 771 | if now.weekday() == 6: # Sunday 772 | end_date = now 773 | else: 774 | end_date = now - timedelta(weeks=1) + timedelta(days=(6 - now.weekday())) 775 | 776 | start_date = end_date - timedelta(weeks=n) + timedelta(days=1) 777 | return f"{start_date.strftime('%Y年%m月%d日')}至{end_date.strftime('%Y年%m月%d日')}" 778 | 779 | @staticmethod 780 | def get_recent_n_day_without_today(now: datetime, n: int) -> str: 781 | start_date = now - timedelta(days=n) 782 | end_date = now - timedelta(days=1) 783 | return f"{start_date.strftime('%Y年%m月%d日')}至{end_date.strftime('%Y年%m月%d日')}" 784 | 785 | @staticmethod 786 | def get_recent_n_quarter_with_current(now: datetime, n: int) -> str: 787 | if now.month < 4: 788 | end_date = datetime(now.year, 3, 31) 789 | elif now.month < 7: 790 | end_date = datetime(now.year, 6, 30) 791 | elif now.month < 10: 792 | end_date = datetime(now.year, 9, 30) 793 | else: 794 | end_date = datetime(now.year, 12, 31) 795 | 796 | start_date = end_date - relativedelta(months=n * 3 - 1) 797 | start_date = datetime(start_date.year, start_date.month, 1) 798 | return f"{start_date.strftime('%Y年%m月%d日')}至{end_date.strftime('%Y年%m月%d日')}" 799 | 800 | @staticmethod 801 | def get_month_last_day_ex(now: datetime, month_ex: str) -> str: 802 | month = now.month 803 | year = now.year 804 | if month_ex == "本月": 805 | next_month = month + 1 if month < 12 else 1 806 | next_year = year if month < 12 else year + 1 807 | first_of_next_month = datetime(year=next_year, month=next_month, day=1) 808 | last_day_of_this_month = first_of_next_month - relativedelta(days=1) 809 | comment = last_day_of_this_month.strftime('%Y年%m月%d日') 810 | elif month_ex == "上月": 811 | first_of_this_month = datetime(year=year, month=month, day=1) 812 | last_day_of_last_month = first_of_this_month - relativedelta(days=1) 813 | comment = last_day_of_last_month.strftime('%Y年%m月%d日') 814 | # if month_ex == "本月": 815 | # comment = (now + relativedelta(day=1, months=1, days=-1)).strftime('%Y年%m月%d日') 816 | 817 | return comment 818 | 819 | @staticmethod 820 | def get_general_year_month_last_day_ex(now: datetime, year_ex: str, month: int) -> str: 821 | year = now.year 822 | if year_ex == "去年": 823 | year -= 1 824 | elif year_ex == "前年": 825 | year -= 2 826 | elif year_ex == "明年": 827 | year += 1 828 | elif year_ex == "后年": 829 | year += 2 830 | 831 | comment = (datetime(year, month, 1) + relativedelta(months=1, days=-1)).strftime('%Y年%m月%d日') 832 | return comment 833 | 834 | @staticmethod 835 | def get_specific_year_half_year_ex(now: datetime, year: int, half_year_ex: str) -> str: 836 | if half_year_ex == "上": 837 | start_date = datetime(year, 1, 1) 838 | end_date = datetime(year, 6, 30) 839 | else: 840 | start_date = datetime(year, 7, 1) 841 | end_date = datetime(year, 12, 31) 842 | 843 | return f"{start_date.strftime('%Y年%m月%d日')}至{end_date.strftime('%Y年%m月%d日')}" 844 | 845 | @staticmethod 846 | def get_general_year_half_year_ex(now: datetime, year_ex: str, half_year_ex: str) -> str: 847 | year = now.year 848 | if year_ex == "去年": 849 | year -= 1 850 | elif year_ex == "前年": 851 | year -= 2 852 | elif year_ex == "明年": 853 | year += 1 854 | elif year_ex == "后年": 855 | year += 2 856 | return DateTimeUtil.get_specific_year_half_year_ex(now, year, half_year_ex) 857 | 858 | @staticmethod 859 | def main(): 860 | expressions = [ 861 | "2024年02月29日", 862 | # "2023年02月29日", 863 | # "24年02月29日", 864 | # "今年2月29日", 865 | # "去年02月29日", 866 | "今年02月29日", 867 | "去年02月28日", 868 | "前年02月28日", 869 | "明年02月28日", 870 | "后年02月28日", 871 | # "本月31日", 872 | "本月30日", 873 | "上月31日", 874 | "上上月30日", 875 | "下月30日", 876 | "上月今天", 877 | "上上月今天", 878 | "今天", 879 | "昨天", 880 | "前天", 881 | "明天", 882 | "后天", 883 | "本周第1天", 884 | "本月最后一天", 885 | "上月最后一天", 886 | "今年02月最后一天", 887 | "2024年02月", 888 | "今年02月", 889 | "去年02月", 890 | "前年02月", 891 | "明年02月", 892 | "后年02月", 893 | "本月", 894 | "上月", 895 | "上上月", 896 | "下月", 897 | "去年本月", 898 | "2023年", 899 | "今年", 900 | "去年", 901 | "前年", 902 | "明年", 903 | "后年", 904 | "2024年第1季度", 905 | "今年第1季度", 906 | "去年第1季度", 907 | "前年第1季度", 908 | "明年第1季度", 909 | "后年第1季度", 910 | "本季度", 911 | "上季度", 912 | "下季度", 913 | "去年本季度", 914 | "2024年上半年", 915 | "2024年下半年", 916 | "今年上半年", 917 | "今年下半年", 918 | "去年上半年", 919 | "去年下半年", 920 | "上半年", 921 | "下半年", 922 | "本周星期3", 923 | "上周星期3", 924 | "上上周星期3", 925 | "下周星期3", 926 | "下下周星期3", 927 | "本周", 928 | "上周", 929 | "上上周", 930 | "下周", 931 | "下下周", 932 | "2024年第01周", 933 | "今年第01周", 934 | "今年第53周", 935 | "去年第01周", 936 | "前年第01周", 937 | "本月第2周", 938 | "上月第1周", 939 | "2024年02月最后一周", 940 | "2023年02月最后一周", 941 | "本月最后一周", 942 | "上月最后一周", 943 | "上上月最后一周", 944 | "2024年02月第4周", 945 | "今年02月第4周", 946 | "去年02月第4周", 947 | "前年02月第4周", 948 | "2024年02月第3个完整周", 949 | "今年02月第3个完整周", 950 | "去年02月第3个完整周", 951 | "前年02月第3个完整周", 952 | "2024年第01个完整周", 953 | "今年第01个完整周", 954 | "去年第01个完整周", 955 | "前年第01个完整周", 956 | "本月第1个完整周", 957 | "上月第1个完整周", 958 | "近2年", 959 | "近3个月", 960 | "近3周", 961 | "近3天", 962 | "近2个完整年", 963 | "近2个完整季度", 964 | "近2个完整月", 965 | "近2个完整周", 966 | "不包含今天的近3天", 967 | "包含当前季度的近2个季度" 968 | ] 969 | 970 | # print(DateTimeUtil.build_date_time_comment(expressions)) 971 | 972 | @staticmethod 973 | def run(date_list): 974 | return DateTimeUtil.build_date_time_comment(date_list) 975 | 976 | 977 | if __name__ == "__main__": 978 | # DateTimeUtil.main() 979 | # DateTimeUtil.run() 980 | pass 981 | -------------------------------------------------------------------------------- /时间表达式.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/XGenerationLab/XiYan-DateResolver/1986cd3300c12877290c3793c90d2b544f98126e/时间表达式.xlsx --------------------------------------------------------------------------------