-1

I pulled some data from an API in JSON format. The data contains a Unix time stamp and information about the timezone. My question is how do I add the time zone info (in bold) at the end of the datetime object?

Combined date and time in UTC(according to ISO 8601): 2017-07-29T12:48:20+00:00

beetroot
  • 4,129
  • 3
  • 12
  • 8
  • 1
    Possible duplicate of [Converting unix timestamp string to readable date in Python](https://stackoverflow.com/questions/3682748/converting-unix-timestamp-string-to-readable-date-in-python) – Andre Kampling Jul 28 '17 at 11:22

1 Answers1

1

Install and import python-dateutil. Make sure to convert the time stamp into datetime (divide stamp with 1e3 if it is longer than 10 characters) and then use the dateutil package to add the time zone info at the end with tzoffset like so:

time = datetime.datetime.fromtimestamp(timestamp / 1e3).replace(tzinfo=tzoffset(None, timezone))
beetroot
  • 4,129
  • 3
  • 12
  • 8
Prem
  • 11,775
  • 1
  • 19
  • 33
  • It works.. thank you. What is up with the '1e3'? What does it do once it divides the var? – beetroot Jul 28 '17 at 14:04
  • `1e3` is 10^3. `fromtimestamp` expects timestamp in second so when you divide var by 1e3 you convert millisecond to second. (BTW - if it answered your query then why don't accept it as the right answer ;) ) – Prem Jul 28 '17 at 14:48
  • It partially did... I'm reading the docs on the datetime module, trying to figure out how to do this. Check out my edit. – beetroot Jul 28 '17 at 16:37
  • try `time = datetime.utcfromtimestamp(var/1e3).replace(tzinfo=tzoffset(None, -480)).strftime('%Y-%m-%dT%H:%M:%S %z')` – Prem Jul 28 '17 at 19:27
  • I tried it and got a syntax error for encoding... I don't know what 'tzoffset' is. I found 'utcoffset' on the docs page. Maybe you meant that? Either way after changing this returned the same result. I then found this: " If you merely want to attach a time zone object tz to a datetime dt without adjustment of date and time data, use dt.replace(tzinfo=tz) " Which returned: " TypeError: tzinfo argument must be None or of a tzinfo subclass, not type 'int' " – beetroot Jul 29 '17 at 08:36
  • add `from dateutil.tz import tzoffset` – Prem Jul 29 '17 at 11:55
  • That did it. I'll re-edit my OP to structure this thread so it looks readable. – beetroot Jul 29 '17 at 13:00
  • Glad that it helped :) – Prem Jul 29 '17 at 13:06