Python中實現對Timestamp和Datetime及UTC時間之間的轉換
http://www.jb51.net/article/63654.htm
Python專案中很多時候會需要將時間在Datetime格式和TimeStamp格式之間轉化,又或者你需要將UTC時間轉化為本地時間,本文總結了這幾個時間之間轉化的函式,供大家參考。
一、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")