Search code examples
pythondatetimetimeunix-timestamp

Problem in converting local unix time to UTC unix time


I am trying to convert unix time on my local system to UTC time in unix format, but after converting it the final time is going off by +1 hour.

To do so, I wrote the following code.

from dateutil import tz 
import time
from time 
import mktime

now_time = time.time()
print('current local unix time', now_time)
print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(now_time)))

to_zone = tz.tzutc()
from_zone = tz.tzlocal()    

t = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(now_time))
utc = datetime.strptime(str(t), '%Y-%m-%d %H:%M:%S')
utc = utc.replace(tzinfo=from_zone)

central = utc.astimezone(to_zone)
print('Converted to UTC ',central)

unix_secs = mktime(central.timetuple())

print('Central unix time ',unix_secs)
print('central unix time to dattime ', time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(unix_secs)))

The output is as follows

current local unix time 1563985835.3707478
2019-07-24 12:30:35
Converted to UTC  2019-07-24 16:30:35+00:00
Central unix time  1564003835.0
central unix time to dattime  2019-07-24 17:30:35

can someone please tell me what am I doing wrong here and how can I fix this?


Solution

  • I guess you're incorrectly transform datetimes with TZ information when converting the timestamp to datetime instance using time.strftime and after that datetime.strptime or when using mktime.

    Anyway, there is much easier way to achieve what you want:

    from datetime import datetime, timezone
    
    # Get current timestamp
    
    now_timestamp = time.time()
    >> 1563987839.054703
    
    # Get datetime of that timestamp but already in UTC.
    # This preserves TZ information and allows 
    # to correctly do transition to the timestamp again.
    
    utc_time = datetime.utcfromtimestamp(now_timestamp)
    >> datetime.datetime(2019, 7, 24, 17, 3, 59, 54703)
    
    # Convert UTC datetime back to timestamp
    
    utc_timestamp = utc_time.timestamp()
    >> 1563977039.054703
    
    # Verify that this timestamp is indeed UTC
    # I am in UTC+3 timezone now
    
    datetime.now()
    >> datetime.datetime(2019, 7, 24, 20, 4, 10, 500229)
    
    datetime.fromtimestamp(utc_timestamp)
    >> datetime.datetime(2019, 7, 24, 17, 3, 59, 54703)