keynesiancross
keynesiancross

Reputation: 3529

python + converting time zone, astimezone() not returning expected value

I have the current DateTime64 object (from pandas). It's currently in GMT. Its string form is:

time = 2017-01-02 23:00:00

I then try to convert it from GMT to EST.

dt = timezone('GMT').localize(time)
time = dt.astimezone(timezone('US/Eastern'))

When I run this, this returns (in string form)

2017-01-02 23:00:00+00:00

Ie, its not converting it from GMT to EST. Any idea why?

Upvotes: 0

Views: 1372

Answers (1)

tomcy
tomcy

Reputation: 455

You may use pytz to transfer the timezone as following:

import pytz
import datetime

gmt = pytz.timezone('GMT')
eastern = pytz.timezone('US/Eastern')
time = "2017-01-02 23:00:00"
date = datetime.datetime.strptime(time, '%Y-%m-%d %H:%M:%S')
print(date)
dategmt = gmt.localize(date)
print(dategmt)
dateeastern = dategmt.astimezone(eastern)
print(dateeastern)

First you have to read the time as local time and localize it, then use astimezone to make it as eastern time. Hope this can help.

Upvotes: 2

Related Questions