首頁  >  文章  >  後端開發  >  Python中实现对Timestamp和Datetime及UTC时间之间的转换

Python中实现对Timestamp和Datetime及UTC时间之间的转换

WBOY
WBOY原創
2016-06-06 11:24:103546瀏覽

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

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn