python 时间 时间戳 相互转换 自用方法

245 阅读1分钟

获取当天的时间,并且格式化

import datetime 

>>> datetime.date.today().strftime("%Y%m%d")
'20200716'

>>> datetime.datetime.now()
datetime.datetime(2020, 7, 16, 14, 49, 33, 127588)

>>> datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
'2020-07-16 14:49:40'

时间格式字符串转换为时间戳

import time

def to_timestamp(s):
    time_array = time.strptime(s, "%Y%m%d")
    timestamp = int(time.mktime(time_array))
    return timestamp

>>> to_timestamp('20200103')
1577980800

时间戳转时间 这里需要判断时间戳是10位的还是13位的

def timestamp_to_date(timestamp):
    time_local = time.localtime(timestamp // 1000)
    dt = time.strftime("%Y-%m-%d", time_local)
    return dt

>>> timestamp_to_date(1577980800000)
'2020-01-03'

转换字符串格式

def change_time_format(s, old_format, new_format):
    arr = time.strptime(s, old_format)
    result = time.strftime(new_format, arr)
    return result