How to convert time zones of datetime column in Pandas?(如何在 Pandas 中转换 datetime 列的时区?)
问题描述
我有一列(非索引列),其中包含日期时间.例如,前五个条目如下所示:
I have a column (non-index column) that has datetimes inside it. For example, the first five entries look something like this:
[Timestamp('2018-11-15 19:57:55'),
Timestamp('2018-11-15 19:59:46'),
Timestamp('2018-11-15 20:00:59'),
Timestamp('2018-11-15 20:01:41'),
Timestamp('2018-11-15 20:01:54')]
我想将条目从 UTC 转换为太平洋时区.假设该列被称为 times
我目前正在执行以下操作:
I want to convert the entries from UTC to the Pacific timezone. Assuming the column is called times
I am currently doing the following:
times.dt.tz_localize('GMT').dt.tz_convert('America/Los_Angeles')
虽然这成功地将列从 UTC 转换为 PST,但输出包含我不想要的无关组件.如下所示:
While this successfully converts the column from UTC to PST, the output has extraneous components that I do not want. It looks like the following:
[Timestamp('2018-11-15 11:57:55-0800', tz='America/Los_Angeles'),
Timestamp('2018-11-15 11:59:46-0800', tz='America/Los_Angeles'),
Timestamp('2018-11-15 12:00:59-0800', tz='America/Los_Angeles'),
Timestamp('2018-11-15 12:01:41-0800', tz='America/Los_Angeles'),
Timestamp('2018-11-15 12:01:54-0800', tz='America/Los_Angeles')]
如何从时间戳中删除或忽略 -0800
?谢谢!
How do I remove or ignore the -0800
from the timestamps? Thanks!
推荐答案
只需添加最后一步.tz_localize(None)
:
import pandas as pd
d = pd.Series(['2018-11-15 19:57:55', '2018-11-15 19:59:46'])
d = pd.to_datetime(d)
d
0 2018-11-15 19:57:55
1 2018-11-15 19:59:46
dtype: datetime64[ns]
d_pacific_tz_aware = d.dt.tz_localize("GMT").dt.tz_convert('America/Los_Angeles')
d_pacific_tz_aware
0 2018-11-15 11:57:55-08:00
1 2018-11-15 11:59:46-08:00
dtype: datetime64[ns, America/Los_Angeles]
d_pacific_tz_naive = d.dt.tz_localize("GMT").dt.tz_convert('America/Los_Angeles').dt.tz_localize(None)
d_pacific_tz_naive
0 2018-11-15 11:57:55
1 2018-11-15 11:59:46
dtype: datetime64[ns]
这篇关于如何在 Pandas 中转换 datetime 列的时区?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 Pandas 中转换 datetime 列的时区?


基础教程推荐
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 筛选NumPy数组 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01