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.
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.