gpt4 book ai didi

python pandas TimeStamps到具有夏令时的本地时间字符串

转载 作者:太空宇宙 更新时间:2023-11-03 12:47:07 26 4
gpt4 key购买 nike

我有一个带有 TimeStamps 列的数据框。我想将它转换为本地时间字符串,即夏令时。

所以我想将下面的 ts[0] 转换为“2015-03-30 03:55:05”。 Pandas 似乎知道夏令时,但只有当您在该系列上调用 .values 时才会知道。

谢谢

(Pdb) ts = df['TimeStamps']
(Pdb) ts
0 2015-03-30 02:55:05.993000
1 2015-03-30 03:10:20.937000
2 2015-03-30 10:09:19.947000
Name: TimeStamps, dtype: datetime64[ns]
(Pdb) ts[0]
Timestamp('2015-03-30 02:55:05.993000')
(Pdb) ts.values
array(['2015-03-30T03:55:05.993000000+0100',
'2015-03-30T04:10:20.937000000+0100',
'2015-03-30T11:09:19.947000000+0100'], dtype='datetime64[ns]')

最佳答案

DST 与您所在的位置相关(例如,伦敦 DST 比纽约晚几周开始)。您首先需要了解时间戳时区:

from pytz import UTC
from pytz import timezone
import datetime as dt

ts = pd.Timestamp(datetime.datetime(2015, 3, 31, 15, 47, 25, 901597))
# or...
ts = pd.Timestamp('2015-03-31 15:47:25.901597')
# ts is a Timestamp, but it has no idea where in the world it is...
>>> ts.tzinfo is None
True

# So the timestamp needs to be localized. Assuming it was originally a UTC timestamp, it can be localized to UTC.
ts_utc = ts.tz_localize(UTC)
# Once localized, it can be expressed in other timezone regions, e.g.:
eastern = pytz.timezone('US/Eastern')
ts_eastern = ts_utc.astimezone(eastern)
# And to convert it to an ISO string of local time (e.g. eastern):
>>> ts_eastern.isoformat()
'2015-03-30T08:09:27.143173-04:00'

参见 pytzdatetime获取更多信息。

关于python pandas TimeStamps到具有夏令时的本地时间字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29352705/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com