String to date with timezone in python 3.3

I can convert the time below if I trim the timezone data using code:



However, when I use% z or% Z along with timezone data, I get the following error, can you please explain where I am going wrong, I am using python 3.3 and% z should work in it.




ValueError: time data '2014-09-16T19:26:18.5455599+05:30' does not match format '%Y-%m-%dT%H:%M:%S.%f%Z'



source to share

1 answer

There are two problems:

  • the length of the miliseconds component is 7 digits, but Python expects 6.
  • the timezone offset contains a colon :


Removing those two extra characters does the job strptime()


>>> import datetime
>>> cctext = '2014-09-16T19:26:18.5455599+05:30'
>>> cctext[:-7] + cctext[-6:-3] + cctext[-2:]
>>> datetime.datetime.strptime(cctext[:-7] + cctext[-6:-3] + cctext[-2:], "%Y-%m-%dT%H:%M:%S.%f%z")
datetime.datetime(2014, 9, 16, 19, 26, 18, 545559, tzinfo=datetime.timezone(datetime.timedelta(0, 19800)))




All Articles