Python之UTC和Local轉換
阿新 • • 發佈:2019-01-27
好記性不如爛筆頭.
from dateutil import tz
from dateutil.tz import tzlocal
from datetime import datetime
# get local time zone name
tz_name = datetime.now(tzlocal()).tzname()
# UTC Zone
from_zone = tz.gettz('UTC')
# local Zone
to_zone = tz.gettz(tz_name)
1. UTC -> Local
utc = datetime.utcnow()
# Tell the datetime object that it's in UTC time zone
utc = utc.replace(tzinfo=from_zone)
# Convert time zone
local = utc.astimezone(to_zone)
print(local)
2. Local -> UTC
2.1 使用dateutil
now = datetime.now(tz=to_zone)
now.replace(tzinfo=from_zone)
utc = now.astimezone(from_zone)
print(utc)
2.2 現將Local time轉為timestamp,然後再將其轉換為UTC time.
import datetime
import time
today = datetime.datetime.today()
stamp = time.mktime(today.timetuple())
utc_now = datetime.datetime.utcfromtimestamp(stamp)
print(today)