general.py 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  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"""
  41. now = datetime.now().strftime('%Y%m%d%H%M%S%f')[:-3]
  42. return f'{now}{randint(100000, 999999)}'
  43. def get_x_day_ago_timestamp(x_days_ago: int = 0, length: Literal[13, 10] = 13):
  44. now = datetime.now()
  45. yesterday = now - timedelta(days=x_days_ago)
  46. yesterday_midnight = yesterday.replace(hour=0, minute=0, second=0, microsecond=0)
  47. if length == 10:
  48. return int(yesterday_midnight.timestamp())
  49. else:
  50. return int(yesterday_midnight.timestamp() * 1000)
  51. def get_file_size(file_path):
  52. with open(file_path, 'rb') as f:
  53. return len(f.read())
  54. def cookie_str_to_json(cookie: str) -> dict:
  55. components = cookie.strip().split(';')
  56. short_parsed_request = {component.split('=')[0].strip(): component.split('=')[1].strip() for component in components if
  57. '=' in component}
  58. return short_parsed_request
  59. def get_day_timestamp(day):
  60. now = datetime.now()
  61. yesterday = now - timedelta(days=day)
  62. yesterday_midnight = yesterday.replace(hour=0, minute=0, second=0, microsecond=0)
  63. timestamp_yesterday_midnight_ms = int(yesterday_midnight.timestamp())
  64. return timestamp_yesterday_midnight_ms
  65. def str_digital_to_int(v: str) -> int:
  66. """将带有+、k、w字符的数据类字符串转为int"""
  67. v = v.rstrip('+')
  68. unit = v[-1]
  69. if unit in _STR_DIGITAL_MAP:
  70. v = float(v.rstrip(unit)) * _STR_DIGITAL_MAP[unit]
  71. else:
  72. v = float(v)
  73. return int(v)
  74. def datetime_to_timestamp(time_str:str):
  75. dt = datetime.strptime(time_str, "%Y-%m-%d %H:%M:%S")
  76. # 转换为时间戳
  77. timestamp = int(dt.timestamp())*1000
  78. return timestamp
  79. if __name__ == '__main__':
  80. print(datetime_to_timestamp("2024-10-30 19:05:56"))