#!/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


# ==========================
# ========== time ==========
# ==========================


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 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 test():
    print(getCurrentMilliSecondTime())
    print(getCurrentSecondTime())
    print(getCurrentFormatTimeStr())
    print(getCurrentTimeTupleByFormatStr())
    print("=======")
    print(getCurrentTimeStr())
    print(getCurrentTimeStrByTuple(time.localtime()))
    print(getTimeByTuple(time.localtime()))
    print("=======")
    print(getNowDateTime())
    print(getNowTime())
    print(getNowDateTime())
    print(getTodayDate())
    print(getTimeDate(time.time() - 86400))
    print("=======")
    print(getAnyDateTime(2))
    print(getAnyDateSecondTime(2))
    print("=======")
    print(getTodayStartTime())
    print(getCurrentWeekTime())
    print('昨天')
    print(getYesterdayStartTime(), time.strftime("%Y-%m-%dT%H:%M:%S", time.localtime(getYesterdayStartTime())))
    print(getYesterdayEndTime(), time.strftime("%Y-%m-%dT%H:%M:%S", time.localtime(getYesterdayEndTime())))
    print('今天')
    print(getTodayStartTime(), time.strftime("%Y-%m-%dT%H:%M:%S", time.localtime(getTodayStartTime())))
    print(getTodayEndTime(), time.strftime("%Y-%m-%dT%H:%M:%S", time.localtime(getTodayEndTime())))
    print('明天')
    print(getTomorrowStartTime(), time.strftime("%Y-%m-%dT%H:%M:%S", time.localtime(getTomorrowStartTime())))
    print(getTomorrowEndTime(), time.strftime("%Y-%m-%dT%H:%M:%S", time.localtime(getTomorrowEndTime())))
    return '测试完毕！'


if __name__ == '__main__':
    print(test())
