Brandon Atkinson
Brandon Atkinson

Reputation: 33

Python3 date and time formatting

I'm using an API that sends a date in a wierd format "YYYY-MM-DDTHH:MM:SSZ". So the date comes out as 2018-04-27T23:59:18Z, I have never seen a date and time formatted like this. Its a string and I would like to format it as MM-DD-YYYY HH:MM:SS. I can't even wrap my head around removing the T and Z. Any help would be appreciated! Thanks in advance!

Upvotes: 2

Views: 171

Answers (3)

Chiheb Nexus
Chiheb Nexus

Reputation: 9257

Use this pattern:

import datetime

d = '2018-04-27T23:59:18Z'
myDate = datetime.datetime.strptime(d, '%Y-%m-%dT%H:%M:%SZ')
# datetime.datetime(2018, 4, 27, 23, 59, 18)

Then to get a datetime string use strftime:

myDate_str = myDate.strftime('%Y-%m-%d %H:%M:%S')
# '2018-04-27 23:59:18'

Upvotes: 1

timgeb
timgeb

Reputation: 78650

Create datetime.datetime object from your string via datetime.strptime, then turn it back into a string with its strftime method.

>>> from datetime import datetime
>>> s = "2018-04-27T23:59:18Z"
>>> datetime.strptime(s, '%Y-%m-%dT%XZ').strftime('%m-%d-%Y %X')
>>> '04-27-2018 23:59:18'

strptime and strftime behavior

(Depending on you locale you might have to use %H, %M and %S instead of %X.)

Upvotes: 2

Julian
Julian

Reputation: 2634

That looks like the ISO 8601 time format.

For reasons that I really don't understand, there's no standard library function that parses ISO 8601 correctly. The dateutil package that you can find on PyPI will parse it for you though.

Upvotes: 1

Related Questions