arbi-g11324115
arbi-g11324115

Reputation: 223

Python parsing date with strptime

I have url that returns date in this format

url_date = "2015-01-12T08:43:02Z"

I don't know why there are strings, it would have been simpler to get it as "2015-01-1208:43:02" which would have been simpler to parse using

datetime.datetime.strptime(url_date , '%Y-%m-%d')

but it does not work. I have tried with

%Y-%m-%d
%Y-%m-%d-%H-%M-%S
%Y-%m-%d-%H-%M-%S-%Z

But I keep getting errors like "time data 2015-01-12T08:43:02Z does not match ..."

Upvotes: 3

Views: 1329

Answers (2)

Anand S Kumar
Anand S Kumar

Reputation: 90879

The format you are looking for is - '%Y-%m-%dT%H:%M:%SZ' .

Example -

>>> url_date = "2015-01-12T08:43:02Z"
>>> import datetime
>>> datetime.datetime.strptime(url_date , '%Y-%m-%dT%H:%M:%SZ')
datetime.datetime(2015, 1, 12, 8, 43, 2)

For the new requirement in comments -

if I wanted to get a time back with the strings as in 2015-01-12:08:43:02 which methods should after datetime().datetime()

You would need to use .strftime() on the datetime.datetime object with the format - '%Y-%m-%d:%H:%M:%S'. Example -

>>> url_date = "2015-01-12T08:43:02Z"
>>> dt = datetime.datetime.strptime(url_date , '%Y-%m-%dT%H:%M:%SZ')
>>> dt.strftime('%Y-%m-%d:%H:%M:%S')
'2015-01-12:08:43:02'

If you wanted the time component , you can use .time() for that. Example -

>>> dt = datetime.datetime.strptime(url_date , '%Y-%m-%dT%H:%M:%SZ')
>>> dt.time()
datetime.time(8, 43, 2)

Upvotes: 5

Kevin
Kevin

Reputation: 76184

You were getting close with the "Z" in your final attempt - you need to specify the T, Z, and colon literal values in your format string.

>>> import datetime
>>> url_date = "2015-01-12T08:43:02Z"
>>> datetime.datetime.strptime(url_date , '%Y-%m-%dT%H:%M:%SZ')
datetime.datetime(2015, 1, 12, 8, 43, 2)

Upvotes: 5

Related Questions