#! /usr/bin/env python
# -*- coding: utf-8 -*-
# __author__ = "chenwei"
# Date: 2018/11/19

import pytz
import time
from datetime import datetime


def utc_to_local(utc_time_str, utc_format='%Y-%m-%dT%H:%M:%SZ'):
    """
    UTCS时间转换为时间戳
    :param utc_time_str: 2016-07-31T16:00:00Z
    :param utc_format:
    :return: 1542816000
    """
    local_tz = pytz.timezone('Asia/Shanghai')
    local_format = "%Y-%m-%d %H:%M:%S"
    utc_dt = datetime.strptime(utc_time_str, utc_format)
    local_dt = utc_dt.replace(tzinfo=pytz.utc).astimezone(local_tz)
    time_str = local_dt.strftime(local_format)
    return int(time.mktime(time.strptime(time_str, local_format)))


def unix_time_to_datetime(stamp):
    """
    时间戳转化为datetime类型
    :param stamp:
    :return:
    """
    return datetime.fromtimestamp(stamp)


def utc_to_datetime(utc_time_str):
    """
    utc时间转化为datetime
    :param utc_time_str:
    :return:
    """
    time_stamp = utc_to_local(utc_time_str)
    return unix_time_to_datetime(time_stamp)


def datetime_toString(dt):
    return dt.strftime("%Y-%m-%d %H:%M:%S")


def analysis_time(time):
    """

    :param time:
    :return:
    """
    try:
        target_time = unix_time_to_datetime(int(time) / 1000)
    except ValueError:
        target_time = utc_to_datetime(time[:-5] + 'Z')

    return datetime_toString(target_time)