Search code examples
pythondatetimetimetimestamppytz

Is there a "local" timestamp?


I can convert from an UTC timestamp e.g. 1417392000 to a local datetime object including daylight saving time, but when I try and convert the local datetime object to a "local timestamp" then I get the same UTC timestamp as before.

Am I thinking in circles and they are the same? I was supposed to save "local timestamp" from incoming UTC timestamp.

This is my code

    print("UTC timestamp %d" % hour[0])
    day = self.get_day(hour)
    month = self.get_month(hour)
    year = self.get_year(hour)
    tz = pytz.timezone('Europe/Stockholm')
    utc_dt = datetime.utcfromtimestamp(int(hour[0])).replace(tzinfo=pytz.utc)
    print("UTC datetime %s" % utc_dt)
    dt = tz.normalize(utc_dt.astimezone(tz))
    print("STO datetime %s" % dt.strftime('%Y-%m-%d %H:%M:%S %Z%z'))
    print("STO ts %d" % int(time.mktime(dt.timetuple())))
    print("STO timestamp %d" % utc_dt.astimezone(tz).timestamp())
    day = int(dt.strftime('%d'))
    month = int(dt.strftime('%m'))
    year = int(dt.strftime('%Y'))

Output

UTC timestamp 1417395600
UTC datetime 2014-12-01 01:00:00+00:00
STO datetime 2014-12-01 02:00:00 CET+0100
STO ts 1417395600
STO timestamp 1417395600

All "timestamps" (i.e. integer representations of the time) are the same. Is it possible to make a "local timestamp" ? The data type is supposed to be a timestamp that is a number and in local time.


Solution

  • As per Wikipedia

    Unix time (also known as POSIX time or Epoch time) is a system for describing instants in time, defined as the number of seconds that have elapsed since 00:00:00 Coordinated Universal Time (UTC), Thursday, 1 January 1970

    So regardless of what timezone you're on, the epoch will always be calculated in the UTC timezone.

    For display purposes, you can convert the timestamp to a local time, but as otherwise the internal representation of the epoch will always be in the UTC timezone