我想将 pd.DatetimeIndex 的时区与 pytz.timezone 进行比较,以查看 DatetimeIndex 是否具有预期的时区。但比较失败,可能是因为使用 tzinfo 参数不起作用,如本答案中所述。
import pandas as pd
import pytz
import unittest
tzstr = 'Europe/Vienna'
manual_tz = pytz.timezone(tzstr)
timestamp = pd.to_datetime('2020-03-02 07:00:00+01:00').tz_convert(tzstr)
tc = unittest.TestCase()
tc.assertEqual(timestamp.tz, manual_tz)
AssertionError: <DstTzInfo 'Europe/Vienna' CET+1:00:00 STD> != <DstTzInfo 'Europe/Vienna' LMT+1:05:00 STD>
如何检查 timestamp
的时区是否符合预期?在我看来,它应该与 pytz.timezone 相同,但是 pytz 和/或 pandas 的行为使它们在某种程度上有所不同。
如果无法进行这样的比较,则提出替代问题:我必须注意什么,才能不再遇到这个问题?这种事已经不止一次地发生在我身上了。我发现了一个 与此类似的问题,但必须使用多个日期来比较偏移量是否始终相同似乎并不喜欢最好的方式。
I want to compare the timezone of a pd.DatetimeIndex with a pytz.timezone to see if the DatetimeIndex has the expected timezone. But the comparison fails, possibly because using the tzinfo argument does not work as explained in this answer.
import pandas as pd
import pytz
import unittest
tzstr = 'Europe/Vienna'
manual_tz = pytz.timezone(tzstr)
timestamp = pd.to_datetime('2020-03-02 07:00:00+01:00').tz_convert(tzstr)
tc = unittest.TestCase()
tc.assertEqual(timestamp.tz, manual_tz)
AssertionError: <DstTzInfo 'Europe/Vienna' CET+1:00:00 STD> != <DstTzInfo 'Europe/Vienna' LMT+1:05:00 STD>
How can I check that the timezone of timestamp
is as expected? It should be the same as pytz.timezone
in my opinion, but the behavior of pytz and/or pandas makes them somehow different.
Alternative question formulation if it is not possible to make a comparison like this: What do I have to look out for, to not come across this problem any more? It did happen to me more than once already. I found a question similar to this, but having to use multiple dates to compare if the offset is always the same does not seem like the best way to.
发布评论
评论(1)
我认为您的问题与此答案相关
这就是我运行代码时所得到的:
您可以做的是:
但是 IHMO,必须创建两个日期来比较时区信息很奇怪。
比较时区是什么意思?您想检查什么?
编辑
关于测试时区和转换。我要做的就是找到你想要检查的测试用例。我要检查的是我是否正确处理了 DST 更改,为此我会执行以下操作:
第一个
to_datetime
调用中的参数utc=True
是强制性的:相反,从 文档。
I think your matter is linked to this answer
This is what I have when I run your code:
What you can do is this:
But IHMO, it's weird to have to create two dates for comparing the timezone information.
What do you mean by compare the timezone? What do you want to check?
Edit
About testing timezone and conversions. What I would do is find test cases you want to check. Something I would check is that I correctly handle the DST change, for this I would do something like this:
The parameter
utc=True
in the firstto_datetime
call is mandatory:From the documentation.