Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a time value to a datetime value in Python?

I have a simple question (at least I thought so), I want to add a time value to a datetime value in Python. The values are read from an excel file.

I have the following code:

import xlrd
from datetime import time, datetime, timedelta
book = xlrd.open_workbook('C:\\Users\eline\Documents\***\***\Python\Example 1.xlsx')
sh = book.sheet_by_name("test")

arr_time = datetime(*xlrd.xldate_as_tuple(sh.cell_value(1,2), book.datemode))
print(arr_time)

a2 = sh.cell_value(1,5)
# converting float from excel to time value
print(int(a2*24*3600))
x = int(a2*24*3600)
slack_time = time(x//3600, (x%3600)//60, x%60)
print(slack_time)

new_arr_time = arr_time + slack_time
print(new_arr_time)

arr_time is here a datetime value which can vary e.g.:

2016-08-28 13:10:00

slack_time is here a time in minutes (sometimes hours) which can vary e.g.:

00:15:00

I would like to add the slack time (e.g. 15 minutes) to the arr_time. Thus for this example I would like to get the following output for new_arr_time:

2016-08-28 13:25:00

However, when running my code I get the following error: "TypeError: unsupported operand type(s) for +: ‘datetime.datetime’ and ‘datetime.time’". From this, I understand that I cannot add a time value to a datetime value, but when converting slack_time to a datetime value and then adding slack_time to arr_time I get a similar error (although subtracting works that way). I know I can use timedelta(minutes = 15) but since the values from the excel file vary and sometimes contain hours this does not work for me.

So my question is: how can I add a time value which is read from excel to a datetime value?

like image 223
Eline Avatar asked Feb 14 '26 20:02

Eline


2 Answers

You should make float value you're using to build slack_time into a time duration i.e. a datetime.timedelta object. Then it can be added to the datetime object:

>>> x = 0.010416666666666666
>>> timedelta(days=x)
datetime.timedelta(0, 900)
>>> 900/60
15 # the fifteen minutes you had earlier

So your code becomes:

from datetime import datetime, timedelta

new_arr_time = arr_time + timedelta(days=float(sh.cell_value(1,5)))
like image 176
Moses Koledoye Avatar answered Feb 17 '26 12:02

Moses Koledoye


import datetime
arr_time = datetime.datetime.strptime('2016-08-28 13:10:00', '%Y-%m-%d %H:%M:%S')
slack_time="00:15:00"
hrs,mts=slack_time.split(":")[:2]
new_time = arr_time + datetime.timedelta(hours=int(hrs),minutes=int(mts))

Your can get back the date in the string format if you want from new_time

like image 36
Sriram Sitharaman Avatar answered Feb 17 '26 10:02

Sriram Sitharaman



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!