Carson P
Carson P

Reputation: 313

How to change entire column's timezone?

I have a pandas dataframe as such:

           Date      Time     Open     High      Low    Close  Volume  OpenInt
0    2017-11-17  15:35:00  68.5300  68.7200  68.3800  68.6700   79411        0
1    2017-11-17  15:40:00  68.5956  68.6900  68.5600  68.5900   10014        0
2    2017-11-17  15:45:00  68.5700  68.6700  68.5100  68.6200   14182        0
3    2017-11-17  15:50:00  68.5900  68.6200  68.4900  68.5800   15756        0
4    2017-11-17  15:55:00  68.5500  68.6100  68.5100  68.5500   15984        0

and I just want to change the Time Column's timezone from Israel to UTC. What is the easiest and quickest way to do this for all the rows with that column? I need to loop this many times, FYI.

Thanks!

Upvotes: 0

Views: 258

Answers (2)

rafaelc
rafaelc

Reputation: 59264

Maybe this works for you

>>> new_dt = pd.to_datetime(df2.Date + " " + df2.Time).dt.tz_localize('Israel').dt.tz_convert('UTC')
>>> df.Date = new_dt.transform(lambda k:k.date())
>>> df.Time = new_dt.transform(lambda k:k.time())


        Date    Time        Open    High    Low     Close   Volume  OpenInt DateTime
0   2017-11-17  13:35:00    68.5300 68.72   68.38   68.67   79411   0   2017-11-17 15:35:00
1   2017-11-17  13:40:00    68.5956 68.69   68.56   68.59   10014   0   2017-11-17 15:40:00
2   2017-11-17  13:45:00    68.5700 68.67   68.51   68.62   14182   0   2017-11-17 15:45:00
3   2017-11-17  13:50:00    68.5900 68.62   68.49   68.58   15756   0   2017-11-17 15:50:00
4   2017-11-17  13:55:00    68.5500 68.61   68.51   68.55   15984   0   2017-11-17 15:55:00

The difference here is that you can get to keep both Date and Time columns.

Upvotes: 1

MaxU - stand with Ukraine
MaxU - stand with Ukraine

Reputation: 210822

Assuming that Date and Time are of object dtype:

In [54]: df['Date'] = (pd.to_datetime(df['Date'] + ' ' + df.pop('Time'))
                         .dt.tz_localize('Israel')
                         .dt.tz_convert('UTC'))

In [55]: df
Out[55]:
                       Date     Open   High    Low  Close  Volume  OpenInt
0 2017-11-17 13:35:00+00:00  68.5300  68.72  68.38  68.67   79411        0
1 2017-11-17 13:40:00+00:00  68.5956  68.69  68.56  68.59   10014        0
2 2017-11-17 13:45:00+00:00  68.5700  68.67  68.51  68.62   14182        0
3 2017-11-17 13:50:00+00:00  68.5900  68.62  68.49  68.58   15756        0
4 2017-11-17 13:55:00+00:00  68.5500  68.61  68.51  68.55   15984        0

Upvotes: 2

Related Questions