I must add a given number of hours:minutes to a date, once I try to format the method string parameter to datetime I am getting the below error:
myTime = '236:22'
myTime_str = '%H:%M'
myTime_time = datetime.strptime(myTime, myTime_str )
ValueError: time data '236:22' does not match format '%H:%M'
As I couldn't find a strptime() format code that allows the hour (236) to be greater than 23 I am wondering if is there other function or library, rather than datetime, that would help me to before addressing it "in the method"
CodePudding user response:
I must add a given number of hours:minutes to a date ...
You could use datetime.timedelta()
:
from datetime import date, timedelta
the_date = date.today()
print(the_date)
myTime = '236:22'
hours, minutes = map(int, myTime.split(":"))
the_date_ext = the_date timedelta(hours=hours, minutes=minutes)
print(the_date_ext)
Output:
2022-08-12
2022-08-21
(This works too if the the_date
is actually a datetime.datetime
object.)
CodePudding user response:
I have solved the requirement as follows:
duration_hours = int(duration.split(':')[0])
duration_minutes = int(duration.split(':')[1])
new_time = given_time timedelta(hours=duration_hours,minutes=duration_minutes)'