pytz localize vs normalize

python 2018. 2. 26. 19:02

If you only want to convert to specific timezone, use localize. and forget normalize.

just use

tz2 = timezone("Asia/Seoul")
dt = datetime.datetime(year=2017, month=4, day=29, hour=8, minute=35, second=10)
dt2 = tz2.localize(dt)

utc_timestamp = dt2.timestamp()

this will calculate including DST time

but If you are going to do arithmetic operation(- or +) to your datetime object and It crosses DST start or end time,

you should use normalize(dt) to fix the utc offset.


refer to

https://github.com/newvem/pytz/blob/master/pytz/tzinfo.py

def normalize():

 '''Correct the timezone information on the given datetime

If date arithmetic crosses DST boundaries, the tzinfo

is not magically adjusted. This method normalizes the

tzinfo to the correct one.

To test, first we need to do some setup

>>> from pytz import timezone

>>> utc = timezone('UTC')

>>> eastern = timezone('US/Eastern')

>>> fmt = '%Y-%m-%d %H:%M:%S %Z (%z)'

We next create a datetime right on an end-of-DST transition point,

the instant when the wallclocks are wound back one hour.

>>> utc_dt = datetime(2002, 10, 27, 6, 0, 0, tzinfo=utc)

>>> loc_dt = utc_dt.astimezone(eastern)

>>> loc_dt.strftime(fmt)

'2002-10-27 01:00:00 EST (-0500)'

Now, if we subtract a few minutes from it, note that the timezone

information has not changed.

>>> before = loc_dt - timedelta(minutes=10)

>>> before.strftime(fmt)

'2002-10-27 00:50:00 EST (-0500)'

But we can fix that by calling the normalize method

>>> before = eastern.normalize(before)

>>> before.strftime(fmt)

'2002-10-27 01:50:00 EDT (-0400)'

'''



블로그 이미지

시간을 거스르는자

ytkang86@gmail.com

,