python实现时间戳与字符串互转

一. 字符串转时间戳

  • 方法一:datetime
from datetime import datetime

str_time = '2022-08-06 17:12:35'
int(datetime.strptime(str_time, "%Y-%m-%d %H:%M:%S").timestamp())
# datetime.strptime()将对应格式的字符串转换成datetime日期格式:datetime.datetime(2022, 8, 6, 17, 12, 35)
  • 方法二:time
import time

str_time = '2022-08-06 17:12:35'
int(time.mktime(time.strptime(str_time,"%Y-%m-%d %H:%M:%S")))
# time.strptime()将对应格式的字符串转换为时间元组:time.struct_time(tm_year=2022, tm_mon=8, tm_mday=6, tm_hour=17, tm_min=12, tm_sec=35, tm_wday=5, tm_yday=218, tm_isdst=-1)
# time.mktime()将时间元组转换成时间戳

二. 时间戳转字符串

  • 方法一:datetime
from datetime import datetime

timeStamp= 1659777155
datetime.fromtimestamp(timeStamp).strftime("%Y-%m-%d %H:%M:%S")
# datetime.fromtimestamp()将时间戳转为datetime日期格式
  • 方法二:time
import time

timeStamp= 1659777155
time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(timeStamp))
# time.localtime()将时间戳转换为时间元组
# time.strftime()将时间元组转换成对应格式的字符串

你可能感兴趣的:(python)