Python項目中很多時候會需要將時間在Datetime格式和TimeStamp格式之間轉(zhuǎn)化,又或者你需要將UTC時間轉(zhuǎn)化為本地時間,本文總結(jié)了這幾個時間之間轉(zhuǎn)化的函數(shù),供大家參考。
一、Datetime轉(zhuǎn)化為TimeStamp
def datetime2timestamp(dt, convert_to_utc=False): ''' Converts a datetime object to UNIX timestamp in milliseconds. ''' if isinstance(dt, datetime.datetime): if convert_to_utc: # 是否轉(zhuǎn)化為UTC時間 dt = dt + datetime.timedelta(hours=-8) # 中國默認(rèn)時區(qū) timestamp = total_seconds(dt - EPOCH) return long(timestamp) return dt
二、TimeStamp轉(zhuǎn)化為Datetime
def timestamp2datetime(timestamp, convert_to_local=False): ''' Converts UNIX timestamp to a datetime object. ''' if isinstance(timestamp, (int, long, float)): dt = datetime.datetime.utcfromtimestamp(timestamp) if convert_to_local: # 是否轉(zhuǎn)化為本地時間 dt = dt + datetime.timedelta(hours=8) # 中國默認(rèn)時區(qū) return dt return timestamp
三、當(dāng)前UTC時間的TimeStamp
def timestamp_utc_now(): return datetime2timestamp(datetime.datetime.utcnow())
四、當(dāng)前本地時間的TimeStamp
def timestamp_now(): return datetime2timestamp(datetime.datetime.now())
五、UTC時間轉(zhuǎn)化為本地時間
# 需要安裝python-dateutil# Ubuntu下:sudo apt-get install python-dateutil# 或者使用PIP:sudo pip install python-dateutilfrom dateutil import tzfrom dateutil.tz import tzlocalfrom datetime import datetime # get local time zone nameprint datetime.now(tzlocal()).tzname() # UTC Zonefrom_zone = tz.gettz('UTC')# China Zoneto_zone = tz.gettz('CST') utc = datetime.utcnow() # Tell the datetime object that it's in UTC time zoneutc = utc.replace(tzinfo=from_zone) # Convert time zonelocal = utc.astimezone(to_zone)print datetime.strftime(local, "%Y-%m-%d %H:%M:%S")新聞熱點
疑難解答
圖片精選