为什么 pd.to_datetime() 仅在 utc 为真时才更改类型?

Why is pd.to_datetime() only changing type if utc is True?

在 VS Code 中将我的 csv 文件加载到笔记本中后,我想将某些列的列类型从 object 更改为 datetime。所以我做了以下事情:

列的对象值

这些是列中的示例值。

my_col_1 -> 2022-02-07 20:19:04+01:00
my_col_2 -> 2020-10-27
my_col_3 -> 2020-10-27 16:00:00+01:00
my_col_4 -> 2020-10-27 18:00:00+01:00

检查

df_example.dtypes

my_col_1 object
my_col_2 object
my_col_3 object
my_col_4 object

转换

format_1 = '%Y-%m-%d %H:%M:%S' 
format_2 = '%Y-%m-%d' 

df_example['my_col_1'] = pd.to_datetime(df_example['my_col_1'], format=format_1, 
    exact=True, errors='raise', utc=False)

df_example['my_col_2'] = pd.to_datetime(df_example['my_col_2'], format=format_2,
        exact=True, errors='raise', utc=False)
    
df_example['my_col_3'] = pd.to_datetime(df_example['my_col_3'],format=format_1,
        exact=True, errors='raise', utc=False)
    
df_example['my_col_4'] = pd.to_datetime(df_example['my_col_4'],format=format_1,
        exact=True, errors='raise', utc=False)

检查

转换列后我想检查是否一切正常。

df_example.dtypes

my_col_1 datetime64[ns, pytz.FixedOffset(60)]
my_col_2 datetime64[ns]
my_col_3 object
my_col_4 object

这很奇怪。 my_col_3my_col_4 似乎没有转换。但与此同时,在处理代码时也没有出现问题或错误。 my_col_3my_col_4my_col_1 具有完全相同的格式,但未进行转换。

第二种方法

让我们将 utc=False 更改为 utc=True

df_example['my_col_3'] = pd.to_datetime(df_example['my_col_3'],format=format_1,
        exact=True, errors='raise', utc=True)
    
df_example['my_col_4'] = pd.to_datetime(df_example['my_col_4'],format=format_1,
        exact=True, errors='raise', utc=True)

检查

让我们再检查一下。

df_example.dtypes

my_col_1 datetime64[ns, pytz.FixedOffset(60)]
my_col_2 datetime64[ns]
my_col_3 datetime64[ns, UTC]
my_col_4 datetime64[ns, UTC]

现在我有

问题

这很奇怪。我不希望 my_col_3my_col_4 转换为 UTC+00:00 时区,因为我住在 UTC+01:00.

我是否必须引入另一个流程步骤并再次将我的时区重新应用到这些列?但这似乎是多余的。为什么不像 pandas 在 my_col_1 中那样简单地使用列中已经给出的时区?我可以告诉 pd.to_datetime() 我的时区是什么吗?喜欢 utc=Truetz=01:00?

这是我的解决方案。用 dt.tz_convert('Europe/Berlin') 转换它就可以了。所以我想没有办法只采用已经给定的 +01:00 值。将带有 to_datetime 的列转换为 UTC +00:00,然后您必须再次将其转换为您的时区。

df_example['my_col_3'] = pd.to_datetime(df_example['my_col_3'],format=format_1,
        exact=True, errors='raise', utc=True).dt.tz_convert('Europe/Berlin')
    
df_example['my_col_4'] = pd.to_datetime(df_example['my_col_4'],format=format_1,
        exact=True, errors='raise', utc=True).dt.tz_convert('Europe/Berlin')

现在我的列已更改为具有正确时区的日期时间

df_example.dtypes

my_col_3 datetime64[ns, Europe/Berlin]
my_col_4 datetime64[ns, Europe/Berlin]