#!/usr/bin/env python
# -*- coding: utf-8 -*-
# time: 2023/3/22 17:17
# file: dpdUtils.py
# author: David
# company: shenyang JY


import time, datetime


class ValidationError(Exception):
    def __init__(self, message):
        self.message = message


def timestamp_to_datetime(ts):
    if type(ts) is not int:
        raise ValueError("timestamp-时间格式必须是整型")
    if len(str(ts)) == 13:
        return datetime.datetime.fromtimestamp(ts/1000)
    elif len(str(ts)) == 10:
        return datetime.datetime.fromtimestamp(ts)
    else:
        raise ValueError("timestamp-时间格式长度错误")


def datetime_to_timestamp(dt, len):
    if len not in (10, 13):
        raise ValueError("timestamp-时间戳转换长度错误")
    if len == 10:
        return int(round(time.mktime(dt.timetuple())))
    else:
        return int(round(time.mktime(dt.timetuple()))*1000)


def datetime_to_timestr(dt):
    return int(dt.strftime('%m%d%H%M'))


def timestr_to_datetime(time_data):
    """
    将时间戳或时间字符串转换为datetime.datetime类型
    :param time_data: int or str
    :return:datetime.datetime
    """
    if isinstance(time_data, float):
        result = timestamp_to_datetime(int(time_data))
    elif isinstance(time_data, int):
        result = timestamp_to_datetime(time_data)
    elif isinstance(time_data, str):
        if len(time_data) == 10:
            result = datetime.datetime.strptime(time_data, '%d/%m/%Y')
            # result = datetime.datetime.strptime(time_data, '%Y-%m-%d')
        elif len(time_data) in {17, 18, 19}:
            # result = datetime.datetime.strptime(time_data, '%d/%m/%Y %H:%M:%S')   # strptime字符串解析必须严格按照字符串中的格式
            result = datetime.datetime.strptime(time_data, '%Y-%m-%d %H:%M:%S')
        else:
            raise ValidationError("时间字符串长度不满足要求！")
    return result


def timestamp_to_timestr(t):
    return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(t))

