dms3_demo / utils /time_util.py
qilongyu
Add application file
446f9ef
# -*- coding:utf-8 –*-
import time
from datetime import datetime, timedelta
def convert_input_time(input_time, digit=13):
if isinstance(input_time, (int, float)):
stamp = stamp_pad(input_time, digit)
return stamp
elif isinstance(input_time, str):
format_str = "%Y-%m-%d %H:%M:%S"
if '/' in input_time:
format_str = "%Y/%m/%d %H:%M:%S"
elif ' ' not in input_time and ':' not in input_time:
format_str = '%Y%m%d%H%M%S'
stamp = convert_time_str(input_time, format_str, digit)
return stamp
else:
raise ValueError('UnSupport type')
def stamp_pad(stamp, digit=10):
stamp = int(stamp)
length = len(str(stamp))
if length < digit:
stamp = int(str(stamp) + '0'*(digit-length))
if length > digit:
stamp = int(str(stamp)[:digit])
return stamp
def convert_stamp(stamp, format_str="%Y-%m-%d %H:%M:%S"):
date_time = time.strftime(format_str, time.localtime(stamp_pad(stamp, digit=10)))
return date_time
def convert_time_str(time_str, format_str="%Y-%m-%d %H:%M:%S", digit=13):
t = datetime.strptime(time_str, format_str).timestamp()
return stamp_pad(t, digit)
def transform_format(time_str, dst_fmt="%Y-%m-%d %H:%M:%S"):
stamp = convert_input_time(time_str, digit=10)
return convert_stamp(stamp, dst_fmt)
# @clock_custom('[{elapsed:0.8f}s] {name}()')
# 计算两个时间戳的差值
def cal_stamps_diff(stamp1, stamp2):
stamp1 = stamp_pad(stamp1)
stamp2 = stamp_pad(stamp2)
if stamp1 <= stamp2:
diff = datetime.fromtimestamp(stamp2) - datetime.fromtimestamp(stamp1)
return diff.seconds
else:
diff = datetime.fromtimestamp(stamp1) - datetime.fromtimestamp(stamp2)
return -diff.seconds
# 速度快
# @clock_custom('[{elapsed:0.8f}s] {name}()')
def cal_diff_seconds(stamp1, stamp2):
stamp1 = stamp_pad(stamp1)
stamp2 = stamp_pad(stamp2)
return stamp2-stamp1
# 计算数小时前的时间戳
def cal_yesterday_stamp(delta_hours=24):
now = datetime.now()
delta = timedelta(hours=delta_hours)
before = (now-delta).timestamp()
return stamp_pad(before)
def get_now_date():
return time.strftime('%m%d', time.localtime(time.time()))
def get_today():
return datetime.now().strftime('%Y%m%d')
def get_days_before(days=5):
return (datetime.now() - timedelta(days=days)).strftime('%Y%m%d')
def get_date(day=0, time_str='%Y%m%d'):
if day == 0:
return datetime.now().strftime(time_str)
elif day > 0:
return (datetime.now() - timedelta(days=day)).strftime(time_str)
def get_season():
month = int(datetime.now().strftime('%m'))
if month <= 2 or month == 12:
return 4
elif month <= 5:
return 1
elif month <= 8:
return 2
else:
return 3
class Timer:
def __init__(self):
# store the start time, end time, and total number of frames
# that were examined between the start and end intervals
self._start = None
self._end = None
self._numFrames = 0
def start(self):
# start the timer
self._start = datetime.now()
return self
def stop(self):
# stop the timer
self._end = datetime.now()
def update(self):
# increment the total number of frames examined during the
# start and end intervals
self._numFrames += 1
def elapsed(self):
# return the total number of seconds between the start and
# end interval
return (self._end - self._start).total_seconds()
def fps(self):
# compute the (approximate) frames per second
return self._numFrames / self.elapsed()
if __name__ == '__main__':
print(convert_stamp(1625465966842))
print(convert_time_str('2020-10-02 05:36:00'))
print(convert_time_str('2020-10-02 06:46:00'))
print(convert_input_time('20201208102335', digit=10))
# print(convert_stamp(1595945099609, "%Y%m%d%H%M%S"))
# stamp1 = 1594288522155
# stamp2 = 1594288582019
# cal_diff_seconds(stamp1, stamp2)
# cal_stamps_diff(stamp1, stamp2)
# print(get_now_date())
# print((datetime.datetime.now()-datetime.timedelta(days=5)).strftime('%Y%m%d'))
"""
{"detectId":11,"startTime":1595945079609,"endTime":1595945119609,"commandId":"738411578604601345","deviceId":"03agptmyb2be9a2c","content":"{\"content\":\"\",\"fileType\":5,\"lat\":23.012758891079372,\"lng\":113.22142671753562,\"startTime\":1595945099670}","timestamp":1595945099609}
{"detectId":11,"startTime":1595945088792,"endTime":1595945128792,"commandId":"738412534595338240","deviceId":"03agptmyb2be9a2c","content":"{\"content\":\"\",\"fileType\":5,\"lat\":23.012758891079372,\"lng\":113.22142671753562,\"startTime\":1595945108854}","timestamp":1595945108792}
{"detectId":11,"startTime":1595945115257,"endTime":1595945155257,"commandId":"738414926988763136","deviceId":"03agph2zhgb56534","content":"{\"content\":\"\",\"fileType\":5,\"lat\":23.105039173700952,\"lng\":113.136789077983,\"startTime\":1595945135322}","timestamp":1595945135257}
""" \
""