python时间格式转换

本地时间转换为时间戳

import time
import pytz
import datetime
dateC1=datetime.datetime(2019,10,17,12,30,17)
timestamp2=time.mktime(dateC1.timetuple())
print timestamp2

时间戳转换为本地时间

import datetime
import time
ltime=time.localtime(1571315417)
timeStr=time.strftime("%Y-%m-%d %H:%M:%S", ltime)
print timeStr

UTC时间转换为时间戳

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

本地时间转换为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"))

你可能感兴趣的:(python时间格式转换)