sam23
sam23

Reputation: 599

How To Convert ISOFormated date to Python datetime?

I have a datetime string in the format 2017-08-30T10:21:45.337312+00:00 send from django server using timezone.localtime(timezone.now()).isoformat()

I need to parse it back to a timezone object. How to do it?

I tried the following but its not working

kolkatta_tz = pytz.timezone("Asia/Kolkata")
kolkatta_tz.localize(datetime.strptime(product_list[index][5], '%Y-%m-%dT%H:%M:%S.%fZ'))

It throws the following error:

time data '2017-08-30T10:21:45.334742+00:00' does not match format '%Y-%m-%dT%H:%M:%S.%fZ'

Upvotes: 0

Views: 596

Answers (2)

Rowshi
Rowshi

Reputation: 357

Use dateutil's parser.parse method:

import dateutil

date_string = '2017-08-30T10:21:45.337312+00:00'
datetime_object = dateutil.parser.parse(date_string)
print(repr(datetime_object))

Gives you:

datetime.datetime(2017, 8, 30, 10, 21, 45, 337312, tzinfo=tzutc())

To get the tzinfo object:

datetime_object.tzinfo

Example:

print(datetime_object.tzinfo)

Outputs:

tzutc()

Sample Function:

import dateutil
import datetime

def get_timezone(date_string):
    dto = dateutil.parser.parse(date_string)
    if not isinstance(dto, datetime.datetime):
        return None
    return dto.tzinfo

Function Tests:

for o in xrange(-12, 12, 2):
     dstring = "2017-08-29T01:58:47.12321"
     if o >= 0:
         dstring += "+{:02n}:00".format(o)
     else:
         dstring += "{:03n}:00".format(o)
     print(get_timezone(dstring))

Returns:

tzoffset(None, -43200)
tzoffset(None, -36000)
tzoffset(None, -28800)
tzoffset(None, -21600)
tzoffset(None, -14400)
tzoffset(None, -7200)
tzutc()
tzoffset(None, 7200)
tzoffset(None, 14400)
tzoffset(None, 21600)
tzoffset(None, 28800)
tzoffset(None, 36000)

Upvotes: 3

PRADEEP PANDEY
PRADEEP PANDEY

Reputation: 344

The python-dateutil package can parse ISO 8601 and other date and time strings and.

>>> import dateutil.parser
>>> dateutil.parser.parse('2008-09-03T20:56:35.450686Z') # RFC 3339 format
datetime.datetime(2008, 9, 3, 20, 56, 35, 450686, tzinfo=tzutc())
>>> dateutil.parser.parse('2008-09-03T20:56:35.450686') # ISO 8601 extended format
datetime.datetime(2008, 9, 3, 20, 56, 35, 450686)
>>> dateutil.parser.parse('20080903T205635.450686') # ISO 8601 basic format
datetime.datetime(2008, 9, 3, 20, 56, 35, 450686)
>>> dateutil.parser.parse('20080903') # ISO 8601 basic format, date only
datetime.datetime(2008, 9, 3, 0, 0)

Upvotes: 2

Related Questions