將UTC、EST時區的時間轉化成北京時間(python)
阿新 • • 發佈:2019-01-01
1、將得到的UTC時間轉化成北京時間:(假設獲得的時間格式為:2018-08-02T14:17:39+00:00)
def utc_to_local(utc_time_str, utc_format='%Y-%m-%dT%H:%M:%S+00:00'): local_tz = pytz.timezone('Asia/Chongqing') local_format = "%Y-%m-%d %H:%M:%S" utc_dt = datetime.datetime.strptime(utc_time_str, utc_format) local_dt = utc_dt.replace(tzinfo=pytz.utc).astimezone(local_tz) # print(local_dt) time_str = local_dt.strftime(local_format) return time_str
2、將得到的EST時間轉化成北京時間:(假設獲得的時間格式為:Jul 10, 2018 5:15 PM EST)
def est_to_local(est_time_str, est_format='%b %d, %Y %I:%M %p EST'): est_tz = pytz.timezone('EST') # 標註時間的時區 local_tz = pytz.timezone('Asia/Chongqing') # 北京時區 local_format = "%Y-%m-%d %H:%M:%S" # 所需要的時間列印格式 est_dt = datetime.datetime.strptime(est_time_str, est_format) local_dt = est_dt.replace(tzinfo=est_tz).astimezone(local_tz) # 將原有時區換成我們需要的 time_str = local_dt.strftime(local_format) # return time_str
3 時間格式2018-08-02T14:17:39+00:00 中,最後的+00:00表示的是UTC時間,如果是+01:00,則需要去找到UTC+01:00對應的時區名稱,然後放入pytz.timezone(‘’)中,按住ctrl、點選timezone函式,裡面有所有時區對應的名稱