Torb
Torb

Reputation: 279

How to add a certain time to a datetime?

I want to add hours to a datetime and use:

date = date_object + datetime.timedelta(hours=6)

Now I want to add a time:
time='-7:00' (string) plus 4 hours.

I tried hours=time+4 but this doesn't work. I think I have to int the string like int(time) but this doesn't work either.

Upvotes: 1

Views: 926

Answers (2)

MyNameIsCaleb
MyNameIsCaleb

Reputation: 4489

You need to convert to a datetime object in order to add timedelta to your current time, then return it back to just the time portion.

Using date.today() just uses the arbitrary current date and sets the time to the time you supply. This allows you to add over days and reset the clock to 00:00.

dt.time() prints out the result you were looking for.

from datetime import date, datetime, time, timedelta

dt = datetime.combine(date.today(), time(7, 00)) + timedelta(hours=4)
print dt.time()

Edit: To get from a string time='7:00' to what you could split on the colon and then reference each.

this_time = this_time.split(':')   # make it a list split at :
this_hour = this_time[0]
this_min = this_time[1]

Edit 2: To put it all back together then:

from datetime import date, datetime, time, timedelta

this_time = '7:00'

this_time = this_time.split(':')   # make it a list split at :
this_hour = int(this_time[0])
this_min = int(this_time[1])

dt = datetime.combine(date.today(), time(this_hour, this_min)) + timedelta(hours=4)
print dt.time()

If you already have a full date to use, as mentioned in the comments, you should convert it to a datetime using strptime. I think another answer walks through how to use it so I'm not going to put an example.

Upvotes: 2

Rajan Chauhan
Rajan Chauhan

Reputation: 1385

Better you parse your time like below and access datetime attributes for getting time components from the parsed datetime object

 input_time = datetime.strptime(yourtimestring,'yourtimeformat')
 input_seconds = input_time.second # for seconds
 input_minutes = input_time.minute # for minutes
 input_hours = input_time.hour     # for hours
 # Usage: input_time = datetime.strptime("07:00","%M:%S")

Rest you have datetime.timedelta method to compose the duration.

new_time = initial_datetime + datetime.timedelta(hours=input_hours,minutes=input_minutes,seconds=input_seconds)

See docs strptime and datetime format

Upvotes: 1

Related Questions