David Hancock
David Hancock

Reputation: 473

Easy way to convert UTC to another timezone in python

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

Upvotes: 1

Views: 8103

Answers (2)

gold_cy
gold_cy

Reputation: 14216

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'

Upvotes: 3

Peter DeGlopper
Peter DeGlopper

Reputation: 37319

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)

Upvotes: 0

Related Questions