简体   繁体   English

在Python中将日期时间转换为Unix时间戳

[英]Convert datetime to unix timestamp in python

When I try to convert from UTC timestamp to normal date and add the right timezone I can't find the way to convert the time back to Unix timestamp. 当我尝试从UTC时间戳转换为正常日期并添加正确的时区时,我找不到将时间转换回Unix时间戳的方法。

What am I doing worng? 我在做什么?

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 is equal to 中央等于

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

This is what I have when running the code, and I need to convert the time back to timestamp. 这是我在运行代码时所拥有的,我需要将时间转换回时间戳。

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

To get an aware datetime that represents time in your local timezone that corresponds to the given Unix time ( self.__modified_time ), you could pass the local timezone to fromtimestamp() directly: 为了获得一个表示您的本地时区中与给定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

To get the Unix time back in Python 3: 要使Unix时间回到Python 3:

unix_time = central.timestamp()
# -> 1444214704.0

unix_time is equal to self.__modified_time (ignoring floating point errors and "right" timezones). unix_time等于self.__modified_time (忽略浮点错误和“正确的”时区)。 To get the code for Python 2 and more details, see this answer . 要获取Python 2的代码和更多详细信息,请参见此答案

Arrow ( http://crsmithdev.com/arrow/ ) appears to be the ultimate Python time-related library Arrowhttp://crsmithdev.com/arrow/ )似乎是终极的Python时间相关库

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM