1

I'm trying to convert a UNIX time stamp to UTC+9. I've been searching for hours and it's all very confusing what with the different libraries etc

Here's what I've got so far

from datetime import datetime
from pytz import timezone
import datetime

time = 1481079600
utc_time = datetime.datetime.fromtimestamp(time)#.strftime('%Y-%m-%d %H:%M:%S')
print utc_time.strftime(fmt)

tz = timezone('Japan')
print tz.localize(utc_time).strftime(fmt)

This just prints the same time, what am I doing wrong

David Hancock
  • 453
  • 1
  • 11
  • 24
  • See the answers here for more insights: https://stackoverflow.com/questions/4770297/python-convert-utc-datetime-string-to-local-datetime/46339491#46339491 – Brōtsyorfuzthrāx Sep 21 '17 at 10:37

2 Answers2

2

I am going to shamelessly plug this new datetime library I am obsessed with, Pendulum.

pip install pendulum

import pendulum

t = 1481079600

pendulum.from_timestamp(t).to_datetime_string()
>>> '2016-12-07 03:00:00'

And now to change it to your timezone super quick and easy!

pendulum.from_timestamp(t, 'Asia/Tokyo').to_datetime_string()
>>> '2016-12-07 12:00:00'
gold_cy
  • 13,648
  • 3
  • 23
  • 45
  • 2 lines of code perfect, i need to improve my google foo, I couldn't find a simple solution anywhere – David Hancock Dec 27 '16 at 21:18
  • It's a relatively new library, but it is amazing and I prefer it to the native Python one. Here is the documentation for all the cool things it can do. https://pendulum.eustace.io/docs/ – gold_cy Dec 27 '16 at 21:19
0

Your utc_time datetime is naive - it has no timezone associated with it. localize assigns a timezone to it, it doesn't convert between timezones. The simplest way to do that is probably to construct a timezone-aware datetime:

import pytz
utc_time = datetime.datetime.fromtimestamp(time, pytz.utc)

Then convert to the timezone you want when you're ready to display it:

print utc_time.astimezone(tz).strftime(fmt)
Peter DeGlopper
  • 36,326
  • 7
  • 90
  • 83