Error formatting string for datetime python

1

I'm trying to format a string with the format "2018-05-09T05: 05: 34Z" to "05/05/2018", but given the error ValueError: unconverted data remains

If I use:

dataAntiga = "2018-05-09T05:05:34Z"
datetime_object = parser.parse(dataAntiga)
dateTemp = datetime.strptime(str(datetime_object), '%Y-%m-%d %H:%M:%S')

The result is 2018-05-09 05:05:34+00:00 and gives the error:

  

ValueError: unconverted data remains: +00: 00

Your I directly use data = datetime.strptime(dataAntiga, '%Y-%m-%d %H:%M:%S') , will also give the error:

  

ValueError: unconverted data remains

    
asked by anonymous 04.06.2018 / 03:44

2 answers

-1

(Assuming you are using dateutil.parser )

When you call parser.parse , the return ( datetime_object ) is a variable of type datetime .

And this object can be formatted directly, using the strftime method. In this method you pass the format you want (in this case, day / month / year) and the return is a string in this format.

So you could just do it:

import dateutil.parser

dataAntiga = "2018-05-09T05:05:34Z"

# fazer o parse e obter um objeto datetime
datetime_object = dateutil.parser.parse(dataAntiga)

# formatar o datetime para o formato desejado (dia/mês/ano)
dataFormatada = datetime_object.strftime("%d/%m/%Y")
print(dataFormatada)

The output is:

  

09/05/2018

As parser.parse returns a datetime , you do not have to convert it to string (using str ) to then parse again with strptime . You have already parse once (with parser.parse ) and got datetime , then just format it to the format you want, with strftime .

    
04.06.2018 / 14:13
-1

If it makes no difference to you, add the parameter ignoretz=True when calling the parse() method:

from datetime import datetime
from dateutil.parser import parse

data = parse("2018-05-09T05:05:34Z", ignoretz=True)

print datetime.strptime(str(data), '%Y-%m-%d %H:%M:%S')
    
04.06.2018 / 05:23