通过正则匹配带时区格式字符串进行格式校验后转换为时间类型
使用datime类型的astimezone方法获得不同时区的时间字符串
import re
from datetime import datetime
def format_datestr_with_zone(datetime_str: str):
"""
格式化带时区时间字符串,返回datetime类型时间
:param datetime_str: 2022-06-14T15:16:31+00:00
:return: datetime
"""
format_ = '%Y-%m-%d %H:%M:%S'
if '.' in datetime_str:
format_ = format_ + '.%f'
zone_ = re.search(r'[+-]\d{2}:\d{2}', datetime_str)
if zone_:
format_ = format_ + '%z'
if 'T' in datetime_str:
format_ = format_.replace(' ', 'T')
return datetime.strptime(datetime_str, format_)
print(format_datestr_with_zone('2022-06-14T15:19:39'))
# datetime.datetime(2022, 6, 14, 15, 19, 39)
print(format_datestr_with_zone('2022-06-14T15:19:39.000+00:00'))
# datetime.datetime(2022, 6, 14, 15, 19, 39, tzinfo=datetime.timezone.utc)
print(format_datestr_with_zone('2022-06-14T15:19:39.000+08:00'))
# datetime.datetime(2022, 6, 14, 15, 19, 39, tzinfo=datetime.timezone(datetime.timedelta(seconds=28800)))
# 转换为本地时区的时间
print(format_datestr_with_zone('2022-06-14T15:19:39.000+00:00').astimezone())
# datetime.datetime(2022, 6, 14, 23, 19, 39, tzinfo=datetime.timezone(datetime.timedelta(seconds=28800), '中国标准时间'))
# 转换为UTC时间
print(format_datestr_with_zone('2022-06-14T15:19:39+08:00').astimezone(pytz.UTC))
# datetime.datetime(2022, 6, 14, 7, 19, 39, tzinfo=<UTC>)
print(datetime.now())
# datetime.datetime(2022, 6, 14, 11, 16, 28, 45080)
print(datetime.now(pytz.UTC))
# datetime.datetime(2022, 6, 14, 3, 16, 29, 282739, tzinfo=<UTC>)
# 时区转换
print(format_datestr_with_zone('2022-06-14T15:19:39.000+05:00'))
# datetime.datetime(2022, 6, 14, 15, 19, 39, tzinfo=datetime.timezone(datetime.timedelta(seconds=18000)))
print(format_datestr_with_zone('2022-06-14T15:19:39.000+05:00').astimezone())
# datetime.datetime(2022, 6, 14, 18, 19, 39, tzinfo=datetime.timezone(datetime.timedelta(seconds=28800), '中国标准时间'))
print(format_datestr_with_zone('2022-06-14T15:19:39.000+05:00').astimezone(pytz.UTC))
# datetime.datetime(2022, 6, 14, 10, 19, 39, tzinfo=<UTC>)
时间戳转时间,可指定时区
from datetime import datetime
import pytz
datetime.fromtimestamp(1654828314).strftime("%Y-%m-%d %H:%M:%S")
# '2022-06-10 10:31:54'
datetime.fromtimestamp(1654828314, pytz.utc).strftime("%Y-%m-%d %H:%M:%S")
# '2022-06-10 02:31:54'