(Assuming that you’re using dateutil.parser
)
When you call parser.parse
, the return (datetime_object
) is a variable of the type datetime
.
And this object can be formatted directly, through the method strftime
. In this method you pass the format you want (in this case, day/month/year) and the return is a string in this format.
Then you could just do:
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 exit is:
09/05/2018
Like parser.parse
returns a datetime
, there is no reason to convert it to string (using str
) and then parse again with strptime
. You’ve done the parse once (with parser.parse
) and obtained a datetime
, then just format it to the format you want, with strftime
.
Another alternative is to use the method strptime
*:
from datetime import datetime
dataAntiga = "2018-05-09T05:05:34Z"
# fazer o parse e obter um objeto datetime
datetime_object = datetime.strptime(dataAntiga, '%Y-%m-%dT%H:%M:%S%z')
# formatar o datetime para o formato desejado (dia/mês/ano)
dataFormatada = datetime_object.strftime("%d/%m/%Y")
print(dataFormatada) # 09/05/2018
*: the Z
at the end indicates that the date/time is in UTC, but unfortunately the Pattern %z
only recognizes the Z
from Python 3.7 as indicated in documentation:
Changed in version 3.7: When the %z Directive is provided to the strptime() method, ... providing 'Z' is identical to '+00:00'
In previous versions, the Z
is not recognized and gives error (Ideone.com, for example, uses Python 3.5, see how it doesn’t work in this version). In that case, it’s best to use dateutil
even.
Thanks, it worked out!
– priscyllat