I am unable to obtain an instance of a date with the GMT+2 format, that is, from the text string 2022-10-01 00:00:00 GMT+2
I want to obtain a datetime
.
My code is the following:
time_gmt: str = '2022-10-01 00:00:00 GMT+2'
mi_fecha = datetime.datetime.strptime(time_gmt, '%Y-%m-%d %H:%M:%S %Z')
The error I get with this format is: ValueError: unconverted data remains: +2
, because it doesn't know what to do with that "+2" of the GMT. I've looked at https://docs.python.org/3/library/datetime.html for the format to see if it's wrong, but I'm not sure if something else needs to be added to it, or treated in another way.
In the documentation it indicates the following fragment:
In strftime(),
%Z
is replaced by an empty string if tzname() returnsNone
; otherwise%Z
is replaced by the returned value, which must be a string.strptime() only accepts certain values for
%Z
:
- any value in
time.tzname
for your machine's locale- the hard-coded values
UTC
andGMT
So someone living in Japan may have
JST
,UTC
, andGMT
as valid values, but probably notEST
. It will raiseValueError
for invalid values.
From the error that appears, I understand that GMT+2
it is not a valid value, but then, what would be a valid value?
My only goal is from a string similar to this to 2022-10-01 00:00:00 GMT+2
get an object datetime
. If anyone knows of a way to do this, help would be greatly appreciated.
All the best
PS: thanks in advance
Good day,
You almost made it but there is a little confusion,
%Z
(With uppercase) is used to identify the name of the time zone and%z
(With lowercase) to assign the offset or offset in format±HHMM[SS[.ffffff]]
So it would be like this:
And now we see that it
mi_fecha
is an object of typedatetime
that has an offset ortimedelta
seconds7200
that is 2 hours and the time zone isGMT
If you print
mi_fecha
you will only get the following:If you want to see
mi_fecha
with the format you want then you have to include the format when printing:Example from the terminal: