Python Pandas时间戳转换为带有夏令时的本地时间字符串

5

我有一个带有时间戳列的数据框。我想把它转换成本地时间的字符串,即考虑到夏令时。

因此,我希望将下面的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]')

你所在的本地时区是什么(例如 Europe/London)?2015年3月30日是否有夏令时转换? - jfs
嗨,是的,DST在2015年3月29日开始。 UTC中的时间戳是正确的,但我找不到将其显示为伦敦时间字符串的方法。@Alexander搞定了。 - jf328
将Pandas时间戳转换为不同时区 - jfs
1个回答

14

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


如果dtdatetime模块的话,那么在这里使用utcnow()代替now() - jfs
当然可以,但重点是展示如何将本地时间戳转换为UTC时间('now'实例只是一个示例)。在处理时间时,始终使用UTC时间被认为是最佳实践,除非进行显示。 - Alexander
欧洲/伦敦时区 ≠ UTC!不要使用.now()(返回本地时区时间),而是使用.utcnow()(返回UTC时间)! - jfs
从来没有说他们是,但是我更新了这个例子以澄清步骤。 - Alexander
请注意,在这种情况下使用.now()而不是.utcnow()等同于说Europe/London== UTC(OP的本地时区为Europe/London)。 - jfs
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接