utils_func.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import os
  2. from hashlib import sha256, md5
  3. from datetime import datetime
  4. import requests
  5. def get_md5(file_path):
  6. data_md5 = None
  7. if os.path.isfile(file_path):
  8. f = open(file_path, 'rb')
  9. md5_obj = md5()
  10. md5_obj.update(f.read())
  11. hash_code = md5_obj.hexdigest()
  12. f.close()
  13. data_md5 = str(hash_code).lower()
  14. return data_md5
  15. def get_modified_time(file_path):
  16. # 获取文件最后修改的时间戳
  17. timestamp = os.path.getmtime(file_path)
  18. # 将时间戳转换为datetime对象,并格式化为指定格式的字符串
  19. modified_time = datetime.fromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M:%S')
  20. return modified_time
  21. def compare_two_times(time_str1, time_str2):
  22. # 定义时间格式
  23. time_format = "%Y-%m-%d %H:%M:%S"
  24. # 将时间字符串解析为datetime对象
  25. time1 = datetime.strptime(time_str1, time_format)
  26. time2 = datetime.strptime(time_str2, time_format)
  27. # 比较两个时间
  28. if time1 > time2:
  29. # print(f"{time_str1} 比 {time_str2} 新。")
  30. return "left_new"
  31. elif time1 < time2:
  32. # print(f"{time_str2} 比 {time_str1} 新。")
  33. return "right_new"
  34. else:
  35. # print("两个时间相等。")
  36. return "is_same"
  37. async def download_file(url, file_path):
  38. try:
  39. root_path, file_name = os.path.split(file_path)
  40. check_path(root_path)
  41. response = requests.get(url)
  42. _content = response.content
  43. with open(file_path, 'wb') as f:
  44. f.write(_content)
  45. print("下载成功:{}".format(file_path))
  46. except:
  47. print("下载失败:{}".format(file_path))
  48. def check_path(_path):
  49. if not os.path.exists(_path):
  50. # 创建多级目录
  51. os.makedirs(_path, exist_ok=True)
  52. # os.mkdir(_path)
  53. return True