[英]Pandas: How to convert local time to utc?
I have a pandas dataframe where I have a column consisting of strings of date times, these I have converted to datetime with pd.to_datetime().我有一个 pandas dataframe ,其中有一列由日期时间字符串组成,这些我已使用 pd.to_datetime() 转换为日期时间。 Then I have tried to convert this column to UTC from Swedish Local time, but get an
NonExistentTimeError
when converting with pandas.然后我尝试将此列从瑞典当地时间转换为 UTC,但在使用
NonExistentTimeError
转换时会出现 NonExistentTimeError。 How do I resolve this without removing timestamps?如何在不删除时间戳的情况下解决此问题?
df['Time'] = pd.to_dataframe(df['Time'])
df['Time'] = df['Time'].dt.tz_localize('Europe/Stockholm')
My dataframe looks like this:我的 dataframe 看起来像这样:
Time![]() |
value![]() |
---|---|
2022-03-26 23:00:00 ![]() |
1 ![]() |
2022-03-27 00:00:00 ![]() |
5 ![]() |
2022-03-27 01:00:00 ![]() |
6 ![]() |
2022-03-27 02:00:00 ![]() |
8 ![]() |
2022-03-27 03:00:00 ![]() |
4 ![]() |
2022-03-27 04:00:00 ![]() |
11 ![]() |
2022-03-27 05:00:00 ![]() |
10 ![]() |
As the error作为错误
NonExistentTimeError: 2022-03-27 02:00:00
NonExistentTimeError:2022-03-27 02:00:00
tells you, that time did not exist in Stockholm local time.告诉你,那个时间在斯德哥尔摩当地时间是不存在的。 Due to the DST change, the hour after 1 am was 3 am, not 2 am.
由于 DST 更改,凌晨 1 点之后的时间是凌晨 3 点,而不是凌晨 2 点。 So to me, this looks like something wrong is happening during generation of this data, maybe worth investigating.
所以对我来说,这看起来像是在生成这些数据的过程中发生了一些错误,也许值得调查。
Anyways, what you can do is set nonexistent
keyword, eg like无论如何,你可以做的是设置
nonexistent
的关键字,例如
df['Time'] = pd.to_datetime(df['Time'])
df['Time'] = df['Time'].dt.tz_localize('Europe/Stockholm', nonexistent='NaT')
df['Time']
0 2022-03-26 23:00:00+01:00
1 2022-03-27 00:00:00+01:00
2 2022-03-27 01:00:00+01:00
3 NaT
4 2022-03-27 03:00:00+02:00
5 2022-03-27 04:00:00+02:00
6 2022-03-27 05:00:00+02:00
Name: Time, dtype: datetime64[ns, Europe/Stockholm]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.