Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

string to date with Timezone in python 3.3

I am able to convert the below date time if I trim of the timezone data by using the code:

print(datetime.datetime.strptime(cc.text[:25],"%Y-%m-%dT%H:%M:%S.%f"))

However, when I use %z or %Z along with the time zone data, I am receiving the below error, could you please make me understand where I am going wrong, I am using python 3.3 and %z should work in it.

print(datetime.datetime.strptime(cc.text,"%Y-%m-%dT%H:%M:%S.%f%z"))

Error:

ValueError: time data '2014-09-16T19:26:18.5455599+05:30' does not match format '%Y-%m-%dT%H:%M:%S.%f%Z'
like image 428
surpavan Avatar asked Jul 16 '26 15:07

surpavan


1 Answers

There are two problems:

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

Removing those two extra characters makes strptime() work:

>>> import datetime
>>> cctext = '2014-09-16T19:26:18.5455599+05:30'
>>> cctext[:-7] + cctext[-6:-3] + cctext[-2:]
'2014-09-16T19:26:18.545559+0530'
>>> 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)))
like image 141
Martijn Pieters Avatar answered Jul 18 '26 05:07

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!