I am converting non-timezone aware datetimes to timezone aware datetimes in Python using pytz.
It seems that astimezone
is over 3x faster than localize
.
Is there ever a reason to use localize
instead of astimezone
?
-------- Trial Name: Convert nonaware datetimes to timezone aware via localize
Totaltime: 1.854642400s
Time per loop: 18.546us
-------- Trial Name: Convert nonaware datetimes to timezone aware via astimezone
Totaltime: 0.584159600s
Time per loop: 5.842us
Trials done on a Intel(R) Core(TM) i7-7700HQ CPU @ 2.80GHz 2.81 GHz, 16GB ram running Windows 10 Home.
import timeit
numberOfTrials = 100000
def myTimeit(trialName, mysetup, mycode, numberOfTrials):
print(f'-------- Trial Name: {trialName}')
# timeit statement
totalTime = timeit.timeit(setup=mysetup,
stmt=mycode,
number=numberOfTrials)
print(f"Totaltime: {totalTime:0,.9f}s")
print(f"Time per loop: {totalTime / numberOfTrials * 1e6:0.3f}us")
print()
return totalTime
mysetup = '''
from datetime import datetime
import pytz
notTimezoneAware_datetime = datetime.strptime("220105 230310", '%y%m%d %H%M%S')
TOKYO_tz = pytz.timezone('Asia/Tokyo')
'''
myTimeit(trialName='Convert nonaware datetimes to timezone aware via localize',
mysetup=mysetup,
mycode='TOKYO_tz.localize(notTimezoneAware_datetime)',
numberOfTrials=numberOfTrials)
myTimeit(trialName='Convert nonaware datetimes to timezone aware via astimezone',
mysetup=mysetup,
mycode='notTimezoneAware_datetime.astimezone(TOKYO_tz)',
numberOfTrials=numberOfTrials)
To clarify my comment,
localize
sets the time zone for a naive datetime object. It does not change the object's attributes (date/time)astimezone
takes a given datetime object, naive or aware, and converts the date/time to the desired time zone. If the datetime object is naive, it is assumed to be local time.EX:
from datetime import datetime
import pytz
# just localize to a certain time zone.
pytz.timezone("America/Denver").localize(datetime(2022, 5, 15))
Out[3]: datetime.datetime(2022, 5, 15, 0, 0, tzinfo=<DstTzInfo 'America/Denver' MDT-1 day, 18:00:00 DST>)
# convert to the desired time zone; note that my local time zone is UTC+2
# US/Denver is at UTC-6 on May 15th 2022, so total shift is 8 hours:
datetime(2022, 5, 15).astimezone(pytz.timezone("America/Denver"))
Out[4]: datetime.datetime(2022, 5, 14, 16, 0, tzinfo=<DstTzInfo 'America/Denver' MDT-1 day, 18:00:00 DST>)
To answer the question: no, there is no benefit. You're dealing with methods that have different purposes.
As a side note, the Python 3.9+ standard library actually offers a benefit:
from zoneinfo import ZoneInfo
%timeit pytz.timezone("America/Denver").localize(datetime(2022, 5, 15))
16.8 µs ± 30.3 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
%timeit datetime(2022, 5, 15).replace(tzinfo=ZoneInfo("America/Denver"))
1.19 µs ± 5.83 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)