Error formatting string for python datetime

Asked

Viewed 1,096 times

1

I am trying to format a string with the format "2018-05-09T05:05:34Z" for "09/05/2018" but is 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 makes the mistake:

Valueerror: unconverted data remains: +00:00

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

Valueerror: unconverted data remains

2 answers

0

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

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')

0


(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!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.