python中实现对timestamp和datetime及utc时间之间的转换

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”)

Posted in 未分类