1 导入模块


  1. import time

2 睡眠


  • 用法:time.sleep(second)
    1. time.sleep(1)

3 取现行时间戳


  • 用法:time.time()
    1. start = time.time()
    2. print(start)

4 结构化时间


  • 结构化时间也称为:时间元组
    1. struct_time = time.struct_time(tm_year=年, tm_mon=月, tm_mday=日, tm_hour=时, tm_min=分, tm_sec=秒, tm_wday=星期, tm_yday=年第几天,tm_isdst=0)

5 时间戳转时间元组


  • 用法:time.localtime(时间戳)
    1. start_time = time.localtime(start)
    2. print(start_time)

6 时间元组转字符串


  • 用法:time.strftime(format,struct_time)
    1. str_time = time.strftime('%Y-%m-%d %H-%M-%S', time.localtime(time.time()))
    2. print(str_time)

6 字符串转时间元组


  • 用法:time.strptime(string,format)
    1. struct_time = time.strptime(str_time, '%Y-%m-%d %H-%M-%S')
    2. print(struct_time)

7 时间元组转时间戳


  • 用法:time.mktime(struct_time)
    1. end = time.mktime(start_time)
    2. print(end)

8 时间管理器


  1. class TimeManage:
  2. def init(self):
  3. self.localTime = 0
  4. self.start = 0
  5. self.end = 0
  6. self.startTime = ''
  7. self.endTime = ''
  8. self.startEnd = ''
  9. while True:
  10. self.task = input('请输入任务名称:')
  11. if self.task != '':
  12. break
  13. else:
  14. print('任务名称不能为空!')
  15. while True:
  16. try:
  17. self.setTime = int(input('你认为可以专注多少时间(min):'))
  18. break
  19. except ValueError:
  20. print('请输入数字!')
  21. self.print_info()
  22. self.start_task()
  23. self.end_task()
  24. def print_info(self):
  25. print('----------任务信息----------')
  26. print(f'任务名称:{self.task}')
  27. print(f'专注时间:{self.setTime}分钟')
  28. input('按回车开始任务:')
  29. def start_task(self):
  30. self.start = time.time()
  31. self.startTime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(self.start))
  32. for i in range(self.setTime * 60, 0, -1):
  33. info = '请专注任务,还要保持专注 ' + str(i) + ' 秒哦!'
  34. print(info, end='')
  35. time.sleep(1)
  36. print("\b" * (len(info)), end='', flush=True)
  37. print(f'你已经专注了{self.setTime}分钟了,再接再厉,完成任务!')
  38. while True:
  39. if input('输入y,结束任务:') == 'y':
  40. break
  41. def end_task(self):
  42. self.end = time.time()
  43. self.endTime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(self.end))
  44. self.localTime = int((self.end - self.start) / 60)
  45. self.startEnd = self.startTime + '--' + self.endTime
  46. with open('记事本.txt', 'a', encoding='utf-8') as f:
  47. f.write(f'任务名称:{self.task}\n专注时间:{self.localTime}分钟\n开始时间:{self.startEnd}\n')
  48. print('任务结束!该任务已被记录到【记事本】!')
  49. manage = TimeManage()

参考文件


time模块.py