Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python pytz timezone gives just same as UTC time

On Linux, I'm trying to get timezone converted time using pytz. But, below code does not return correct 'Asial/Seoul' time.

from datetime import datetime
from pytz
seoul = pytz.timezone('Asia/Seoul')
curtime = seoul.localize(datetime.now())

This is how I tested in Linux. datetime.now() returns UTC time. And, pytz timezone with 'Asia/Seoul' also returns same UTC time.

enter image description here

I'm looking for answer how to get correct timezone time with pytz.

like image 823
Justin Avatar asked Feb 04 '26 17:02

Justin


1 Answers

You're localising a naïve datetime. This means you have a datetime with no timezone information; using localize on it means you're attaching timezone information where there previously was none. Compare:

>>> datetime.now()
datetime.datetime(2017, 4, 20, 14, 0, 0, 0)
>>> seoul.localize(datetime.now())
datetime.datetime(2017, 4, 20, 14, 0, 0, 0, tzinfo=<DstTzInfo 'Asia/Seoul' KST+9:00:00 STD>)

It's the same time, once with and once without timezone information.

If you want to get the current time in Seoul, you need to create the datetime with that timezone:

>>> datetime.now(tz=seoul)
datetime.datetime(2017, 4, 20, 21, 0, 0, 0, tzinfo=<DstTzInfo 'Asia/Seoul' KST+9:00:00 STD>)

Or, you take a timestamp which already has a timezone, and convert it:

>>> datetime.now(tz=timezone.utc).astimezone(seoul)
datetime.datetime(2017, 4, 20, 21, 0, 0, 0, tzinfo=<DstTzInfo 'Asia/Seoul' KST+9:00:00 STD>)

You cannot do a timezone conversion from a naïve timestamp (without timezone), since that inherently has no meaning.

like image 90
deceze Avatar answered Feb 07 '26 07:02

deceze



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!