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

2024-04-18 11:59:20 发布

您现在位置:Python中文网/ 问答频道 /正文

当我试图从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)

中心等于

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

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


Tags: to方法fromselfzonedatetimetime时间
3条回答
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())

要获取表示本地时区中与给定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时间,请执行以下操作:

^{pr2}$

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

Arrowhttp://crsmithdev.com/arrow/)似乎是终极的Python时间相关库

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

相关问题 更多 >