python之時間模塊的處理

1.時間轉字符串

def datetime_to_string(mydate, rule='%Y-%m-%d %H:%M:%S'):
    """
    將datetime.datetime轉爲string
    :param mydate:
    :return:
    """
    if isinstance(mydate, datetime.datetime) or isinstance(mydate, datetime.date):
        return mydate.strftime(rule)
    else:
        return mydate

2.字符串轉時間

def string_to_datetime(mystr, rule='%Y-%m-%d %H:%M:%S'):
    """
    將string轉爲 datetime.datetime
    :param mydate:
    :return:
    """
    if isinstance(mystr, str) or isinstance(mystr, unicode):
        return datetime.datetime.strptime(mystr, rule)
    else:
        return mystr

3.字符串轉時間

def string_to_datetime(mystr, rule='%Y-%m-%d %H:%M:%S'):
    """
    將string轉爲 datetime.datetime
    :param mydate:
    :return:
    """
    if isinstance(mystr, str) or isinstance(mystr, unicode):
        return datetime.datetime.strptime(mystr, rule)
    else:
        return mystr

4.unix時間戳轉字符串

def unix_time_to_str(unix_time, rule='%Y-%m-%d %H:%M:%S'):
    """
    unix時間轉str
    :param unix_time:
    :param rule:
    :return:
    """
    date = unix_time_to_datetime(unix_time)
    return datetime_to_string(date, rule)

5.字符串轉unix時間戳

def string_to_unix_time(_str, rule='%Y-%m-%d %H:%M:%S'):
    """
    str 轉unix時間戳
    :param _str:
    :param rule:
    :return:
    """
    _time = string_to_datetime(_str, rule)
    return time.mktime(_time.timetuple()) * 1000

6.unix時間戳轉時間

def unix_time_to_datetime(unix_time):
    """
    unix時間戳轉datetime
    :param _str:
    :param rule:
    :return:
    """
    try:
        _time = datetime.datetime.fromtimestamp(unix_time)
    except ValueError:
        try:
            _time = datetime.datetime.fromtimestamp(unix_time / 1000)
        except ValueError:
            _time = unix_time
    else:
        _time = unix_time
    return _time

7.時間轉unix時間戳

def datetime_to_unix(_time):
    """
    unix時間戳轉datetime
    :param _str:
    :param rule:
    :return:
    """
    if isinstance(_time, datetime.datetime):
        return time.mktime(_time.timetuple())
    else:
        return _time

8.關於時間差計算

def seconds_to_hour(num):
    """
    秒轉時分秒
    :param num:
    :return:
    """
    h = num // 3600
    num = num % 3600
    m = num // 60
    s = num % 60
    return '%d小時%d分鐘%d秒'%(h,m,s)
#前推或後退時間
startTime = endTime - datetime.timedelta(seconds=seconds)
#時間差計算
maxTime = max(createTimeList)
minTime = min(createTimeList)
totalOnline = maxTime - minTime
totalOnline = seconds_to_hour(totalOnline.seconds)

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章