Python中timezone的部分常用操作

对timzone的操作总是感觉特别的繁杂,经过牛人指点,提炼出来几个比较常用的timezone操作。

import pytz
from datetime import datetime

time_str = "2018-04-20 10:10:05"
time_obj = datetime.strptime(time_str, "%Y-%m-%d %H:%M:%S")  # at this point, time_obj is timezone-naive

time_obj_la = pytz.timezone("America/Los_Angeles").localize(time_obj)  # now time_obj_la is timezone-aware, python automatically add daylight saving time if needed
print(time_obj_la)  # 2018-04-20 10:10:05-07:00

time_obj_utc = time_obj_la.astimezone(pytz.timezone("UTC"))  
print(time_obj_utc)  # 2018-04-20 17:10:05+00:00

# convert datetime object to string, no need to remove timezone info
time_str_utc = time_obj_utc.strftime("%Y-%m-%d %H:%M:%S")  # 2018-04-20 17:10:05
time_str_la = time_obj_la.strftime("%Y-%m-%d %H:%M:%S")  # 2018-04-20 10:10:05

# remove timezone info (make datetime object timezone-naive)
time_utc = time_obj_utc.replace(tzinfo=None)  # datetime.datetime(2018, 4, 20, 17, 10, 5)

python中timezone的代码并不是跟国际时区一一对应,转换的时候需要了解pytz library中的时区代码

for tz in pytz.all_timezones:
    print(tz)

你可能感兴趣的:(Python中timezone的部分常用操作)