Easy way to convert UTC to another timezone in python

7.2k views Asked by At

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

2

There are 2 answers

2
gold_cy On BEST ANSWER

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'
2
Peter DeGlopper On

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)