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

1

2 Answers 2

3

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' 
Sign up to request clarification or add additional context in comments.

2 Comments

2 lines of code perfect, i need to improve my google foo, I couldn't find a simple solution anywhere
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. pendulum.eustace.io/docs
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) 

2 Comments

where 'tz' comes from where?
Well, in this example it comes from tz = timezone('Japan') in the question. You do of course have to know what time zone you want to localize to.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.