Convert unix timestamp in Python to datetime and make 2 Hours behind

20,429

With datetime.timedelta object:

from datetime import datetime, timedelta

unix_ts = 1507126064
dt = (datetime.fromtimestamp(unix_ts) - timedelta(hours=2)).strftime('%Y-%m-%d %H:%M:%S')
print(dt)
Share:
20,429
Andrew Christopher
Author by

Andrew Christopher

Updated on November 08, 2020

Comments

  • Andrew Christopher
    Andrew Christopher over 3 years

    I have this code, recieve a unix timestamp from a server which is 2 hours ahead of my time. My time is SAST and theirs is GMT +2.

    I convert this timestamp in python to a readable datetime like this

    import datetime
    
    unixtimestamp = 1507126064
    datetime.datetime.fromtimestamp(unixtimestamp).strftime('%Y-%m-%d %H:%M:%S')
    

    The problem is that this time comes back two hours ahead of me, so what would be the easiest way to minus two hours or make it local time.

  • Andrew Christopher
    Andrew Christopher over 6 years
    seems to have worked like a charm ,do I replace import datetime with from datetime import datetime, timedelta ?
  • RomanPerekhrest
    RomanPerekhrest over 6 years
    @AndrewChristopher, as you wish: you are able to import the entire module datetime (import datetime) OR to import just the needed submodules/objects from datetime import datetime, timedelta
  • Andrew Christopher
    Andrew Christopher over 6 years
    I keep getting errors on from datetime import datetime, timedelta
  • Andrew Christopher
    Andrew Christopher over 6 years
    is this correct import sys import datetime import time import socket import struct import MySQLdb import subprocess import glob from datetime import timedelta
  • Andrew Christopher
    Andrew Christopher over 6 years
    sorry for all on one line