一、Datetime轉化為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: # 是否轉化為UTC時間 dt = dt + datetime.timedelta(hours=-8) # 中國默認時區 timestamp = total_seconds(dt - EPOCH) return long(timestamp) return dt
二、TimeStamp轉化為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: # 是否轉化為本地時間 dt = dt + datetime.timedelta(hours=8) # 中國默認時區 return dt return timestamp
三、當前UTC時間的TimeStamp
def timestamp_utc_now(): return datetime2timestamp(datetime.datetime.utcnow())
四、當前本地時間的TimeStamp
def timestamp_now(): return datetime2timestamp(datetime.datetime.now())
五、UTC時間轉化為本地時間
# 需要安裝python-dateutil # Ubuntu下:sudo apt-get install python-dateutil # 或者使用PIP:sudo pip install python-dateutil from dateutil import tz from dateutil.tz import tzlocal from datetime import datetime # get local time zone name print datetime.now(tzlocal()).tzname() # UTC Zone from_zone = tz.gettz('UTC') # China Zone to_zone = tz.gettz('CST') 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 datetime.strftime(local, "%Y-%m-%d %H:%M:%S")
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com