Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
256 views
in Technique[技术] by (71.8m points)

python - Convert datetime columns to a different timezone pandas

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.

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()

I end up getting:

                 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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')

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...