python常用的时间转化

经常遇到,记不住,每次都要查,就很烦

  • 获取时间戳
    • time.time()
  • 时间加减:
    • datetime.timedelta(hours=8)
  • 时间戳 -> datetime:
    • datetime.datetime.fromtimestamp(time.time())
  • 字符串时间 -> time.struct_time:
    • time.strptime("Fri, 29 Oct 2021 08:52:40 GMT", "%a, %d %b %Y %H:%M:%S GMT")
  • 字符串时间 -> datetime:
    • datetime.datetime.strptime("Fri, 29 Oct 2021 08:52:40 GMT", "%a, %d %b %Y %H:%M:%S GMT")
  • time.struct_time -> 时间戳:
    • time.mktime(time.struct_time)
  • 时间戳 -> time.struct_time:
    • time.localtime(time.time())
  • datetime -> time.struct_time:
    • datetime.datetime(2021, 10, 29, 16, 52, 40).timetuple()
  • datetime -> 时间戳:
    • datetime.datetime(2021, 10, 29, 16, 52, 40).timestamp()
原文地址:https://www.cnblogs.com/pywjh/p/15481454.html