1

Currently I'm writing a small python application where I get a date of the following format (RFC3339) from a webserver:

2016-01-29T20:00:00+01:00

I have to parse this date to a python datetime object and for this I would like to use the datetime.strptime method where I have to specify the format of the date but I don't know how to parse the timezone (+01:00) I tried with:

datetime.strptime(strDate, "%Y-%m-%dT%H:%M:%S%z")

but this does not work. Can you please tell me which format string I have to use?

Community
  • 1
  • 1
Cilenco
  • 6,951
  • 17
  • 72
  • 152

2 Answers2

3

You could use dateutil, however, if you are using Python 3 it only works for 3.2 or 3.3. It also supports Python 2 on 2.6 and 2.7.

The solution I would suggest:

from dateutil.parser import parse

string = "2016-01-29T20:00:00+01:00"

date = parse(string)

This will give you a datetime object like so:

Out[1]: 2016-01-29 20:00:00+01:00
Out[2]: datetime.datetime(2016, 1, 29, 20, 0, tzinfo=tzoffset(None, 3600))

If you'd like to know more, check dateutil documentation.

Moreover, I believe the reason strptime doesn't work straight away here is due to that 'T' on your date string. It's not the format strptime expects. Luckily dateutil parse method works right out of the box to fix that string for you.

Charles David
  • 202
  • 2
  • 11
2

Can you do this,

strDate = strDate.split('+')

datetime.strptime(strDate[0], "%Y-%m-%dT%H:%M:%S")

This will work for you

Kamlesh
  • 2,032
  • 2
  • 19
  • 35