import time, datetime, pytz time_n = "2020-05-14 15:15:38" time_format = time.strptime(time_n, "%Y-%m-%d %H:%M:%S") timestamp = int(time.mktime(time_format)) def local_to_utc(local_ts, utc_format='%Y-%m-%dT%H:%MZ'): local_tz = pytz.timezone('Asia/Shanghai') #定義本地時區 local_format = "%Y-%m-%d %H:%M:%S" #定義本地時間format time_str = time.strftime(local_format, time.localtime(local_ts)) #首先將本地時間戳轉化為時間元組,用strftime格式化成字串 dt = datetime.datetime.strptime(time_str, local_format) #將字串用strptime 轉為為datetime中 datetime格式 local_dt = local_tz.localize(dt, is_dst=None) #給時間新增時區,等價於 dt.replace(tzinfo=pytz.timezone('Asia/Chongqing')) utc_dt = local_dt.astimezone(pytz.utc) #astimezone切換時區 return utc_dt.strftime(utc_format) print(local_to_utc(timestamp)) # 2020-05-14T07:15Z