0

I wanted to convert the UNIX time into local date and time. I am getting the UNIX timestamp value from my server but when I convert the UNIX using these set of code I get a time which is 1 hour 30 min less than the actual time. But when I take the raw timestamp data and check in the online UNIX to local date and time converter I get the correct time.

import datetime

time_local = datetime.datetime.fromtimestamp(1502705627085/1e3)
print time_local
Nimantha
  • 6,405
  • 6
  • 28
  • 69

2 Answers2

1

is your timezone correct on your system ?

From the python datetime documentation :

classmethod datetime.fromtimestamp(timestamp[, tz])

Return the local date and time corresponding to the POSIX timestamp, such as is returned by time.time(). If optional argument tz is None or not specified, the timestamp is converted to the platform’s local date and time, and the returned datetime object is naive.

If you cannot change your system's timezone, you can specify a tz as explained in the datetime module documentation.

Nimantha
  • 6,405
  • 6
  • 28
  • 69
peyo
  • 442
  • 3
  • 9
  • Maybe I'm wrong but aren't timezones always in full hours, so how can it be 90 minutes off!? Just wondering if it may be some other problem. – xander Aug 14 '17 at 13:10
  • Some timezone appears to have 30 min offsets like india tz compared to UTC (UTC+05:30). Also, I've just found here ( https://www.timeanddate.com/time/time-zones-interesting.html ) a list of non round-hour timezones. – peyo Aug 14 '17 at 13:12
  • yes, you were right I haven't noticed my time of my system. this silly mistake bugged me a lot. Thank you Sir. – Dipak Bhagat Aug 15 '17 at 15:30
-1
import datetime
import tzlocal

time_local = datetime.datetime.fromtimestamp(1502705627085/1e3, tzlocal.get_localzone())
print time_local
Nimantha
  • 6,405
  • 6
  • 28
  • 69
Prem
  • 11,775
  • 1
  • 19
  • 33