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
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)