mgchco
mgchco

Reputation: 13

How to convert datetime to different timezone?

I'm trying to convert a datetime string into a different timezone. My code works but the result is not what I'm looking for.

I've already tried .localize() and .astimezone but the output is the same.

phtimezone = timezone('Asia/Manila')
test = datetime.datetime.strptime('Sun Sep 16 03:38:40 +0000 2018','%a %b %d %H:%M:%S +0000 %Y')
date = phtimezone.localize(test)
print (date) 
date = test.astimezone(phtimezone)
print (date)

The output is 2018-09-16 03:38:40+08:00. I was expecting it to be 2018-09-16 11:38:40+08:00.

Upvotes: 0

Views: 1174

Answers (2)

mgchco
mgchco

Reputation: 13

I was able to fix it thanks to @deceze. Here is the code:

phtimezone = pytz.timezone('Asia/Manila')
test = datetime.datetime.strptime('Sun Sep 16 03:38:40 +0000 2018','%a %b %d %H:%M:%S %z %Y')
test_utc = test.replace(tzinfo=timezone('UTC'))
date = test_utc.astimezone(pytz.timezone('Asia/Manila'))
print (date)

The output is now 2018-09-16 11:38:40+08:00

Upvotes: 0

deceze
deceze

Reputation: 522513

Your parsed object test does not contain a timezone. It's a naïve datetime object. Using both localize and astimezone cannot do any conversion, since they don't know what they're converting from; so they just attach the timezone as given to the naïve datetime.

Also parse the timezone:

datetime.strptime('Sun Sep 16 03:38:40 +0000 2018','%a %b %d %H:%M:%S %z %Y')
                                                                      ^^

This gives you an aware datetime object in the UTC timezone which can be converted to other timezones.

Upvotes: 1

Related Questions