问题描述
我有两个datetime列,当我将它们读入内存时它们很幼稚,但实际上在美国/东部.我只想将这两列都转换为美国/中部".
I have two datetime columns which are naive when I read them into memory but which are in US/Eastern actually. I simply want to convert both of these columns to US/Central.
我找到了一种可行的方法,但似乎我正在解决问题.我将我的call_start和call_end列更改为"start"和"end",所以我不会以重复的列名结尾.然后,我为这些列中的每一个创建了一个单独的datetimeindex并重置了索引.
I found a method which works but it seems like I am doing a workaround.I changed my call_start and call_end columns to be named 'start' and 'end' instead so I don't end up with duplicate column names. I then created a separate datetimeindex for each of these columns and reset the index.
aht.set_index(pd.DatetimeIndex(aht['start']).tz_localize('US/Eastern').tz_convert('US/Central'), inplace = True, drop = True)
aht.index.names = ['call_start']
aht = aht.reset_index()
aht.set_index(pd.DatetimeIndex(aht['end']).tz_localize('US/Eastern').tz_convert('US/Central'), inplace = True, drop = True)
aht.index.names = ['call_end']
aht = aht.reset_index()
我最终得到:
call_end call_start start end
2016-01-13 06:05:01-06:00 2016-01-13 06:02:00-06:00 01/13/2016 07:02 01/13/2016 07:05
2016-01-13 06:07:00-06:00 2016-01-13 06:03:16-06:00 01/13/2016 07:03 01/13/2016 07:07
2016-01-13 06:09:13-06:00 2016-01-13 06:06:02-06:00 01/13/2016 07:06 01/13/2016 07:09
2016-01-13 06:17:51-06:00 2016-01-13 06:06:20-06:00 01/13/2016 07:06 01/13/2016 07:17
这是最好的方法吗?所有其他数据都在中央时间进行,因此我只想确保该文件也是如此,因此当我将文件合并在一起时,它就更有意义了.我不在乎实际的时区戳,在创建新列之后是否可以轻松剥离它?
Is this the best method? All other data is in central time so I just want to make sure that this file is too so when I merge files together it makes more sense. I do not care about having the actual timezone stamp there though - is there a way to easily strip it after I created my new columns?
推荐答案
您不需要往返于DatetimeIndex,因为对于Series(列)也可以通过dt
访问器使用这些方法: /p>
You don't need to do the roundtrip to DatetimeIndex, as these methods are avaliable for a Series (column) as well through the dt
accessor:
aht['call_start'] = aht['start'].dt.tz_localize('US/Eastern').dt.tz_convert('US/Central')
与end
相同.
要删除时区信息但将其保留在本地时间,请在此之后再执行一次.dt.tz_localize(None)
(请参阅以下问题: https://stackoverflow .com/a/34687479/653364 )
And the same for end
.
To remove the timezone information but keep it in the local time, you do another .dt.tz_localize(None)
afterwards (see this question: https://stackoverflow.com/a/34687479/653364)
这篇关于将datetime列转换为其他时区 pandas 的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!