简体   繁体   中英

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.

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

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:

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_time = central.timestamp()
# -> 1444214704.0

unix_time is equal to self.__modified_time (ignoring floating point errors and "right" timezones). To get the code for Python 2 and more details, see this answer .

Arrow ( http://crsmithdev.com/arrow/ ) appears to be the ultimate Python time-related library

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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