general.py 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. import os
  2. import re
  3. from datetime import datetime, timedelta
  4. from pathlib import Path
  5. from random import randint
  6. from typing import Any, List, Literal, Optional, Tuple
  7. _STR_DIGITAL_MAP = {
  8. 'k': 1e3,
  9. '千': 1e3,
  10. 'w': 1e4,
  11. '万': 1e4,
  12. '亿': 1e8,
  13. }
  14. def get_root_dir() -> str:
  15. """获取项目根目录的绝对路径"""
  16. current_path = Path(__file__).resolve()
  17. root_path = current_path.parent if not current_path.is_dir() else current_path
  18. while True:
  19. if 'requirements.txt' in os.listdir(root_path):
  20. return str(root_path.absolute())
  21. root_path = root_path.parent
  22. def get_abs_path(relative_path: str) -> str:
  23. """获取目标文件或目录的相对路径在系统中的绝对路径"""
  24. return os.path.join(get_root_dir(), relative_path)
  25. def get_now_ts(length: Literal[10, 13] = 13) -> int:
  26. """获取当前时间的10位或13位时间戳"""
  27. now_ts = datetime.now().timestamp()
  28. if length == 10:
  29. return int(now_ts)
  30. else:
  31. return int(now_ts * 1000)
  32. def pascal_to_snake(pascal_str: str) -> str:
  33. """将Pascal字符串转为蛇形字符串"""
  34. snake_str = re.sub(r'([a-z])([A-Z])', r'\1_\2', pascal_str)
  35. return snake_str.lower()
  36. def snake_to_pascal(snake_str: str) -> str:
  37. """将蛇形字符串转为Pascal字符串"""
  38. return ''.join([item.title() for item in snake_str.split('_')])
  39. def generate_task_id():
  40. """生成task_id(包含日期时间,36字符)"""
  41. import uuid
  42. # 日期时间部分:YYYYMMDDHHMMSS(14位)
  43. datetime_part = datetime.now().strftime('%Y%m%d%H%M%S')
  44. # UUID 部分:取 UUID 的后 22 位(去掉连字符)
  45. uuid_part = str(uuid.uuid4()).replace('-', '')[-22:]
  46. # 组合:14 + 22 = 36 字符
  47. return f'{datetime_part}{uuid_part}'
  48. def get_x_day_ago_timestamp(x_days_ago: int = 0, length: Literal[13, 10] = 13):
  49. now = datetime.now()
  50. yesterday = now - timedelta(days=x_days_ago)
  51. yesterday_midnight = yesterday.replace(hour=0, minute=0, second=0, microsecond=0)
  52. if length == 10:
  53. return int(yesterday_midnight.timestamp())
  54. else:
  55. return int(yesterday_midnight.timestamp() * 1000)
  56. def get_file_size(file_path):
  57. with open(file_path, 'rb') as f:
  58. return len(f.read())
  59. def cookie_str_to_json(cookie: str) -> dict:
  60. components = cookie.strip().split(';')
  61. short_parsed_request = {component.split('=')[0].strip(): component.split('=')[1].strip() for component in components if
  62. '=' in component}
  63. return short_parsed_request
  64. def get_day_timestamp(day):
  65. now = datetime.now()
  66. yesterday = now - timedelta(days=day)
  67. yesterday_midnight = yesterday.replace(hour=0, minute=0, second=0, microsecond=0)
  68. timestamp_yesterday_midnight_ms = int(yesterday_midnight.timestamp())
  69. return timestamp_yesterday_midnight_ms
  70. def str_digital_to_int(v: str) -> int:
  71. """将带有+、k、w字符的数据类字符串转为int"""
  72. v = v.rstrip('+')
  73. unit = v[-1]
  74. if unit in _STR_DIGITAL_MAP:
  75. v = float(v.rstrip(unit)) * _STR_DIGITAL_MAP[unit]
  76. else:
  77. v = float(v)
  78. return int(v)
  79. def datetime_to_timestamp(time_str:str):
  80. dt = datetime.strptime(time_str, "%Y-%m-%d %H:%M:%S")
  81. # 转换为时间戳
  82. timestamp = int(dt.timestamp())*1000
  83. return timestamp
  84. if __name__ == '__main__':
  85. print(datetime_to_timestamp("2024-10-30 19:05:56"))