From 7b1900c1e1d19cf7427f3c7544ad1610e6ac4054 Mon Sep 17 00:00:00 2001 From: guozg Date: Fri, 12 Mar 2021 23:11:20 +0800 Subject: [PATCH] =?UTF-8?q?=E6=96=87=E4=BB=B6=E6=BC=8F=E4=B8=8A=E4=BC=A0?= =?UTF-8?q?=E4=BA=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- common/util/handle_datetime.py | 187 +++++++++++++++++++++++++++++++++ common/util/handle_jsonfile.py | 88 ++++++++++++++++ 2 files changed, 275 insertions(+) create mode 100644 common/util/handle_datetime.py create mode 100644 common/util/handle_jsonfile.py diff --git a/common/util/handle_datetime.py b/common/util/handle_datetime.py new file mode 100644 index 0000000..3dc34bf --- /dev/null +++ b/common/util/handle_datetime.py @@ -0,0 +1,187 @@ +#!/usr/bin/python3 +# -*- coding: UTF-8 -*- +# 设置utf-8 显示中文 +""" +@Author: guo +@File:handle_datetime.py +""" +from datetime import date +from datetime import datetime +import time + + +class HandleDateTime: + + def __init__(self): + # 到天的时间格式 + self.__d_format = "%Y-%m-%d" + # 到小时的时间格式 + self.__h_format = "%Y-%m-%d %H" + # 到分钟的时间格式 + self.__m_format = "%Y-%m-%d %H:%M" + # 到秒的时间格式 + self.__s_format = "%Y-%m-%d %H:%M:%S" + + def get_cur_date(self) -> str: + """ + 获取当前客户端的日期,格式为 2017-01-01 \n + :return: 当前日期 + """ + # curdate = time.strftime("%Y-%m-%d") + # return curdate + curdate = date.strftime(datetime.now(), self.__d_format) + return curdate + + def get_cur_time(self) -> str: + ''' + 获取当前客户端的时间,格式为 2019-08-09 23:33:20 \n + :return: 当前时间,时间格式为"%Y-%m-%d %H:%M:%S" 如2019-08-09 23:33:20 + ''' + curtime = datetime.strftime(datetime.now(), self.__s_format) + return curtime + + def get_curtime_to_hh(self) -> str: + """ + 获取当前客户端时间,到小时,不包括分钟和秒,格式为:2018-01-01 13 \n + :return: 不包括分钟和秒的当前客户端时间,24小时制 + """ + # curtime = time.strftime("%Y-%m-%d %H") + # return curtime + curtime = datetime.strftime(datetime.now(), self.__h_format) + return curtime + + def get_curtime_to_mm(self) -> str: + """ + 获取当前客户端的时间,到分钟,不包含秒,格式为:2018-01-01 13:10 \n + :return: 不包含秒的当前客户端时间,24小时制 + """ + # curtime = time.strftime("%Y-%m-%d %H:%M") + # return curtime + curtime = datetime.strftime(datetime.now(), self.__m_format) + return curtime + + def get_curtime_to_ss(self) -> str: + """ + 获取当前客户端的时间,到秒,包含秒,格式为:2018-01-01 13:10:10 \n + :return: 包含秒的当前客户端时间,24小时制 + """ + # curtime = time.strftime("%Y-%m-%d %H:%M:%S") + # return curtime + curtime = datetime.strftime(datetime.now(), self.__s_format) + return curtime + + def str_to_time(self, strtime: str): + """ + 将传入的时间字符串格式化为对应的时间对象,最后返回的格式为%Y-%m-%d %H:%M:%S + 如:2017-01-09 12:30:40 \n + :param strtime: 时间字符串 + :return: 格式化为%Y-%m-%d %H:%M:%S(2018-01-05 21:13)的时间对象 + """ + # 到秒钟的格式 2018-01-01 12:30:30 + if strtime.count(":") == 2 and strtime.count("-") == 2: + Otime = datetime.strptime(strtime, self.__s_format) + # 到分钟的格式 2018-01-01 12:30 + elif strtime.count("-") == 2 and strtime.count(":") == 1: + Otime = datetime.strptime(strtime, self.__m_format) + # 到小时的格式 2018-01-01 18 + elif strtime.count("-") == 2 and strtime.count(":") == 0 and strtime.count(" ") == 1: + Otime = datetime.strptime(strtime, self.__h_format) + # 到日期的格式 2018-01-01 + elif strtime.count("-") == 2 and strtime.count(":") == 0: + Otime = datetime.strptime(strtime, self.__d_format) + return Otime + + def __timedelta(self, starttime: str, endtime: str): + """ + 私有方法,仅内部使用。主要是为后面求取两时间间隔时, + 将时间字符串转化为时间对象后,对两个时间进行大小判断,同时进行相减 \n + :param starttime: + :param endtime: + :return: + """ + if starttime <= endtime: + timedelta = (endtime - starttime) + else: + timedelta = (starttime - endtime) + return timedelta + + def time_delta_ss(self, starttime: str, endtime: str) -> int: + """ + 计算两个时间之间的相差多少秒,返回的值为int类型 + 在进行计算之前,先要判断传入的是到小时,还是到分钟,或者是到秒, + 然后再将传入的参数进行对应的时间类型转换。 \n + :param starttime: 要比较的开始时间 + :param endtime: 要比较的结束时间 + :return: 返回两个时间的差值,结果为秒,为int类型 + """ + # 进行比较之前,先进行格式转换,转换为时间对象 + start_time = self.str_to_time(starttime) + end_time = self.str_to_time(endtime) + # 调用私有方法,进行时间大小判断 + timedelta = self.__timedelta(start_time, end_time) + # 这里必须使用total_seconds()方法,否则当秒数超过60后,就会向前进一,即转为成分钟 + # 即总共是80秒,如果使用seconds()方法,返回的值 则为20,如果使用total_seconds()则是80 + return int(timedelta.total_seconds()) + + def time_delta_mm(self, starttime: str, endtime: str) -> int: + """ + 计算两个时间之间相差多少分钟,返回的值为int类型。 + 在进行计算之前,先要判断传入的时间 是到小时,还是到分钟,还是到秒钟, + 然后再将传入按照匹配的时间类型进行转换。 \n + :param starttime: 要比较的开始时间 + :param endtime: 要比较的结束时间 + :return: 返回两个时间的差值,结果为分钟,为int类型 + """ + # 在进行比较之前,先进行格式转换,将其转换为时间对象 + start_time = self.str_to_time(starttime) + end_time = self.str_to_time(endtime) + # 调用私有方法,进行时间大小判断,并返回相应的时间差 + timedelta = self.__timedelta(start_time, end_time) + return int(timedelta.total_seconds() // 60) + + def time_delta_hh(self, starttime: str, endtime: str) -> int: + """ + 计算两个时间之间相差多少小时,返回的值为int类型。 + 在进行计算之前,先要判断传入的时间 是到小时,还是到分钟,还是到秒钟, + 然后再将传入按照匹配的时间类型进行转换。 \n + :param starttime: 要比较的开始时间 + :param endtime: 要比较的结束时间 + :return: 返回两个时间的差值,结果为小时,为int类型 + """ + # 在进行比较之前,先进行格式转换,将其转换为时间对象 + start_time = self.str_to_time(starttime) + end_time = self.str_to_time(endtime) + # 调用私有方法,进行时间大小判断,并返回相应的时间差 + timedelta = self.__timedelta(start_time, end_time) + # return ((timedelta.seconds) // (60 * 60)) + return int(timedelta.total_seconds() // (60 * 60)) + + def time_delta_days(self, starttime: str, endtime: str) -> int: + """ + 计算两个时间之间相差多少天,返回的值为int类型。 \n + :param starttime: 要比较的开始时间 + :param endtime: 要比较的结束时间 + :return: 返回两人时间的差值,结果为天数,为int类型 + """ + # 在进行比较之前,先进行格式转换,将其转换为时间对象 + start_time = self.str_to_time(starttime) + end_time = self.str_to_time(endtime) + # 调用私有方法,进行时间大小判断,并返回相应的时间差 + timedelta = self.__timedelta(start_time, end_time) + # return ((timedelta.seconds) // (60 * 60)) + return timedelta.days + + def timestamp_to_time(self, timestamp) -> str: + """ + 将时间时间戳转为时间, 转化格式为 "%Y-%m-%d %H:%M:%S" \n + :param timestamp: 时间戳 + :return: str 类型,转化的时间 如: 2020-01-01 09:30:30 + """ + return time.strftime(self.__s_format, time.localtime(timestamp)) + +if __name__ == '__main__': + htime = HandleDateTime() + start = '2020-10-1 10:10:20' + end = '2020-10-1 10:10:30' + data = htime.time_delta_days(start,end) + print(data) \ No newline at end of file diff --git a/common/util/handle_jsonfile.py b/common/util/handle_jsonfile.py new file mode 100644 index 0000000..d6bfb9b --- /dev/null +++ b/common/util/handle_jsonfile.py @@ -0,0 +1,88 @@ +#!/usr/bin/python3 +# -*- coding: UTF-8 -*- +# 设置utf-8 显示中文 +""" +@Author: guo +@File:handle_jsonfile.py +""" +import json +import os + + +class HandleJsonFile: + ''' + 操作json文件,进行读写. + ''' + + def write_json_data(self, filepath, dict_value:dict): + ''' + 将dict转为string后,写入到json文件中,易传输 \n + :param filepath: 文件路径,包含文件名 + :param dict_value: 要写入的字典值 + :return: None + ''' + filepath = filepath + # 判断是否是以.josn结束 + if filepath: + filepath = filepath if filepath.endswith('.json') else filepath + '.json' + + # 在写入之前,要先检测目录是否存在,若不存在,则新建,否则会抛异常 + dir = os.path.dirname(filepath) + if not os.path.exists(dir): + # os.mkdir(dir) + os.makedirs(dir, exist_ok=True) + + with open(filepath, 'w', encoding='utf-8') as fp: + # dict 转化为string 并存入到json文件中,要设置不启用askii编码,否则中文会显示编码。 + fp.write(json.dumps(dict_value, ensure_ascii=False)) + + def write_dict_to_json_file(self, filepath, dict_value:dict): + ''' + 将dict写入到json文件中(将dict转化为json字符串格式,写入文件) ,易存储 \n + :param filepath: 文件路径 + :param dict_value: 要写入的字典 + :return: + ''' + filepath = filepath + # 判断是否是以.josn结束 + if filepath: + filepath = filepath if filepath.endswith('.json') else filepath + '.json' + + # 在写入之前,要先检测目录是否存在,若不存在,则新建,否则会抛异常 + dir = os.path.dirname(filepath) + if not os.path.exists(dir): + # os.mkdir(dir) + os.makedirs(dir, exist_ok=True) + + with open(filepath, 'w', encoding='utf-8') as fp: + # 直接将字典写入到json文件中,要设置不启用askii编码,否则中文会显示编码。 + json.dump(dict_value, fp, ensure_ascii=False) + + def read_json_data(self, filepath): + ''' + 读取json文件中的值,并转化为dict,针对内存对象,将string转化为dict对象 \n + :param filepath: 文件相对路径,包含文件名 + :return: 转化后的dict + ''' + filepath = filepath + # 判断是否是以.josn结束 + if filepath: + filepath = filepath if filepath.endswith('.json') else filepath + '.json' + + with open(filepath, 'r', encoding='utf-8') as fp: + # 将string转化为dict + return json.loads(fp.read()) + + def read_json_file_to_dict(self, filepath): + ''' + 读取json文件,并将数据转化为dict,针对文件句柄,是直接从文件中读取 \n + :param filepath: 文件的相对路径,包含文件名 + :return: 转化后的dict + ''' + filepath = filepath + # 判断是否是以.josn结束 + if filepath: + filepath = filepath if filepath.endswith('.json') else filepath + '.json' + + with open(filepath, 'r', encoding='utf-8') as fp: + return json.load(fp)