将Pandas DF列从UTC转换为没有日期的美国东部时间 [英] Convert Pandas DF column from UTC to US-Eastern time without date
问题描述
我有此Pandas数据框列:
I have this Pandas dataframe column:
time_UTC
0 2015-01-05 16:44:34+00:00
1 2015-08-11 16:44:38+00:00
2 2015-08-02 16:53:25+00:00
3 2015-08-17 16:53:25+00:00
4 2015-09-28 16:53:26+00:00
Name: time_UTC, dtype: datetime64[ns, UTC]
,然后我使用以下命令将其从UTC转换为美国东部时区:
and I converted it from UTC to US-Eastern timezone using:
list_temp = []
for row in df['time_UTC']:
list_temp.append(Timestamp(row, tz = 'UTC').tz_convert('US/Eastern'))
df['time_EST'] = list_temp
得到这个:
0 2015-01-05 11:44:34-05:00
1 2015-08-11 11:44:38-05:00
2 2015-08-02 11:53:25-05:00
3 2015-08-17 11:53:25-05:00
4 2015-09-28 11:53:26-05:00
Name: time_EST, dtype: datetime64[ns, US/Eastern]
现在,我需要删除条目中的日期部分,以便仅获得时间.这是我需要的:
Now, I need to drop the date part of the entries so that I only get the time. Here is what I need:
0 11:44:34-05:00
1 11:44:38-05:00
2 11:53:25-05:00
3 11:53:25-05:00
4 11:53:26-05:00
Name: time_EST, dtype: datetime64[ns, US/Eastern]
尝试:
我尝试过:
print df['time_EST'].apply(lambda x: dt.time(x.hour,x.minute,x.second))
进行转换,以便删除日期,我只有时间.但是它正在恢复为UTC时区.这是上面命令的输出:
The conversion is made so that date is dropped and I only get time. But it is reverting back to the UTC timezone. Here is the output of the above command:
0 16:44:34
1 16:44:38
2 16:53:25
3 16:53:25
4 16:53:26
Name: time_EST, dtype: object
问题:
有没有办法在不自动恢复为UTC的情况下将日期和时间保持为美国东部时间?
Is there a way to drop the date and keep time as US-Eastern, without automatically reverting back to UTC?
要重新创建问题,只需复制上面的第一个DataFrame并使用此代码:
To recreate the problem, just copy the first DataFrame above and use this code:
import pandas as pd
from pandas.lib import Timestamp
import datetime as dt
df = pd.read_clipboard()
然后复制问题中其余的代码行.对于此问题的任何帮助将不胜感激.
Then copy the remaining lines of code from the question. Any assistance with this problem would be greatly appreciated.
推荐答案
您要使用strftime
设置字符串格式,还请注意矢量化日期操作:
You want to use strftime
to format your string, also note the vectorized date manipulations:
df = pd.read_clipboard()
df.time_UTC = pd.to_datetime(df.time_UTC)
df['EST'] = (df.time_UTC.dt.tz_localize('UTC')
.tz_convert('US/Eastern')
.strftime("%H:%M:%S"))
In [41]: df
Out[41]:
time_UTC EST
time_UTC
2016-02-15 16:44:34 2016-02-15 16:44:34 11:44:34
2016-02-15 16:44:38 2016-02-15 16:44:38 11:44:38
2016-02-15 16:53:25 2016-02-15 16:53:25 11:53:25
2016-02-15 16:53:25 2016-02-15 16:53:25 11:53:25
2016-02-15 16:53:26 2016-02-15 16:53:26 11:53:26
这篇关于将Pandas DF列从UTC转换为没有日期的美国东部时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!