I need to covert time that is in this format:
2021-10-20T09:35:06.615-07:00
to this format:
10/20/2021:09:35:06
I have been playing around with datetime.datetime.strptime() since I am using Python 2.7, but I have had no luck.
Which method will help me do the conversion?
CodePudding user response:
please use python-dateutil
import datetime
import dateutil.parser
datestring = '2021-10-20T09:35:06.615-07:00'
d = dateutil.parser.parse(datestring)
you try to parse timezone:
def parse_timezone(datestring):
tzchar = datestring[-6];
datestr = datestring[0:-6];
tzstr = datestring[-5:];
d = datetime.datetime.strptime(datestr, '%Y-%m-%dT%H:%M:%S.%f');
if tzchar == ' ':
d = d datetime.timedelta(hours=int(tzstr[0:2]), minutes = int(tzstr[3:]));
else:
d = d - datetime.timedelta(hours=int(tzstr[0:2]), minutes = int(tzstr[3:]));
return d;
d = parse_timezone('2021-10-20T09:35:06.615-07:00');
print(d.strftime('%M/%d/%Y:%H:%M:%S'));