EDITED: I want to convert a UTC time in my country UTC (spain). I am using the module pytz to do the conversion but the result I am getting is UTC-1 rather than the UTC+1. This is my code:
import datetime
import pytz
madrid = pytz.timezone("Europe/Madrid")
UTC_time = datetime.datetime.strptime("2019-03-01 14:45","%Y-%m-%d %H:%M")
madrid_dt = madrid.localize(UTC_time, is_dst=None)
MadridTime = madrid_dt.astimezone(pytz.utc).strftime ("%Y-%m-%d %H:%M")
And this is the output:
UTC_Time: 2019-03-01 14:45:00
MadridTime: 2019-03-01 13:45
I need that MadridTime returns 15:45 instead 13:45. What am I doing wrong?
EDITED2: With your help I saw that I was confusing the use of localize and astimeszone. Now I am facing two new issues. This is the new code:
import datetime
import pytz
dt = datetime.datetime.strptime('2019-03-01 14:45','%Y-%m-%d %H:%M')
madrid_tz = pytz.timezone('Europe/Madrid')
madrid = dt.astimezone(madrid_tz)
print(madrid)
# 2019-03-01 14:45:00+01:00
print(madrid.strftime ("%Y-%m-%d %H:%M"))
# 2019-03-01 14:45
Issue 1: Running this code in Windows 10, Python3, the output I expected was 2019-03-01 15:45:00
rather than 2019-03-01 14:45:00+01:00
. I tried to format it with strftime ("%Y-%m-%d %H:%M")
but that didn't make the trick.
Issue 2: Running this code in Raspberrypi (which is where I will run the code when is finished), Python3, I get a ValueError in this line madrid = dt.astimezone(madrid_tz)
. The error is ValueError: astimezone() cannot be applied to a naive datetime
Any ideas?