#!/usr/bin/env python # -*- coding: utf-8 -*- """ __title__ = '操作时间的工具类' @Time : 2020/9/26 19:44 @Author : Kenny-PC @Software: PyCharm # code is far away from bugs with the god animal protecting I love animals. They taste delicious. ┏┓ ┏┓ ┏┛┻━━━┛┻┓ ┃ ☃ ┃ ┃ ┳┛ ┗┳ ┃ ┃ ┻ ┃ ┗━┓ ┏━┛ ┃ ┗━━━┓ ┃ 神兽保佑 ┣┓ ┃ 永无BUG! ┏┛ ┗┓┓┏━┳┓┏┛ ┃┫┫ ┃┫┫ ┗┻┛ ┗┻┛ """ import datetime import time from datetime import timedelta from dateutil.relativedelta import relativedelta # ========================== # ========== time ========== # ========================== def getDateLists(begin, end): """ 返回一个时间列表 """ interval = getInterval(begin, end) return [getLastDays(begin, -x) for x in range(interval + 1)] def getInterval(begin, end): t1 = datetime.datetime(int(begin[0:4]), int(begin[5:7]), int(begin[8:10])) t2 = datetime.datetime(int(end[0:4]), int(end[5:7]), int(end[8:10])) return (t2 - t1).days def getLastDays( begin, interval): """ :param begin: :param interval: 正数是之前几天, 负数是之后几天 :return: """ start =datetime.datetime(int(begin[0:4]), int(begin[5:7]), int(begin[8:10])) delta = timedelta(days=1) if interval < 0: for _ in range(0, -interval): start = start + delta else: for _ in range(0, interval): start = start - delta return start.strftime("%Y-%m-%d") def str_to_stamp(str): return int(time.mktime(time.strptime(str,'%Y-%m-%d'))) def getLastMonthDay(): """ 获取上月第一天和最后一天 @returen str""" today = datetime.date.today() last_day_of_last_month = datetime.date(today.year, today.month, 1) - datetime.timedelta(1) first_day_of_last_month = datetime.date(last_day_of_last_month.year, last_day_of_last_month.month, 1) return first_day_of_last_month, last_day_of_last_month def getCurrentMilliSecondTime(): """ description: 获取当前时间-毫秒级 return: 1557730376981 -> str """ timestamps = str(round(time.time() * 1000)) return timestamps def getCurrentSecondTime(): """ description: 获取当前时间-秒级 return: 1557730377 -> int """ timestamps = int(time.time()) return timestamps def getCurrentTimeTuple(times=time.time()): """ description: 接受秒级时间戳并返回时间元组(与mktime(tuple)相反) times: 默认当前时间 可传second return: (tm_year=2019, tm_mon=5, tm_mday=13, tm_hour=10, tm_min=9, tm_sec=18, tm_wday=0, tm_yday=133, tm_isdst=0) -> tuple tips: time.localtime() 不传参则取当前时间 """ timestamps = time.localtime(times) return timestamps def getTimeByTuple(tupleTime=time.localtime()): """ description: 接受时间元组并返回秒级时间戳(与localtime(sec)相反) tupleTime: 默认当前时间的元组 可通过time.localtime() or datetime.datetime.now().timetuple()获取 return: 1557733061 -> str """ timestamps = str(round(time.mktime(tupleTime))) return timestamps def getCurrentFormatTimeStr(times=time.time()): """ description: 将指定时间元组格式化为字符串 times: 默认当前时间 可传second return: 2019-05-13 15:00:47 -> str tips: %y 两位数的年份表示(00-99) %Y 四位数的年份表示(000-9999) %m 月份(01-12) %d 月内中的一天(0-31) %H 24小时制小时数(0-23) %I 12小时制小时数(01-12) %M 分钟数(00=59) %S 秒(00-59) %w 星期(0-6) """ timestamps = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(times)) return timestamps def getCurrentTimeTupleByFormatStr(time_str=str(datetime.datetime.now()).split(".")[0], format_type="%Y-%m-%d %H:%M:%S"): """ description: 接受格式化字符串返回时间元组 time_str: 格式化字符串 如:2019-05-13 15:00:47 默认当前时间 format_type: 格式化规则 如:%Y-%m-%d %H:%M:%S 默认%Y-%m-%d %H:%M:%S return: (tm_year=2019, tm_mon=5, tm_mday=13, tm_hour=10, tm_min=9, tm_sec=18, tm_wday=0, tm_yday=133, tm_isdst=0) -> tuple """ return time.strptime(time_str, format_type) def getCurrentTimeStr(): """ description: 获取当前时间的可读形式字符串 return: Mon May 13 11:27:42 2019 -> str """ return time.ctime() def getCurrentTimeStrByTuple(tupleTime=time.localtime()): """ description: 获取指定时间的可读形式字符串 tupleTime: 时间元组 可通过time.localtime() or datetime.datetime.now().timetuple()获取 默认当前时间的元组 return: Mon May 13 11:27:42 2019 -> str """ return time.asctime(tupleTime) def sleepTime(): """ description: 推迟调用线程的运行 """ for i in range(4): print(i) time.sleep(3) # ====================== # ====== datetime ====== # ====================== def getNowDateTime(): """ description: 获取当前日期&时间 return: 2019-05-13 14:41:15 -> str """ timestamps = str(datetime.datetime.now()).split(".")[0] return timestamps def getNowTime(): """ description: 获取当前时间 return: 14:41:15 -> str """ timestamps = str(datetime.datetime.now().time()).split(".")[0] return timestamps def getTodayDate(): """ description: 获取当前日期 return: 2019-05-13 -> str tipe: datetime.datetime.now().date()有相同效果 """ timestamps = str(datetime.date.today()) return timestamps def getTimeDate(times=time.time()): """ description: 获取指定时间戳的日期 time: 秒 默认当前时间 return: 2019-05-13 -> str tips: 一天86400秒 """ timestamps = str(datetime.date.fromtimestamp(round(times))) return timestamps def getAnyDateTime(day, hour=0, min=0, sec=0): """ description: 获取距离现在时间的任意时间的日期&时间 day: 天数 1代表当前时间+1天 -1代表当前时间-1天 hour: 小时 2代表当前时间+2h -2代表当前时间-2h 默认=0 min: 分钟 30代表当前时间+30min -30代表当前时间-30m 默认=0 sec: 秒 120代表当前时间+120s -120代表当前时间-120s 默认=0 return: 2019-05-15 15:37:41 -> str """ return str(datetime.datetime.now() + datetime.timedelta(days=day, hours=hour, minutes=min, seconds=sec)).split(".")[ 0] def getSecondsToDatetime(seconds=getCurrentSecondTime(), datetime_format="%Y-%m-%d %H:%M:%S"): """ description: 秒/时间戳转日期字符串 seconds: 时间戳 默认为当前时间戳 datetime_format: 格式字符串 默认=%Y-%m-%d %H:%M:%S return: 2019-05-15 15:37:41 -> str """ return time.strftime(datetime_format, time.localtime(seconds)) def getAnyDateSecondTime(day, hour=0, min=0, sec=0): """ description: 获取距离现在时间的任意时间的秒数 day: 天数 1代表当前时间+1天 -1代表当前时间-1天 hour: 小时 2代表当前时间+2h -2代表当前时间-2h 默认=0 min: 分钟 30代表当前时间+30min -30代表当前时间-30m 默认=0 sec: 秒 120代表当前时间+120s -120代表当前时间-120s 默认=0 return: 1557902182 -> str """ anyDay = datetime.datetime.now() + datetime.timedelta(days=day, hours=hour, minutes=min, seconds=sec) return str(round(time.mktime(anyDay.timetuple()))) def getTodayStartTime(): """ description: 获取当天0点的时间戳 return: 1557676800 -> str """ return int(time.mktime(datetime.date.today().timetuple())) def getTodayEndTime(): """ description: 获取今天23点59分59秒的时间戳 return: 1601049599 -> str """ yesterday = datetime.date.today() + datetime.timedelta(days=1) return int(time.mktime(time.strptime(str(yesterday), '%Y-%m-%d'))) - 1 def getYesterdayStartTime(): """ description: 获取昨天0点的时间戳 return: 1557676800 -> int """ yesterday = datetime.date.today() - datetime.timedelta(days=1) return int(time.mktime(time.strptime(str(yesterday), '%Y-%m-%d'))) def getYesterdayEndTime(): """ description: 获取昨天23点59分59秒的时间戳 return: 1601049599 -> int """ return int(time.mktime(time.strptime(str(datetime.date.today()), '%Y-%m-%d'))) - 1 def getTomorrowStartTime(): """ description: 获取明天0点的时间戳 return: 1557676800 -> int """ tomorrow = datetime.date.today() + datetime.timedelta(days=1) return int(time.mktime(time.strptime(str(tomorrow), '%Y-%m-%d'))) def getTomorrowEndTime(): """ description: 获取明天23点59分59秒的时间戳 return: 1601049599 -> str """ yesterday = datetime.date.today() + datetime.timedelta(days=2) return int(time.mktime(time.strptime(str(yesterday), '%Y-%m-%d'))) - 1 def getPreviousHourAndCurrentHourSecondTime(seconds=getCurrentSecondTime()): """ description: 接受时间戳并返回上一小时整点时间和当前小时整点时间 seconds: 默认当前时间 可传second return: 1602313200,1602316800 -> (previous_hour_second_time,current_hour_second_time) tips: seconds 不传参则取当前时间 """ previous_hour_second_time = int(seconds // 3600 * 3600 - 3600) current_hour_second_time = int(seconds // 3600 * 3600) return previous_hour_second_time, current_hour_second_time def getPrevious2HourAndCurrentHourSecondTime(seconds=getCurrentSecondTime()): """ description: 接受时间戳并返回上2小时整点时间和当前小时整点时间 seconds: 默认当前时间 可传second return: 1602313200,1602316800 -> (previous_hour_second_time,current_hour_second_time) tips: seconds 不传参则取当前时间 """ previous_hour_second_time = int(seconds // 3600 * 3600 - 7200) current_hour_second_time = int(seconds // 3600 * 3600) return previous_hour_second_time, current_hour_second_time def getCurrentWeekTime(): """ description: 获取本周周一0点 return: 1557676800 -> str tips: 可替换成: timestamps = time.mktime(time.strptime(time.strftime("%Y-%m-%d", time.localtime(times)), "%Y-%m-%d")) """ week = int(time.strftime("%w", time.localtime())) times = round(time.time()) - (week - 1) * 86400 timestamps = time.mktime(datetime.date.fromtimestamp(times).timetuple()) return str(round(timestamps)) def checkInterval(start_time, end_time, need_compare_time): """ description: 判断 need_compare_time 是否在 start_time 和 end_time区间里 return: true -> bool """ return need_compare_time >= start_time and need_compare_time < end_time def getSelfDateStr(times=time.time(),date_format='%Y%m%d'): """ ## 20201028添加,阳光接口,日期参数请求格式20201028,一日一拉api数据 description: 获取指定时间戳 time: 秒 默认当前时间 return: 返回指定时间戳的前一日日期 。 比如 :接收20190512号的时间戳,返回 20190513 -> str tips: 一天86400秒 """ timestamps = str(time.strftime(date_format,time.localtime(times))) return timestamps def getTodayStart(myday,flag=0): if flag: return datetime.datetime.strptime(myday+" 00:00:00",'%Y-%m-%d %H:%M:%S') else: return myday+" 00:00:00" def getTodayEnd(myday,flag=0): if flag: return datetime.datetime.strptime(myday+" 23:59:59",'%Y-%m-%d %H:%M:%S') else: return myday+" 23:59:59" def get_n_day(n=0, is_timestamp=0, is_datetime=0): """默认返回字符串 2020-01-01 """ str = (datetime.datetime.now() + datetime.timedelta(days=n)).strftime("%Y-%m-%d") date1 = datetime.datetime.strptime(str, "%Y-%m-%d") stamp = int(time.mktime(time.strptime(str, "%Y-%m-%d"))) if is_timestamp: return stamp elif is_datetime: return date1 else: return str def stamp_to_str(stamp): a = time.localtime(stamp) return time.strftime("%Y-%m-%d %H:%M:%S", a) if __name__ == '__main__': # print(test()) # print(getTodayEnd('2020-01-01')) print(stamp_to_str(get_n_day(is_timestamp=1)))