0

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.

CodeMonkey
  • 22,825
  • 4
  • 35
  • 75
ParisNakitaKejser
  • 12,112
  • 9
  • 46
  • 66
  • 3
    could this work https://docs.python.org/2/library/calendar.html#calendar.timegm – scrineym Oct 07 '15 at 13:06
  • Yes what i need, :) pls make a aswer with it, :) – ParisNakitaKejser Oct 07 '15 at 13:09
  • related: [Converting datetime.date to UTC timestamp in Python](http://stackoverflow.com/q/8777753/4279) – jfs Oct 07 '15 at 16:41
  • if there is no error then `self.__modified_time` is the unix timestamp that you want. Why do you want to recompute it? – jfs Oct 07 '15 at 16:42
  • unrelated: it seems that your code uses `dateutil.tz`: beware, [utc -> local conversions may fail with `dateutil` timezones](https://github.com/dateutil/dateutil/issues/112) – jfs Oct 07 '15 at 16:45

3 Answers3

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())
ρss
  • 5,115
  • 8
  • 43
  • 73
scrineym
  • 759
  • 1
  • 6
  • 28
  • 1
    downvote. It is incorrect. `timegm()` expect UTC time, not central. You could test it by comparing `unix_time_central` to `self.__modified_time` (they should be equal). – jfs Oct 07 '15 at 16:52
0

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.

Community
  • 1
  • 1
jfs
  • 399,953
  • 195
  • 994
  • 1,670
-1

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
Daniel F
  • 13,684
  • 11
  • 87
  • 116