Adding datetime.time objects to each other in python [duplicate] - python

This question already has answers here:
What is the standard way to add N seconds to datetime.time in Python?
(11 answers)
Closed 6 years ago.
How can i add datetime.time objects to each other? Lets say i have:
import datetime as dt
a = dt.time(hour=18, minute=15)
b = dt.time(hour=0, minute=15)
#c = a+b???
c should be equal to datetime.time(hour=18, minute=30)
Edit:
I have a function that gets as arguments datetime.time objects and should return datetime.time object that is sum of passed arguments. As i am only dealing with hours and minutes i wrote this:
def add_times(t1, t2):
hours = t1.hour + t2.hour
minutes = t1.minute + t2.minute
hours += minutes // 60
minutes %= 60
new_time = datetime.time(hour=hours, minute=minutes)
return new_time
But it is a dirty way and i am sure there is a legit way of doing it.
How do i achieve that?

Adding timedeltas
You can add dt.timedeltas
import datetime as dt
a = dt.timedelta(hours=18, minutes=15)
b = dt.timedelta(hours=0, minutes=15)
a + b
datetime.timedelta(0, 66600)

Related

How to format this date.time variable to include on milliseconds up to 2 decimal places? [duplicate]

This question already has answers here:
Format timedelta to string
(33 answers)
Closed 1 year ago.
How can I format this date.time variable to include on milliseconds up to 2dp?
Using the date.time module in Python, I have created 2 variables. These are as follows:
begin = datetime.datetime.now()
end = datetime.datetime.now()
I then print the variable below.
time_taken = end - begin
Printing this variable time_taken in this format 0:00:16.664335.
The question I want to ask, is there a simple way to round the milliseconds to 2dp?
I have searched other methods but they seem over-complicated and not worth using.
yes the simple way to round a variable:
{selected variable} = round({selected variable}, {number of dp})`
example:
time = 1.3454
time = round(time, 2)
print time
{out put is 1.35}
Hopes this helps.
Subtracting datetime objects return a timedelta object. It has time upto microseconds stored inside it.
You can get that value & round it to however many points of precision you require.
import time
from datetime import datetime
begin = datetime.now()
time.sleep(0.005) # 5 ms
end = datetime.now()
time_taken = end - begin # this is a timedelta object
time_taken_ms = round(time_taken.total_seconds() * 1000, 2)
print(time_taken_ms)
Output:
6.97
The result of subtracting two datetimes is a timedelta object which only stores days, seconds, and microseconds internally and that is what is normally displayed when you print their values. If you desire something different, you will need to define your own formatting function. Below is and example of one that does what you want with respect to milliseconds:
import datetime
import time
def format_timedelta(td):
""" Format a timedelta into this format D:H:M:SS.ss """
days = td.days
hours, remainder = divmod(td.seconds, 3600)
minutes, seconds = divmod(remainder, 60)
seconds += td.microseconds / 1e6
return (f'{days}:{hours}:{minutes}:{seconds:02.2f}' if days else
f'{hours}:{minutes}:{seconds:02.2f}')
begin = datetime.datetime.now()
time.sleep(0.123) # 123 ms
end = datetime.datetime.now()
time_taken = end - begin
print(format_timedelta(time_taken)) # -> 0:0:0.12

Add time with integer number in python [duplicate]

This question already has answers here:
How to add hours to current time in python
(4 answers)
Closed 3 years ago.
I want to get current time and add it with an integer of hours. Example now is 11.00pm, May 12, 2019. I want to add 3 hours more. So the result would be 2.00 am May 13, 2019. Please help me to datetime + hours(integer type)
import datetime
currentDT = datetime.datetime.now()
print('Now is: '+ str(currentDT))
hours = int(input()) #any hours you want
result = currentDT + hours #it will get the errors here
Use datetime.now to obtain the current time, and add a datetime.timedelta:
from datetime import datetime, timedelta
n_hours = 3
date = datetime.now() + timedelta(hours=n_hours)
print(datetime.now())
# 2019-05-12 19:16:51.651376
print(date)
# 2019-05-12 22:16:51.464890

Calculate difference between two datetimes odoo 10 [duplicate]

This question already has answers here:
Date difference in minutes in Python
(12 answers)
Closed 5 years ago.
Working on Odoo10, i need to calculate the difference between two fields of datetime type, start and finish, i need the difference to be in minutes. how can i do that ?
Try with this example:
from dateutil.relativedelta import relativedelta
#api.one
#api.depends('start_field','finish_field')
def _total_minutes(self):
if self.start_field and self.finish_field:
start_dt = fields.Datetime.from_string(self.start_field)
finish_dt = fields.Datetime.from_string(self.finish_field)
difference = relativedelta(finish_dt, start_dt)
days = difference.days
hours = difference.hours
minutes = difference.minutes
seconds = 0

How to format duration in Python (timedelta)? [duplicate]

This question already has answers here:
Formatting timedelta objects [duplicate]
(7 answers)
Format timedelta to string
(33 answers)
Closed 7 years ago.
I'm a newbie to python.
I was trying to display the time duration.
What I did was:
startTime = datetime.datetime.now().replace(microsecond=0)
... <some more codes> ...
endTime = datetime.datetime.now().replace(microsecond=0)
durationTime = endTime - startTime
print("The duration is " + str(durationTime))
The output is => The duration is 0:01:28
Can I know how to remove hour from the result?
I want to display => The duration is 01:28
Thanks in advance!
You can split your timedelta as follows:
>>> hours, remainder = divmod(durationTime.total_seconds(), 3600)
>>> minutes, seconds = divmod(remainder, 60)
>>> print '%s:%s' % (minutes, seconds)
This will use python's builtin divmod to convert the number of seconds in your timedelta to hours, and the remainder will then be used to calculate the minutes and seconds. You can then explicitly print the units of time you want.
You can do this by converting durationTime which is a datetime.timedelta object to a datetime.time object and then using strftime.
print datetime.time(0, 0, durationTime.seconds).strftime("%M:%S")
Another way would be to manipulate the string:
print ':'.join(str(durationTime).split(':')[1:])

In Python, how do I make a datetime that is 15 minutes from now? 1 hour from now? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicates:
Python - easy way to add N seconds to a datetime.time?
How to create a DateTime equal to 15 minutes ago?
what's the best way to do this?
d1 = datetime.datetime.now() + datetime.timedelta(minutes=15)
d2 = datetime.datetime.now() + datetime.timedelta(hours=1)

Categories

Resources