Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Module pytz: UTC decrease instead of increase

Tags:

python

utc

pytz

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?

like image 620
Dani LA Avatar asked Mar 01 '19 15:03

Dani LA


1 Answers

Let's make it a little clearer what's what here:

madrid = pytz.timezone('Europe/Madrid')

The timezone Europe/Madrid, which is UTC+1/+2.

naive_ts = datetime.strptime('2019-03-01 14:45', '%Y-%m-%d %H:%M')

A naïve timestamp without any particular timezone.

madrid_ts = madrid.localize(naive_ts)

The same timestamp, now with the timezone Europe/Madrid attached, i.e. 14:45 in Madrid (UTC+1).

utc_ts = madrid_ts.astimezone(pytz.utc)

The same time as 14:45 in Madrid (UTC+1) in UTC, so, 14:45 - 1 hour → 13:45. All as expected. If it's 14:45 in Madrid, it's 13:45 in UTC, because Madrid is one hour ahead of UTC.

datetime.now()

Whatever that is… it has nothing to do with any of the two timestamps above, and depends on the default timezone of your machine and the current time there when you execute this code.

like image 176
deceze Avatar answered Sep 22 '22 23:09

deceze