[Python] 时间戳转换

# -*- coding: UTF-8 -*-
import time


'''
常规时间转换为时间戳
'''
test1 = '2019-8-01 00:00:00'
def localtime2timestamp(time_sj):                #传入单个时间比如'2019-8-01 00:00:00',类型为str
    data_sj = time.strptime(time_sj,"%Y-%m-%d %H:%M:%S")       #定义格式
    time_int = int(time.mktime(data_sj))
    return time_int             #返回传入时间的时间戳,类型为int
'''
时间戳转换年月日时间格式
'''
test2 = 1564588800
def timestamp2localtime(time_sj):     #传入参数
    data_sj = time.localtime(time_sj)
    time_str = time.strftime("%Y-%m-%d %H:%M:%S",data_sj)            #时间戳转换正常时间
    return time_str       #返回日期,格式为str



if __name__ == "__main__":
    # sqlite_read()
    test1 = '2022-8-01 00:00:00'
    test2 = 1669977515
    l1 = localtime2timestamp(test1)
    print(l1)
    
    t2 = timestamp2localtime(test2)
    print(t2)

你可能感兴趣的:(python)