在同一个pandas DatetimeIndex对象中使用不同时区的时间戳?

时间:2015-10-11 20:49:25

标签: python datetime pandas pytz

是否可以将由单个时区中的时间戳组成的pd.DatetimeIndex转换为每个时间戳都有自己的时间戳,在某些情况下是不同的时区?

以下是我想要的例子:

型(df.index)

 pandas.tseries.index.DatetimeIndex

df.index [0]

Timestamp('2015-06-07 23:00:00+0100', tz='Europe/London')

df.index [1]

Timestamp('2015-06-08 00:01:00+0200', tz='Europe/Brussels') 

3 个答案:

答案 0 :(得分:1)

如果您对它不是/** This is outside loop to capture my own author email not from within loop which is from other author's post **/ $MyEmail = the_author_email(); /** This is inside loop **/ <?php $args = array( 'post_id' => $post->ID, 'author_email' => $MyEmail, /** When I used comment_id it will displays all comments even I used my comment_id taken from outside the loop. Using 'author_email no comments displayed **/ ); $comments = get_comments($args); foreach($comments as $comment) : echo ($comment->comment_content); endforeach; ?> 感到高兴,而只是常规Index这应该没问题:

Series

答案 1 :(得分:1)

可以包含具有不同时区的Timestamps索引。但是你必须明确地将它构造为Index

In [33]: pd.Index([pd.Timestamp('2015-06-07 23:00:00+0100', tz='Europe/London'),pd.Timestamp('2015-06-08 00:01:00+0200', tz='Europe/Brussels')],dtype='object')
Out[33]: Index([2015-06-07 23:00:00+01:00, 2015-06-08 00:01:00+02:00], dtype='object')

In [34]: list(pd.Index([pd.Timestamp('2015-06-07 23:00:00+0100', tz='Europe/London'),pd.Timestamp('2015-06-08 00:01:00+0200', tz='Europe/Brussels')],dtype='object'))  
Out[34]: 
[Timestamp('2015-06-07 23:00:00+0100', tz='Europe/London'),
 Timestamp('2015-06-08 00:01:00+0200', tz='Europe/Brussels')]

这是一件非常奇怪的事情,完全不具备表现力。您通常希望表示单个时区(UTC或其他)。在0.17.0中,您可以有效地表示具有时区的单个列,因此实现我认为您的目标的一种方法是将不同的时区分隔到不同的列中。请参阅docs

答案 2 :(得分:0)

将具有不同时区的时间戳添加到同一DatetimeIndex中会自动生成DatetimeIndex,其中UTC为默认时区。例如:

In [269]  index = pandas.DatetimeIndex([Timestamp('2015-06-07 23:00:00+0100')])

In [270]  index
Out[270]  DatetimeIndex(['2015-06-07 23:00:00+01:00'], dtype='datetime64[ns, pytz.FixedOffset(60)]', freq=None)

In [271]  index2 = DatetimeIndex([Timestamp('2015-06-08 00:01:00+0200')])

In [272]  index2
Out[272]  DatetimeIndex(['2015-06-08 00:01:00+02:00'], dtype='datetime64[ns, pytz.FixedOffset(120)]', freq=None)

In [273]  index.append(index2)  # returns single index containing both data
Out[273]  DatetimeIndex(['2015-06-07 22:00:00+00:00', '2015-06-07 22:01:00+00:00'], dtype='datetime64[ns, UTC]', freq=None)

注意结果是如何保留正确的UTC时间戳的UTC DatetimeIndex

类似地:

In [279]  pandas.to_datetime([Timestamp('2015-06-07 23:00:00+0100'), Timestamp('2015-06-08 00:01:00+0200')], utc=True)  # utc=True is needed
Out[279]  DatetimeIndex(['2015-06-07 22:00:00+00:00', '2015-06-07 22:01:00+00:00'], dtype='datetime64[ns, UTC]', freq=None)

这不是一件坏事,因为您可以保留正确的时间,同时能够使用DatetimeIndex的索引功能(例如,按日期范围切片),同时您可以轻松转换时间戳到任何其他时区(除非你真的需要知道每个时间戳的原始时区,否则这不是理想的)。

相关问题