-3

i've one doubt.

I'm doing request to an API which return me event date. I was hope that date will be a timestamp, but i get this value:

{"date":"2020-08-24T21:15:00+00:00"}

I want to get a python datetime object.

How can I do that?

kind26
  • 7
  • 1
  • 7

3 Answers3

2
from datetime import datetime

dates = {"date":"2020-08-24T21:15:00+00:00"}

date = dates.get("date")
day = datetime.strptime(date, "%Y-%m-%dT%H:%M:%S+00:00")

Your looking for strptime. Heres a good article: https://www.programiz.com/python-programming/datetime/strptime

  • 1
    you *could* also be looking for [fromisoformat](https://docs.python.org/3/library/datetime.html#datetime.datetime.fromisoformat) - it is [faster](https://stackoverflow.com/questions/13468126/a-faster-strptime) ;-) – FObersteiner Sep 07 '20 at 15:34
0

Use dateutil.parser which smartly parse date string:

import json
import dateutil.parser

result = '{"date":"2020-08-24T21:15:00+00:00"}'
x = json.loads(result)
dt = dateutil.parser.parse(x['date'])

# 2020-08-24 21:15:00+00:00
print(dt)

# <class 'datetime.datetime'>
print(type(dt))
Aviv Yaniv
  • 6,188
  • 3
  • 7
  • 22
0

I think you can do it respecting the format while parsing the string:

You have to try to follow the structure of the string and assign each value to the correct time value. For example:

str = '2018-06-29 08:15:27.243860'
time_obj = datetime.datetime.strptime(date_time_str, '%Y-%m-%d %H:%M:%S.%f')

Note that your case is pretty different. It could be similar to '%Y-%m-%dT%H:%M:%S.f'

Esme Povirk
  • 3,004
  • 16
  • 24
porteroi
  • 1
  • 1