Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 488
Andrew Christopher Avatar asked Oct 04 '17 13:10

Andrew Christopher


1 Answers

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)
like image 128
RomanPerekhrest Avatar answered Sep 22 '22 00:09

RomanPerekhrest