Python 关于时间戳的转化格式记录

#datetime格式转标准字符串

import datetime
import time
# datetime.timedelta(hours=8)  # 根据自己当前时间判定是否需要 + 8 个小时时区
# strftime 格式化时间字符串,strptime 字符串转换(解析)为指定时间类型
start = datetime.datetime.strftime(datetime.datetime(2020, 9, 8, 20, 17, 44, 447429), "%Y-%m-%d %H:%M:%S")
start = datetime.datetime.strptime(start, "%Y-%m-%d %H:%M:%S") + datetime.timedelta(hours=8)
print(start)
end = datetime.datetime.strftime(datetime.datetime(2020, 9, 9, 0, 17, 45, 545916), "%Y-%m-%d %H:%M:%S")
end = datetime.datetime.strptime(end, "%Y-%m-%d %H:%M:%S") + datetime.timedelta(hours=8)
print(end)
print(round(((end-start).seconds)/60))
#输出
2020-09-09 04:17:44
2020-09-09 08:17:45
240

#时间戳转标准字符串

import time
format_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(1436949765))
print(format_time)
#输出
2015-07-15 16:42:45

#标准字符串转时间戳

import time
timearray = time.strptime("2015-07-15 16:42:45", "%Y-%m-%d %H:%M:%S")
timestamp = int(time.mktime(timearray))
print(str(timestamp))
#输出
1436949765

#UTC时间格式转标准字符串

#TODO 输入:"Wed Jun 10 17:47:25 +0000 2020"  
def format_creation_time(time_str):
    str2 = time_str[0:-10] + time_str[-10:].split(" ")[-1]
    dt = datetime.datetime.strptime(str2, '%a %b %d %H:%M:%S %Y') + datetime.timedelta(hours=8)
    return dt.strftime("%Y-%m-%d %H:%M:%S")

 

posted @ 2020-09-18 09:45  小鲨鱼~  阅读(426)  评论(0编辑  收藏  举报