整理工作中常用的时间处理方法
# coding:utf-8
import time
import datetime
def gap_day(time_str, date=None, format="%Y-%m-%d"):
"""
:判断自然日差几天
:param time_str: 2019-02-19 21:49:20
:return:
"""
if not date:
date = time.strftime(format)
now_day_stamps = time.mktime(time.strptime(date, format))
if " " in format:
format = format.split(" ")[0]
input_stamps = time.mktime(time.strptime(time_str.split(" ")[0], format))
return int(abs((now_day_stamps - input_stamps)) // 86400)
def gap_stamps_day(time_str, now_day_stamps=None):
"""
:判断绝对时间差几天
:param time_str: 2019-02-19 21:49:20
:return:
"""
if not now_day_stamps:
now_day_stamps = time.time()
input_stamps = time.mktime(time.strptime(time_str, "%Y-%m-%d %H:%M:%S"))
return int(abs((now_day_stamps - input_stamps)) // 86400)
def gap_stamps_hour(time_str):
"""
:判断绝对上差几个小时
:param time_str: 2019-02-19 21:49:20
:return:
"""
now = int(time.time())
input_stamps = time.mktime(time.strptime(time_str, "%Y-%m-%d %H:%M:%S"))
return int(abs((now - input_stamps)) // 3600)
def gap_stamps_minute(time_str):
"""
:判断绝对上差几个分钟
:param time_str: 2019-02-19 21:49:20
:return:
"""
now = int(time.time())
input_stamps = time.mktime(time.strptime(time_str, "%Y-%m-%d %H:%M:%S"))
return int(abs((now - input_stamps)) // 60)
def get_time_stamp(timeStr, format="%Y-%m-%d %H:%M:%S"):
"""
获取时间戳
:param timeStr: 2019-05-12 09:00:00
:param format: "%Y-%m-%d %H:%M:%S"
:return:
"""
timeArray = time.strptime(timeStr, format)
timestamp = time.mktime(timeArray)
return int(timestamp)
def gap_stamps_sec(time_str):
"""
:判断绝对上差几秒
:param time_str: 2019-02-19 21:49:20
:return:
"""
now = int(time.time())
input_stamps = time.mktime(time.strptime(time_str, "%Y-%m-%d %H:%M:%S"))
return int(abs((now - input_stamps)))
def get_day_jia(date, n, format='%Y-%m-%d'):
"""
时间加n天
:param date:
:param n:
:return:
"""
jia_date = datetime.datetime.strptime(date, format)
jia_date = jia_date + datetime.timedelta(days=n)
return jia_date.strftime(format)
def get_sec_jia(seconds, format="%Y-%m-%d %H:%M:%S"):
"""
当前时间加多少秒
:param seconds:
:param format:
:return: 2019-12-30 19:25:30
"""
return (datetime.datetime.now() + datetime.timedelta(seconds=seconds)).strftime(format)
def get_ts_to_time(ts):
"""时间戳转字符串"""
return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(ts))
def day_long(time1, time2):
"""
计算时间差
:return: 相差的天数
"""
ts1 = get_time_stamp(time1)
ts2 = get_time_stamp(time2)
date1 = datetime.datetime.fromtimestamp(ts1)
date2 = datetime.datetime.fromtimestamp(ts2)
return abs(int((date2 - date1).days))