本地時(shí)間轉(zhuǎn)換為時(shí)間戳
import time
import pytz
import datetime
dateC1=datetime.datetime(2019,10,17,12,30,17)
timestamp2=time.mktime(dateC1.timetuple())
print timestamp2
時(shí)間戳轉(zhuǎn)換為本地時(shí)間
import datetime
import time
ltime=time.localtime(1571315417)
timeStr=time.strftime("%Y-%m-%d %H:%M:%S", ltime)
print timeStr
UTC時(shí)間轉(zhuǎn)換為時(shí)間戳
def utc_format_local(utc_time, timezone, input_format, output_format):
local_tz = pytz.timezone(timezone)
utc_dt = datetime.datetime.strptime(utc_time, input_format)
local_dt = utc_dt.replace(tzinfo=pytz.utc).astimezone(local_tz)
time_str = local_dt.strftime(output_format)
return time_str
本地時(shí)間轉(zhuǎn)換為UTC
def local_format_utc(local_time, timezone, input_format, output_format):
dt = datetime.datetime.fromtimestamp(time.mktime(time.strptime(local_time, input_format)))
local_dt = pytz.timezone(timezone).localize(dt)
utc_dt = local_dt.astimezone(pytz.utc)
time_str = utc_dt.strftime(output_format)
return time_str
print(utc_format_local("2019-10-17T01:42:08.287Z", "Asia/Hong_Kong", "%Y-%m-%dT%H:%M:%S.%fZ", "%Y-%m-%d %H:%M:%S"))
print(local_format_utc("2019-10-17 09:42:08", "Asia/Hong_Kong", "%Y-%m-%d %H:%M:%S", "%Y-%m-%dT%H:%M:%S.%fZ"))