Python項(xiàng)目中很多時(shí)候會(huì)需要將時(shí)間在Datetime格式和TimeStamp格式之間轉(zhuǎn)化,又或者你需要將UTC時(shí)間轉(zhuǎn)化為本地時(shí)間,本文總結(jié)了這幾個(gè)時(shí)間之間轉(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時(shí)間 dt = dt + datetime.timedelta(hours=-8) # 中國默認(rèn)時(shí)區(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)化為本地時(shí)間 dt = dt + datetime.timedelta(hours=8) # 中國默認(rèn)時(shí)區(qū) return dt return timestamp
三、當(dāng)前UTC時(shí)間的TimeStamp
?
def timestamp_utc_now(): return datetime2timestamp(datetime.datetime.utcnow())
四、當(dāng)前本地時(shí)間的TimeStamp
?
def timestamp_now(): return datetime2timestamp(datetime.datetime.now())
五、UTC時(shí)間轉(zhuǎn)化為本地時(shí)間
?
# 需要安裝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")
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號(hào)聯(lián)系: 360901061
您的支持是博主寫作最大的動(dòng)力,如果您喜歡我的文章,感覺我的文章對(duì)您有幫助,請(qǐng)用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長非常感激您!手機(jī)微信長按不能支付解決辦法:請(qǐng)將微信支付二維碼保存到相冊(cè),切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對(duì)您有幫助就好】元
