gabriel
gabriel

Reputation: 33

Python extract a part of a json element

I have this json response:

"dataDeNascimento":"1980-03-30T00:00:00",

What i need is to the response be like this:

30/03/1980

The part of my code how represente this json:

        response = session.get(url, headers=headers)
        resp_json2 = response.json()
        nascimento = resp_json2['dataDeNacimento']

If you guys can help me i appreciate.

Upvotes: 1

Views: 38

Answers (2)

Chiheb Nexus
Chiheb Nexus

Reputation: 9267

You can use datetime from datetime module to convert your date string into datetime object then reconvert it into your desired date string again.

For example:

from datetime import datetime


date_ = "1980-03-30T00:00:00" 
new_date = datetime.strptime(date_, '%Y-%m-%dT%H:%M:%S').strftime('%d/%m/%Y')
print(new_date)

Output:

30/03/1980

Edit:

As @Mark Meyer suggested and if you're using Python >= 3.7 your can use datetime.fromisoformat

Upvotes: 2

Tristan
Tristan

Reputation: 23

You can chop up your string nascimento like this:

nascimento = resp_json2['dataDeNacimento'][:10]

Which will give you the first 10 characters as a string.

"1980-03-30"

Upvotes: -1

Related Questions