从无意识到有意识时,在 pytz 中使用 localize 而不是 astimezone 有什么好处吗?

问题描述 投票:0回答:1
我正在使用 pytz 将 Python 中的非时区感知日期时间转换为时区感知日期时间。

看起来

astimezone

localize
 快 3 倍以上。

是否有理由使用

localize

 而不是 
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
在运行 Windows 10 Home 的 Intel(R) Core(TM) i7-7700HQ CPU @ 2.80GHz 2.81 GHz、16GB RAM 上进行的试验。

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)

pytz sourceforge 文档的完整性

python datetime timezone pytz
1个回答
3
投票
为了澄清我的评论,

  • localize
     设置原始日期时间对象的时区。它不会更改对象的属性(日期/时间)
  • astimezone
     接受给定的日期时间对象(无论是天真的还是有意识的),并将日期/时间转换为所需的时区。如果日期时间对象很简单,则假定它是本地时间。
例如:

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>)
回答问题:不,没有任何好处。您正在处理具有不同目的的方法。


顺便说一句,Python 3.9+ 标准库实际上提供了一个好处:

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)
    
© www.soinside.com 2019 - 2024. All rights reserved.