2015-10-07 158 views
0

當我嘗試從UTC時間戳轉換爲正常日期並添加正確的時區時,我無法找到將時間轉換回Unix時間戳的方式。將日期時間轉換爲python中的unix時間戳

我在做什麼撥錯?

utc_dt = datetime.utcfromtimestamp(self.__modified_time) 
from_zone = tz.tzutc() 
to_zone = tz.tzlocal() 

utc = utc_dt.replace(tzinfo=from_zone) 
central = utc.astimezone(to_zone) 

中央等於

2015年10月7日12:45:04 + 02:00

這是我所運行代碼的時候,我需要將時間轉換回時間戳。

+3

會這樣工作https://docs.python.org/2/library/calendar.html#calendar.timegm – scrineym

+0

是的,我需要,:)請儘快與它,:) – ParisNakitaKejser

+0

相關:[轉換datetime.date到Python時間戳記](http://stackoverflow.com/q/8777753/4279) – jfs

回答

1
from datetime import datetime 
from datetime import timedelta 
from calendar import timegm 

utc_dt = datetime.utcfromtimestamp(self.__modified_time) 
from_zone = tz.tzutc() 
to_zone = tz.tzlocal() 

utc = utc_dt.replace(tzinfo=from_zone) 
central = utc.astimezone(to_zone) 
unix_time_central = timegm(central.timetuple()) 
+1

downvote 。這是不正確的。 'timegm()'預計UTC時間,而不是中心。你可以通過比較'unix_time_central'和'self.__ modified_time'來測試它們(它們應該是相等的)。 – jfs

0

來獲取表示在本地時區的時間對應於給定的Unix時間(self.__modified_time)的感知日期時間,你可以直接在本地時區傳遞到fromtimestamp()

from datetime import datetime 
import tzlocal # $ pip install tzlocal 

local_timezone = tzlocal.get_localzone() # pytz tzinfo 
central = datetime.fromtimestamp(self.__modified_time, local_timezone) 
# -> 2015-10-07 12:45:04+02:00 

要獲得Unix時間回在Python 3:

unix_time = central.timestamp() 
# -> 1444214704.0 

unix_time等於self.__modified_time(忽略浮動POI nt錯誤和「正確的」時區)。 To get the code for Python 2 and more details, see this answer

-1

http://crsmithdev.com/arrow/)似乎是最終的Python時間相關的庫

import arrow 
ts = arrow.get(1455538441) 
# ts -> <Arrow [2016-02-15T12:14:01+00:00]> 
ts.timestamp 
# 1455538441 
相關問題