Python時間轉換

1.UTC時間字符串 --> 本地時間字符串

import datetime


def utc_str_to_local_str(utc_str: str, utc_format: str, local_format: str):
    """
    把UTC格式的時間字符串轉換成本地時間字符串
    :param utc_str: UTC time string
    :param utc_format: format of UTC time string
    :param local_format: format of local time string
    :return: local time string
    """
    temp1 = datetime.datetime.strptime(utc_str, utc_format)
    temp2 = temp1.replace(tzinfo=datetime.timezone.utc)
    local_time = temp2.astimezone()
    return local_time.strftime(local_format)

使用示例: 把UTC時間字符串轉換成本地的時間字符串python

utc = '2018-10-17T00:00:00.111Z'
utc_fmt = '%Y-%m-%dT%H:%M:%S.%fZ'
local_fmt = '%Y-%m-%dT%H:%M:%S'
local_string = utc_str_to_local_str(utc, utc_fmt, local_fmt)
print(local_string)   # 2018-10-17T08:00:00

原先的UTC時間字符串爲: 2018-10-17T00:00:00.111Z
如今的轉換結果爲: 2018-10-17T08:00:00
我所處的爲東8時區, 正好領先 UTC8個小時, 證實這個時間轉換是正確的.code

2.UTC時間字符串 --> 時間戳

def utc_str_to_timestamp(utc_str: str, utc_format: str):
    """
    UTC時間字符串轉換爲時間戳
    """
    temp1 = datetime.datetime.strptime(utc_str, utc_format)
    temp2 = temp1.replace(tzinfo=datetime.timezone.utc)
    return int(temp2.timestamp())

時間戳: 從1970年1月1日0時0分0秒開始的絕對秒數
精度能夠選擇是否保留小數點orm

使用示例字符串

utc = '2018-10-17T00:00:00'
utc_fmt = '%Y-%m-%dT%H:%M:%S'
timestamp = utc_str_to_timestamp(utc, utc_fmt)
print(timestamp)
相關文章
相關標籤/搜索