When attempting to format s1, s2
and then calculate a time delta I get the output listed below. This may be because I'm using replace()
incorrectly(what one of the two issues appears to be) Or there is an strftime()
. I think this because of the output ValueError("unconverted data remains: %s" % ValueError: unconverted data remains: PM
but I don't fully understand the error code and can't resolve the issue myself. Could anyone help me fix my not so professional code? haha. Or possibly point/create me to a more efficient timedelta calculator that works with STD time and appends PM & AM to the end where needed?
My code:
from datetime import datetime, date
import pytz
s1 = '11:00PM'
s2 = '12:00PM'
def timedelta(a, b):
chars = ['AM', 'PM']
for i in chars:
a.replace(i, '')
b.replace(i, '')
FMT = '%H:%M'
tdelta = datetime.strptime(b, FMT) - datetime.strptime(a, FMT)
return tdelta
print(timedelta(s1, s2))
This code may be broken since I did some last minute modifications to it myself in an attempt to repair the issue. Please ask for original(which works the same and has the same output) if needed! Thanks for the help!
Output(windows cmd):
Traceback (most recent call last):
File "t.py", line 19, in <module>
print(timedelta())
File "t.py", line 16, in timedelta
tdelta = datetime.strptime(s2, FMT) - datetime.strptime(s1, FMT)
File "C:\Users\danie\AppData\Local\Programs\Python\Python38-32\lib\_strptime.py", line 568, in _strptime_datetime
tt, fraction, gmtoff_fraction = _strptime(data_string, format)
File "C:\Users\danie\AppData\Local\Programs\Python\Python38-32\lib\_strptime.py", line 352, in _strptime
raise ValueError("unconverted data remains: %s" %
ValueError: unconverted data remains: PM
Wanted output:
1:00
You need to assign to a
and b
after replace:
from datetime import datetime, date
import pytz
s1 = '11:00PM'
s2 = '12:00PM'
def timedelta(a, b):
chars = ['AM', 'PM']
for i in chars:
a = a.replace(i, '')
b = b.replace(i, '')
FMT = '%H:%M'
tdelta = datetime.strptime(b, FMT) - datetime.strptime(a, FMT)
return tdelta
print(timedelta(s1, s2))