0

I have date in the following format "2020-03-22T03:15:05+00:00" in Python. I need to convert this to "%Y-%m-%d %H:%m:%s". I am trying to do this using dateutil but could not find anything.

Can anyone please help

d = "2020-03-22T03:15:05+00:00"

print(d)

t = dateutil.parser.parse(d)    

time = t.strftime('%Y-%m-%d')

I need some idea to extract date and time from above code

Jérôme
  • 13,328
  • 7
  • 56
  • 106
noopur kharche
  • 59
  • 1
  • 11

2 Answers2

3

Python 3.7 introduces fromisoformat.

import datetime as dt

d = "2020-03-22T03:15:05+00:00"
dt.datetime.fromisoformat(d).strftime("%Y-%m-%d %H:%M:%S")
Jérôme
  • 13,328
  • 7
  • 56
  • 106
3

You can use datetime.strptime() plus datetime.strftime() from the standard library:

>>> import datetime as dt
>>> d = "2020-03-22T03:15:05+00:00"
>>> t = dt.datetime.strptime(d, "%Y-%m-%dT%H:%M:%S%z")
>>> t
datetime.datetime(2020, 3, 22, 3, 15, 5, tzinfo=datetime.timezone.utc)
>>> t.strftime("%Y-%m-%d %H:%M:%S")
'2020-03-22 03:15:05'
Brad Solomon
  • 38,521
  • 31
  • 149
  • 235
  • With Python 3.7, the ISO 8601 string parsing has a dedicated method: `fromisoformat`. – Jérôme Apr 13 '20 at 18:30
  • 1
    Yes @Jérôme, indeed it does. However, in this case the user is assumed to be parsing a strict and known input format. So using [`_parse_isoformat_date`](https://github.com/python/cpython/blob/96b1c59c71534db3f0f3799cd84e2006923a5098/Lib/datetime.py#L264) would instead potentially run through a whole slew of code branches. – Brad Solomon Apr 13 '20 at 18:33
  • Good point. It makes sense to specify the format manually in this case if performance matters. – Jérôme Apr 13 '20 at 18:44