在python中将datetime转换为unix时间戳

时间:2015-10-07 13:04:32

标签: python datetime

当我尝试将UTC时间戳转换为正常日期并添加正确的时区时,我无法找到将时间转换回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)

Central等于

  

2015-10-07 12:45:04 + 02:00

这是我在运行代码时所拥有的,我需要将时间转换回时间戳。

3 个答案:

答案 0 :(得分: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 :(得分: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

在Python 3中获取Unix时间:

unix_time = central.timestamp()
# -> 1444214704.0

unix_time等于self.__modified_time(忽略浮点错误和"右"时区)。 To get the code for Python 2 and more details, see this answer

答案 2 :(得分:-1)

箭头This Doxia JIRA query)似乎是最终的Python时间相关库

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