crawlo 1.0.2__py3-none-any.whl → 1.0.3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of crawlo might be problematic. Click here for more details.

Files changed (79) hide show
  1. crawlo/__init__.py +9 -6
  2. crawlo/__version__.py +1 -2
  3. crawlo/core/__init__.py +2 -2
  4. crawlo/core/engine.py +158 -158
  5. crawlo/core/processor.py +40 -40
  6. crawlo/core/scheduler.py +57 -59
  7. crawlo/crawler.py +242 -222
  8. crawlo/downloader/__init__.py +78 -78
  9. crawlo/downloader/aiohttp_downloader.py +259 -96
  10. crawlo/downloader/httpx_downloader.py +187 -48
  11. crawlo/downloader/playwright_downloader.py +160 -160
  12. crawlo/event.py +11 -11
  13. crawlo/exceptions.py +64 -64
  14. crawlo/extension/__init__.py +31 -31
  15. crawlo/extension/log_interval.py +49 -49
  16. crawlo/extension/log_stats.py +44 -44
  17. crawlo/filters/__init__.py +37 -37
  18. crawlo/filters/aioredis_filter.py +157 -129
  19. crawlo/filters/memory_filter.py +202 -203
  20. crawlo/filters/redis_filter.py +119 -119
  21. crawlo/items/__init__.py +62 -62
  22. crawlo/items/items.py +118 -118
  23. crawlo/middleware/__init__.py +21 -21
  24. crawlo/middleware/default_header.py +32 -32
  25. crawlo/middleware/download_delay.py +28 -28
  26. crawlo/middleware/middleware_manager.py +140 -140
  27. crawlo/middleware/request_ignore.py +30 -30
  28. crawlo/middleware/response_code.py +18 -18
  29. crawlo/middleware/response_filter.py +26 -26
  30. crawlo/middleware/retry.py +90 -90
  31. crawlo/network/__init__.py +7 -7
  32. crawlo/network/request.py +204 -233
  33. crawlo/network/response.py +166 -162
  34. crawlo/pipelines/__init__.py +13 -13
  35. crawlo/pipelines/console_pipeline.py +39 -39
  36. crawlo/pipelines/mongo_pipeline.py +116 -116
  37. crawlo/pipelines/mysql_batch_pipline.py +133 -133
  38. crawlo/pipelines/mysql_pipeline.py +195 -195
  39. crawlo/pipelines/pipeline_manager.py +56 -56
  40. crawlo/settings/__init__.py +7 -7
  41. crawlo/settings/default_settings.py +93 -89
  42. crawlo/settings/setting_manager.py +99 -99
  43. crawlo/spider/__init__.py +36 -36
  44. crawlo/stats_collector.py +59 -47
  45. crawlo/subscriber.py +106 -106
  46. crawlo/task_manager.py +27 -27
  47. crawlo/templates/item_template.tmpl +21 -21
  48. crawlo/templates/project_template/main.py +32 -32
  49. crawlo/templates/project_template/setting.py +189 -189
  50. crawlo/templates/spider_template.tmpl +30 -30
  51. crawlo/utils/__init__.py +7 -7
  52. crawlo/utils/concurrency_manager.py +124 -124
  53. crawlo/utils/date_tools.py +177 -177
  54. crawlo/utils/func_tools.py +82 -82
  55. crawlo/utils/log.py +39 -39
  56. crawlo/utils/pqueue.py +173 -173
  57. crawlo/utils/project.py +59 -59
  58. crawlo/utils/request.py +122 -85
  59. crawlo/utils/system.py +11 -11
  60. crawlo/utils/tools.py +302 -302
  61. crawlo/utils/url.py +39 -39
  62. {crawlo-1.0.2.dist-info → crawlo-1.0.3.dist-info}/METADATA +48 -48
  63. crawlo-1.0.3.dist-info/RECORD +80 -0
  64. {crawlo-1.0.2.dist-info → crawlo-1.0.3.dist-info}/top_level.txt +1 -0
  65. tests/__init__.py +7 -0
  66. tests/baidu_spider/__init__.py +7 -0
  67. tests/baidu_spider/demo.py +94 -0
  68. tests/baidu_spider/items.py +25 -0
  69. tests/baidu_spider/middleware.py +49 -0
  70. tests/baidu_spider/pipeline.py +55 -0
  71. tests/baidu_spider/request_fingerprints.txt +9 -0
  72. tests/baidu_spider/run.py +27 -0
  73. tests/baidu_spider/settings.py +78 -0
  74. tests/baidu_spider/spiders/__init__.py +7 -0
  75. tests/baidu_spider/spiders/bai_du.py +61 -0
  76. tests/baidu_spider/spiders/sina.py +79 -0
  77. crawlo-1.0.2.dist-info/RECORD +0 -68
  78. {crawlo-1.0.2.dist-info → crawlo-1.0.3.dist-info}/WHEEL +0 -0
  79. {crawlo-1.0.2.dist-info → crawlo-1.0.3.dist-info}/entry_points.txt +0 -0
@@ -1,125 +1,125 @@
1
- import os
2
- import platform
3
- import logging
4
- from typing import Optional
5
-
6
- try:
7
- import psutil # 用于获取系统资源信息的第三方库
8
- except ImportError:
9
- psutil = None # 如果psutil不可用则设为None
10
-
11
- logger = logging.getLogger(__name__)
12
-
13
-
14
- def calculate_optimal_concurrency(user_specified: Optional[int] = None, use_logical_cores: bool = True) -> int:
15
- """
16
- 基于系统资源计算最优并发数,或使用用户指定值
17
-
18
- 参数:
19
- user_specified: 用户指定的并发数(优先使用)
20
- use_logical_cores: 是否使用逻辑CPU核心数(超线程),默认为True
21
-
22
- 返回:
23
- 计算得出的最优并发数
24
-
25
- 说明:
26
- 1. 优先使用用户指定的并发数
27
- 2. 根据操作系统类型采用不同的计算策略:
28
- - Windows: 保守计算,避免内存压力
29
- - macOS: 平衡资源使用
30
- - Linux: 充分利用服务器资源
31
- - 其他系统: 使用合理默认值
32
- 3. 使用可用内存和CPU核心数进行计算
33
- 4. 提供psutil不可用时的备用方案
34
- """
35
- # 优先使用用户指定的并发数
36
- if user_specified is not None:
37
- logger.info(f"使用用户指定的并发数: {user_specified}")
38
- return user_specified
39
-
40
- try:
41
- current_os = platform.system() # 获取当前操作系统类型
42
- logger.debug(f"检测到操作系统: {current_os}")
43
-
44
- # 获取CPU核心数(根据参数决定是否使用逻辑核心)
45
- cpu_count = psutil.cpu_count(logical=use_logical_cores) or 1 if psutil else os.cpu_count() or 1
46
-
47
- # 根据操作系统类型选择不同的计算方法
48
- if current_os == "Windows":
49
- concurrency = _get_concurrency_for_windows(cpu_count, use_logical_cores)
50
- elif current_os == "Darwin": # macOS系统
51
- concurrency = _get_concurrency_for_macos(cpu_count, use_logical_cores)
52
- elif current_os == "Linux":
53
- concurrency = _get_concurrency_for_linux(cpu_count, use_logical_cores)
54
- else: # 其他操作系统
55
- concurrency = _get_concurrency_default(cpu_count)
56
-
57
- logger.info(f"计算得到最大并发数: {concurrency}")
58
- return concurrency
59
-
60
- except Exception as e:
61
- logger.warning(f"动态计算并发数失败: {str(e)},使用默认值50")
62
- return 50 # 计算失败时的安全默认值
63
-
64
-
65
- def _get_concurrency_for_windows(cpu_count: int, use_logical_cores: bool) -> int:
66
- """Windows系统专用的并发数计算逻辑"""
67
- if psutil:
68
- # 计算可用内存(GB)
69
- available_memory = psutil.virtual_memory().available / (1024 ** 3)
70
- # 内存计算:每4GB可用内存分配10个并发
71
- mem_based = int((available_memory / 4) * 10)
72
- # CPU计算:使用逻辑核心时乘数较大
73
- cpu_based = cpu_count * (5 if use_logical_cores else 3)
74
- # 取5-100之间的值,选择内存和CPU限制中较小的
75
- return max(5, min(100, mem_based, cpu_based))
76
- else:
77
- # 无psutil时的备用方案
78
- return min(50, cpu_count * 5)
79
-
80
-
81
- def _get_concurrency_for_macos(cpu_count: int, use_logical_cores: bool) -> int:
82
- """macOS系统专用的并发数计算逻辑"""
83
- if psutil:
84
- available_memory = psutil.virtual_memory().available / (1024 ** 3)
85
- # 内存计算:每3GB可用内存分配10个并发
86
- mem_based = int((available_memory / 3) * 10)
87
- # CPU计算:使用逻辑核心时乘数较大
88
- cpu_based = cpu_count * (6 if use_logical_cores else 4)
89
- # 取5-120之间的值
90
- return max(5, min(120, mem_based, cpu_based))
91
- else:
92
- try:
93
- # macOS备用方案:使用系统命令获取物理CPU核心数
94
- import subprocess
95
- output = subprocess.check_output(["sysctl", "hw.physicalcpu"])
96
- cpu_count = int(output.split()[1])
97
- return min(60, cpu_count * 5)
98
- except:
99
- return 40 # Mac电脑的合理默认值
100
-
101
-
102
- def _get_concurrency_for_linux(cpu_count: int, use_logical_cores: bool) -> int:
103
- """Linux系统专用的并发数计算逻辑(更激进)"""
104
- if psutil:
105
- available_memory = psutil.virtual_memory().available / (1024 ** 3)
106
- # 内存计算:每1.5GB可用内存分配10个并发
107
- mem_based = int((available_memory / 1.5) * 10)
108
- # CPU计算:服务器环境使用更大的乘数
109
- cpu_based = cpu_count * (8 if use_logical_cores else 5)
110
- # 取5-200之间的值
111
- return max(5, min(200, mem_based, cpu_based))
112
- else:
113
- try:
114
- # Linux备用方案:解析/proc/cpuinfo文件
115
- with open("/proc/cpuinfo") as f:
116
- cpu_count = f.read().count("processor\t:")
117
- if cpu_count > 0:
118
- return min(200, cpu_count * 8)
119
- except:
120
- return 50 # Linux服务器的合理默认值
121
-
122
-
123
- def _get_concurrency_default(cpu_count: int) -> int:
124
- """未知操作系统的默认计算逻辑"""
1
+ import os
2
+ import platform
3
+ import logging
4
+ from typing import Optional
5
+
6
+ try:
7
+ import psutil # 用于获取系统资源信息的第三方库
8
+ except ImportError:
9
+ psutil = None # 如果psutil不可用则设为None
10
+
11
+ logger = logging.getLogger(__name__)
12
+
13
+
14
+ def calculate_optimal_concurrency(user_specified: Optional[int] = None, use_logical_cores: bool = True) -> int:
15
+ """
16
+ 基于系统资源计算最优并发数,或使用用户指定值
17
+
18
+ 参数:
19
+ user_specified: 用户指定的并发数(优先使用)
20
+ use_logical_cores: 是否使用逻辑CPU核心数(超线程),默认为True
21
+
22
+ 返回:
23
+ 计算得出的最优并发数
24
+
25
+ 说明:
26
+ 1. 优先使用用户指定的并发数
27
+ 2. 根据操作系统类型采用不同的计算策略:
28
+ - Windows: 保守计算,避免内存压力
29
+ - macOS: 平衡资源使用
30
+ - Linux: 充分利用服务器资源
31
+ - 其他系统: 使用合理默认值
32
+ 3. 使用可用内存和CPU核心数进行计算
33
+ 4. 提供psutil不可用时的备用方案
34
+ """
35
+ # 优先使用用户指定的并发数
36
+ if user_specified is not None:
37
+ logger.info(f"使用用户指定的并发数: {user_specified}")
38
+ return user_specified
39
+
40
+ try:
41
+ current_os = platform.system() # 获取当前操作系统类型
42
+ logger.debug(f"检测到操作系统: {current_os}")
43
+
44
+ # 获取CPU核心数(根据参数决定是否使用逻辑核心)
45
+ cpu_count = psutil.cpu_count(logical=use_logical_cores) or 1 if psutil else os.cpu_count() or 1
46
+
47
+ # 根据操作系统类型选择不同的计算方法
48
+ if current_os == "Windows":
49
+ concurrency = _get_concurrency_for_windows(cpu_count, use_logical_cores)
50
+ elif current_os == "Darwin": # macOS系统
51
+ concurrency = _get_concurrency_for_macos(cpu_count, use_logical_cores)
52
+ elif current_os == "Linux":
53
+ concurrency = _get_concurrency_for_linux(cpu_count, use_logical_cores)
54
+ else: # 其他操作系统
55
+ concurrency = _get_concurrency_default(cpu_count)
56
+
57
+ logger.info(f"计算得到最大并发数: {concurrency}")
58
+ return concurrency
59
+
60
+ except Exception as e:
61
+ logger.warning(f"动态计算并发数失败: {str(e)},使用默认值50")
62
+ return 50 # 计算失败时的安全默认值
63
+
64
+
65
+ def _get_concurrency_for_windows(cpu_count: int, use_logical_cores: bool) -> int:
66
+ """Windows系统专用的并发数计算逻辑"""
67
+ if psutil:
68
+ # 计算可用内存(GB)
69
+ available_memory = psutil.virtual_memory().available / (1024 ** 3)
70
+ # 内存计算:每4GB可用内存分配10个并发
71
+ mem_based = int((available_memory / 4) * 10)
72
+ # CPU计算:使用逻辑核心时乘数较大
73
+ cpu_based = cpu_count * (5 if use_logical_cores else 3)
74
+ # 取5-100之间的值,选择内存和CPU限制中较小的
75
+ return max(5, min(100, mem_based, cpu_based))
76
+ else:
77
+ # 无psutil时的备用方案
78
+ return min(50, cpu_count * 5)
79
+
80
+
81
+ def _get_concurrency_for_macos(cpu_count: int, use_logical_cores: bool) -> int:
82
+ """macOS系统专用的并发数计算逻辑"""
83
+ if psutil:
84
+ available_memory = psutil.virtual_memory().available / (1024 ** 3)
85
+ # 内存计算:每3GB可用内存分配10个并发
86
+ mem_based = int((available_memory / 3) * 10)
87
+ # CPU计算:使用逻辑核心时乘数较大
88
+ cpu_based = cpu_count * (6 if use_logical_cores else 4)
89
+ # 取5-120之间的值
90
+ return max(5, min(120, mem_based, cpu_based))
91
+ else:
92
+ try:
93
+ # macOS备用方案:使用系统命令获取物理CPU核心数
94
+ import subprocess
95
+ output = subprocess.check_output(["sysctl", "hw.physicalcpu"])
96
+ cpu_count = int(output.split()[1])
97
+ return min(60, cpu_count * 5)
98
+ except:
99
+ return 40 # Mac电脑的合理默认值
100
+
101
+
102
+ def _get_concurrency_for_linux(cpu_count: int, use_logical_cores: bool) -> int:
103
+ """Linux系统专用的并发数计算逻辑(更激进)"""
104
+ if psutil:
105
+ available_memory = psutil.virtual_memory().available / (1024 ** 3)
106
+ # 内存计算:每1.5GB可用内存分配10个并发
107
+ mem_based = int((available_memory / 1.5) * 10)
108
+ # CPU计算:服务器环境使用更大的乘数
109
+ cpu_based = cpu_count * (8 if use_logical_cores else 5)
110
+ # 取5-200之间的值
111
+ return max(5, min(200, mem_based, cpu_based))
112
+ else:
113
+ try:
114
+ # Linux备用方案:解析/proc/cpuinfo文件
115
+ with open("/proc/cpuinfo") as f:
116
+ cpu_count = f.read().count("processor\t:")
117
+ if cpu_count > 0:
118
+ return min(200, cpu_count * 8)
119
+ except:
120
+ return 50 # Linux服务器的合理默认值
121
+
122
+
123
+ def _get_concurrency_default(cpu_count: int) -> int:
124
+ """未知操作系统的默认计算逻辑"""
125
125
  return min(50, cpu_count * 5) # 保守的默认计算方式
@@ -1,177 +1,177 @@
1
- #!/usr/bin/python
2
- # -*- coding:UTF-8 -*-
3
- """
4
- # @Time : 2025-05-17 10:20
5
- # @Author : crawl-coder
6
- # @Desc : 时间工具
7
- """
8
- import dateparser
9
- from typing import Optional, Union
10
- from datetime import datetime, timedelta
11
- from dateutil.relativedelta import relativedelta
12
-
13
- # 常见时间格式列表
14
- COMMON_FORMATS = [
15
- "%Y-%m-%d %H:%M:%S",
16
- "%Y/%m/%d %H:%M:%S",
17
- "%d-%m-%Y %H:%M:%S",
18
- "%d/%m/%Y %H:%M:%S",
19
- "%Y-%m-%d",
20
- "%Y/%m/%d",
21
- "%d-%m-%Y",
22
- "%d/%m/%Y",
23
- "%b %d, %Y", # Jan 01, 2023
24
- "%B %d, %Y", # January 01, 2023
25
- "%Y年%m月%d日", # 2023年01月01日
26
- "%Y年%m月%d日 %H时%M分%S秒", # 2023年01月01日 12时30分45秒
27
- "%a %b %d %H:%M:%S %Y", # Wed Jan 01 12:00:00 2020
28
- "%a, %d %b %Y %H:%M:%S", # Wed, 01 Jan 2020 12:00:00
29
- "%Y-%m-%dT%H:%M:%S.%f", # ✅ 新增:ISO 8601 格式(带毫秒)
30
- ]
31
-
32
-
33
- def normalize_time(time_str: str) -> Optional[datetime]:
34
- """
35
- 尝试使用常见格式解析时间字符串。
36
-
37
- :param time_str: 时间字符串(如 "2023-01-01 12:00:00")
38
- :return: 解析成功返回 datetime 对象,失败返回 None 或抛出异常(可选)
39
- """
40
- for fmt in COMMON_FORMATS:
41
- try:
42
- return datetime.strptime(time_str, fmt)
43
- except ValueError:
44
- continue
45
- raise ValueError(f"无法解析时间字符串:{time_str}")
46
-
47
-
48
- def get_current_time(fmt: str = '%Y-%m-%d %H:%M:%S'):
49
- """
50
- 获取当前时间,根据是否传入格式化参数决定返回类型
51
- :param fmt: 格式化字符串,如 "%Y-%m-%d %H:%M:%S"
52
- :return: datetime 或 str
53
- """
54
- dt = datetime.now()
55
- if fmt is not None:
56
- return dt.strftime(fmt)
57
- return dt
58
-
59
-
60
- def time_diff_seconds(start_time: str, end_time: str, fmt: str = '%Y-%m-%d %H:%M:%S'):
61
- """
62
- 计算两个时间字符串之间的秒数差。
63
-
64
- :param start_time: 起始时间字符串
65
- :param end_time: 结束时间字符串
66
- :param fmt: 时间格式,默认为 '%Y-%m-%d %H:%M:%S'
67
- :return: 秒数差(总是正整数)
68
- """
69
- start = datetime.strptime(start_time, fmt)
70
- end = datetime.strptime(end_time, fmt)
71
- delta = end - start
72
- return int(delta.total_seconds())
73
-
74
-
75
- TimeType = Union[str, datetime]
76
-
77
-
78
- def time_diff(start: TimeType, end: TimeType, fmt: str = None, unit='seconds', auto_parse=True) -> Optional[int]:
79
- """
80
- 计算两个时间之间的差值(支持字符串或 datetime)。
81
-
82
- :param start: 起始时间(字符串或 datetime)
83
- :param end: 结束时间(字符串或 datetime)
84
- :param fmt: 时间格式(如果传入字符串且 auto_parse=False 时需要)
85
- :param unit: 单位(seconds, minutes, hours, days)
86
- :param auto_parse: 是否自动尝试解析任意格式的字符串(推荐开启)
87
- :return: 差值整数(根据 unit 返回),失败返回 None
88
- """
89
-
90
- def ensure_datetime(t):
91
- if isinstance(t, datetime):
92
- return t
93
- elif isinstance(t, str):
94
- if auto_parse:
95
- parsed = normalize_time(t)
96
- if parsed:
97
- return parsed
98
- if fmt:
99
- return datetime.strptime(t, fmt)
100
- raise ValueError("字符串时间未提供格式,或无法自动解析")
101
- else:
102
- raise TypeError(f"不支持的时间类型: {type(t)}")
103
-
104
- start_dt = ensure_datetime(start)
105
- end_dt = ensure_datetime(end)
106
-
107
- delta = (end_dt - start_dt)
108
- abs_seconds = int(abs(delta.total_seconds()))
109
-
110
- if unit == 'seconds':
111
- return abs_seconds
112
- elif unit == 'minutes':
113
- return abs_seconds // 60
114
- elif unit == 'hours':
115
- return abs_seconds // 3600
116
- elif unit == 'days':
117
- return abs_seconds // 86400
118
- else:
119
- raise ValueError(f"Unsupported unit: {unit}")
120
-
121
-
122
- def format_datetime(dt, fmt="%Y-%m-%d %H:%M:%S"):
123
- """格式化时间"""
124
- return dt.strftime(fmt)
125
-
126
-
127
- def parse_datetime(s, fmt="%Y-%m-%d %H:%M:%S"):
128
- """将字符串解析为 datetime 对象"""
129
- return datetime.strptime(s, fmt)
130
-
131
-
132
- def datetime_to_timestamp(dt):
133
- """将 datetime 转换为时间戳"""
134
- return dt.timestamp()
135
-
136
-
137
- def timestamp_to_datetime(ts):
138
- """将时间戳转换为 datetime"""
139
- return datetime.fromtimestamp(ts)
140
-
141
-
142
- def add_days(dt, days=0):
143
- """日期加减(天)"""
144
- return dt + timedelta(days=days)
145
-
146
-
147
- def add_months(dt, months=0):
148
- """日期加减(月)"""
149
- return dt + relativedelta(months=months)
150
-
151
-
152
- def days_between(dt1, dt2):
153
- """计算两个日期之间的天数差"""
154
- return abs((dt2 - dt1).days)
155
-
156
-
157
- def is_leap_year(year):
158
- """判断是否是闰年"""
159
- return (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)
160
-
161
-
162
- def parse_relative_time(time_str: str) -> str:
163
- """
164
- 解析相对时间字符串(如 "3分钟前"、"昨天")为 datetime 对象。
165
- """
166
- dt = dateparser.parse(time_str)
167
- return dt.isoformat()
168
-
169
-
170
- if __name__ == '__main__':
171
- print(normalize_time(parse_relative_time("30分钟前")))
172
- print(parse_relative_time("昨天"))
173
- print(parse_relative_time("10小时前"))
174
- print(parse_relative_time("1个月前"))
175
- print(parse_relative_time("10天前"))
176
- print(parse_relative_time("2024年1月1日"))
177
- print(parse_relative_time('2025年5月30日'))
1
+ #!/usr/bin/python
2
+ # -*- coding:UTF-8 -*-
3
+ """
4
+ # @Time : 2025-05-17 10:20
5
+ # @Author : crawl-coder
6
+ # @Desc : 时间工具
7
+ """
8
+ import dateparser
9
+ from typing import Optional, Union
10
+ from datetime import datetime, timedelta
11
+ from dateutil.relativedelta import relativedelta
12
+
13
+ # 常见时间格式列表
14
+ COMMON_FORMATS = [
15
+ "%Y-%m-%d %H:%M:%S",
16
+ "%Y/%m/%d %H:%M:%S",
17
+ "%d-%m-%Y %H:%M:%S",
18
+ "%d/%m/%Y %H:%M:%S",
19
+ "%Y-%m-%d",
20
+ "%Y/%m/%d",
21
+ "%d-%m-%Y",
22
+ "%d/%m/%Y",
23
+ "%b %d, %Y", # Jan 01, 2023
24
+ "%B %d, %Y", # January 01, 2023
25
+ "%Y年%m月%d日", # 2023年01月01日
26
+ "%Y年%m月%d日 %H时%M分%S秒", # 2023年01月01日 12时30分45秒
27
+ "%a %b %d %H:%M:%S %Y", # Wed Jan 01 12:00:00 2020
28
+ "%a, %d %b %Y %H:%M:%S", # Wed, 01 Jan 2020 12:00:00
29
+ "%Y-%m-%dT%H:%M:%S.%f", # ✅ 新增:ISO 8601 格式(带毫秒)
30
+ ]
31
+
32
+
33
+ def normalize_time(time_str: str) -> Optional[datetime]:
34
+ """
35
+ 尝试使用常见格式解析时间字符串。
36
+
37
+ :param time_str: 时间字符串(如 "2023-01-01 12:00:00")
38
+ :return: 解析成功返回 datetime 对象,失败返回 None 或抛出异常(可选)
39
+ """
40
+ for fmt in COMMON_FORMATS:
41
+ try:
42
+ return datetime.strptime(time_str, fmt)
43
+ except ValueError:
44
+ continue
45
+ raise ValueError(f"无法解析时间字符串:{time_str}")
46
+
47
+
48
+ def get_current_time(fmt: str = '%Y-%m-%d %H:%M:%S'):
49
+ """
50
+ 获取当前时间,根据是否传入格式化参数决定返回类型
51
+ :param fmt: 格式化字符串,如 "%Y-%m-%d %H:%M:%S"
52
+ :return: datetime 或 str
53
+ """
54
+ dt = datetime.now()
55
+ if fmt is not None:
56
+ return dt.strftime(fmt)
57
+ return dt
58
+
59
+
60
+ def time_diff_seconds(start_time: str, end_time: str, fmt: str = '%Y-%m-%d %H:%M:%S'):
61
+ """
62
+ 计算两个时间字符串之间的秒数差。
63
+
64
+ :param start_time: 起始时间字符串
65
+ :param end_time: 结束时间字符串
66
+ :param fmt: 时间格式,默认为 '%Y-%m-%d %H:%M:%S'
67
+ :return: 秒数差(总是正整数)
68
+ """
69
+ start = datetime.strptime(start_time, fmt)
70
+ end = datetime.strptime(end_time, fmt)
71
+ delta = end - start
72
+ return int(delta.total_seconds())
73
+
74
+
75
+ TimeType = Union[str, datetime]
76
+
77
+
78
+ def time_diff(start: TimeType, end: TimeType, fmt: str = None, unit='seconds', auto_parse=True) -> Optional[int]:
79
+ """
80
+ 计算两个时间之间的差值(支持字符串或 datetime)。
81
+
82
+ :param start: 起始时间(字符串或 datetime)
83
+ :param end: 结束时间(字符串或 datetime)
84
+ :param fmt: 时间格式(如果传入字符串且 auto_parse=False 时需要)
85
+ :param unit: 单位(seconds, minutes, hours, days)
86
+ :param auto_parse: 是否自动尝试解析任意格式的字符串(推荐开启)
87
+ :return: 差值整数(根据 unit 返回),失败返回 None
88
+ """
89
+
90
+ def ensure_datetime(t):
91
+ if isinstance(t, datetime):
92
+ return t
93
+ elif isinstance(t, str):
94
+ if auto_parse:
95
+ parsed = normalize_time(t)
96
+ if parsed:
97
+ return parsed
98
+ if fmt:
99
+ return datetime.strptime(t, fmt)
100
+ raise ValueError("字符串时间未提供格式,或无法自动解析")
101
+ else:
102
+ raise TypeError(f"不支持的时间类型: {type(t)}")
103
+
104
+ start_dt = ensure_datetime(start)
105
+ end_dt = ensure_datetime(end)
106
+
107
+ delta = (end_dt - start_dt)
108
+ abs_seconds = int(abs(delta.total_seconds()))
109
+
110
+ if unit == 'seconds':
111
+ return abs_seconds
112
+ elif unit == 'minutes':
113
+ return abs_seconds // 60
114
+ elif unit == 'hours':
115
+ return abs_seconds // 3600
116
+ elif unit == 'days':
117
+ return abs_seconds // 86400
118
+ else:
119
+ raise ValueError(f"Unsupported unit: {unit}")
120
+
121
+
122
+ def format_datetime(dt, fmt="%Y-%m-%d %H:%M:%S"):
123
+ """格式化时间"""
124
+ return dt.strftime(fmt)
125
+
126
+
127
+ def parse_datetime(s, fmt="%Y-%m-%d %H:%M:%S"):
128
+ """将字符串解析为 datetime 对象"""
129
+ return datetime.strptime(s, fmt)
130
+
131
+
132
+ def datetime_to_timestamp(dt):
133
+ """将 datetime 转换为时间戳"""
134
+ return dt.timestamp()
135
+
136
+
137
+ def timestamp_to_datetime(ts):
138
+ """将时间戳转换为 datetime"""
139
+ return datetime.fromtimestamp(ts)
140
+
141
+
142
+ def add_days(dt, days=0):
143
+ """日期加减(天)"""
144
+ return dt + timedelta(days=days)
145
+
146
+
147
+ def add_months(dt, months=0):
148
+ """日期加减(月)"""
149
+ return dt + relativedelta(months=months)
150
+
151
+
152
+ def days_between(dt1, dt2):
153
+ """计算两个日期之间的天数差"""
154
+ return abs((dt2 - dt1).days)
155
+
156
+
157
+ def is_leap_year(year):
158
+ """判断是否是闰年"""
159
+ return (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)
160
+
161
+
162
+ def parse_relative_time(time_str: str) -> str:
163
+ """
164
+ 解析相对时间字符串(如 "3分钟前"、"昨天")为 datetime 对象。
165
+ """
166
+ dt = dateparser.parse(time_str)
167
+ return dt.isoformat()
168
+
169
+
170
+ if __name__ == '__main__':
171
+ print(normalize_time(parse_relative_time("30分钟前")))
172
+ print(parse_relative_time("昨天"))
173
+ print(parse_relative_time("10小时前"))
174
+ print(parse_relative_time("1个月前"))
175
+ print(parse_relative_time("10天前"))
176
+ print(parse_relative_time("2024年1月1日"))
177
+ print(parse_relative_time('2025年5月30日'))