What's the time unit of this timedelta? - python

import time
from datetime import timedelta
start = time.time()
...
end = time.time()
print('Total time spent: {}'.format(str(timedelta(seconds=end - start))))
For example, one output could be:
0:00:00.395616
The fist 3 must be hours, minutes and seconds. What about the '.395616' part? Is it millseconds or microseconds, or even seconds?

Related

Subtracting asctime from time module to get hours minutes and seconds in python

How can I subtract end - start to get hours minutes and seconds of time completion in Python?
I have some pseudocode here, I want to convert the print statement to what I said above.
start = time.asctime(time.localtime(time.time()))
< some code here>
end = time.asctime(time.localtime(time.time()))
print(end - start)
a solution using datetime
You can use the datetime module in Python to subtract two datetime objects and obtain a timedelta object that represents the duration between the two times. The timedelta object can be further used to extract hours, minutes, and seconds by accessing its attributes total_seconds(), seconds, minutes, hours, and days. Here is an example:
import datetime
start = datetime.datetime.now()
end = datetime.datetime.now()
duration = end - start
hours, remainder = divmod(duration.total_seconds(), 3600)
minutes, seconds = divmod(remainder, 60)

Trying to find the difference between 2 datetime objects and getting only Hours, Minutes, and Seconds [duplicate]

This question already has answers here:
Convert timedelta to total seconds
(4 answers)
Closed 27 days ago.
I am pulling an ending time from a json api response. Then I am trying to calculate the time remaining, before the end time, to call a function after it ends.
end_time_string = data['endTime'] # Get the end time in a string in weird format
date_format = "%Y%m%dT%H%M%S.%fZ" # Specify the date format for the datetime parser
end_time = datetime.strptime(end_time_string, date_format) # turn the date time string into datetime object
current_time = datetime.utcnow() # Get current time in UTC time zone, which is what CoC uses.
time_remaining = end_time - current_time # Get the time remaining till end of war
My end_time is a datetime object. My current_time is a datetime object. But time_remaining is a timedelta object. I am able to pull the hours, minutes and seconds from the object using:
hours, minutes, seconds = map(float, str(time_remaining).split(':'))
But the problem is that sometimes the time_remaining has days in it, and sometimes it doesn't.
1 day, 4:55:22.761359
-1 days, 23:59:08.45766
When there are days involved, specifically when the timedelta object goes negative, my script fails.
What is the best find the amount of time between my two datetime objects in ONLY hours, minutes, and seconds, without days included?
timedelta is an object. One of its methods is total_seconds() so dividing by 3600 gives hours. Also dividing by another timedelta gives a float result of the ratio, so divide by timedelta(hours=1) to get the time in hours:
>>> import datetime as dt
>>> x = dt.timedelta(days=1, seconds=5000)
>>> x.total_seconds() / 3600
25.38888888888889
>>> x / dt.timedelta(hours=1)
25.38888888888889
or in hours, minutes, seconds:
>>> hours, remaining_seconds = divmod(x.total_seconds(), 3600)
>>> minutes, seconds = divmod(remaining_seconds, 60)
>>> hours, minutes, seconds
(25.0, 23.0, 20.0)
So, a timedelta object has days, seconds and microseconds. Multiply the days by 24 to convert it into hours, and then some nice math with modulo (%) and the usefull // operator, for which I will quote something:
//: Divides the number on its left by the number on its right, rounds
down the answer, and returns a whole number.
combining everything you get a nice f-string with padding for the zeros:
f"{td.seconds//3600 + td.days*24:02}:{(td.seconds//60)%60:02}:{td.seconds%60:02}:{td.microseconds:06}"
To put this into code:
from datetime import datetime, timedelta
# 3670 seconds is 1h1m10s
tomorrow = datetime.utcnow() + timedelta(1, 3670, 123)
current_time = datetime.utcnow()
td = tomorrow - current_time
print(td)
print(td.days)
print(td.seconds)
print(td.microseconds)
print(f"{td.seconds//3600 + td.days*24:02}:{(td.seconds//60)%60:02}:{td.seconds%60:02}:{td.microseconds:06}")
Which generates the following output:
1 day, 1:01:10.000123
1
3670
123
25:01:10:000123

Problem with calculating how many times some date has passed midnight

I would like to ask for a help. I am a beginner when it comes to Python. I try to write a function, that sums up together two "times" and returns new_time and also how many times new_time passed midnight of "start_time"(for example 23:00 and 03:00, new_date is 02:00, and 1 day has passed )
Thank you really much in advance
from datetime import datetime, timedelta
def add_time(start_time: str, time_to_add: str):
start_time_time = datetime.strptime(start_time, "%H:%M")
add_time_time = datetime.strptime(time_to_add, "%H:%M")
new_time = start_time_time + timedelta(minutes=add_time_time.minute, hours=add_time_time.hour)
return f"New time is {new_time.strftime('%H:%M')}, XXX days after"
print(add_time("23:20", "19:20"))
Calculate the dates for start_time_time and new_time. The number of days elapsed will be the difference (in days) between these dates.
I believe there are several ways to extract just the date from a "datetime", but I have just replaced the hours and minutes to zero.
from datetime import datetime, timedelta
def add_time(start_time: str, time_to_add: str):
start_time_time = datetime.strptime(start_time, "%H:%M")
start_date = start_time_time.replace(hour=0, minute=0)
#print(start_date)
add_time_time = datetime.strptime(time_to_add, "%H:%M")
new_time = start_time_time + timedelta(minutes=add_time_time.minute, hours=add_time_time.hour)
new_date = new_time.replace(hour=0, minute=0)
#print(new_date)
days_elapsed = (new_date - start_date).days
return f"New time is {new_time.strftime('%H:%M')}, {days_elapsed} days after"
print(add_time("23:20", "19:20"))
The following code snippets demonstrates how to calculate the number of days after. You can uncomment the print statements to see what these dates actually represent.
Hope this helps.
There are many ways to do this, I done mine in such as way that it should allow you to add example of 100hours, etc. Hope this helps.
from datetime import datetime, timedelta
# Function that adds time HH:mm to a datetime object, adds set Hours and Minutes to start time and returns total days, hours, minutes and seconds passed
def add_time(start_time, time_to_add):
# Add time to start time
start_time = datetime.strptime(start_time, '%H:%M')
# Strip hours, minutes and convert to ms
time_to_add = time_to_add.split(':')
time_to_add = timedelta(hours=int(time_to_add[0]), minutes=int(time_to_add[1]))
finish_time = start_time + time_to_add
# Calculate total days, hours, minutes and seconds passed
total_days = finish_time.day - start_time.day
total_hours = finish_time.hour - start_time.hour
total_minutes = finish_time.minute - start_time.minute
total_seconds = finish_time.second - start_time.second
# Return total days, hours, minutes and seconds passed
return total_days, total_hours, total_minutes, total_seconds
# today + 23 hours + 20 minutes
days, hours, minutes, seconds = add_time("13:13", "25:00")
print(days, hours, minutes, seconds)

How could I display a time difference in python in total "hours:minutes:seconds"?

In Python, I retrieved a start time and end time using datetime.datetime.now(). I would like to round any microseconds to the nearest second and convert days into hours. The final displayed format of the time difference should be "hours:minutes:seconds". Thanks in advance for the help!
There is no direct way to format a timedelta object as you wish, so you have to do the calculations by yourself:
delta = end - start
seconds = int(round(delta.total_seconds()))
minutes, seconds = divmod(seconds, 60)
hours, minutes = divmod(minutes, 60)
print("{:d}:{:02d}:{:02d}".format(hours, minutes, seconds))

Calculating the times into minutes

I am working on my python code as I want to calulcating on the program time to convert it into minutes. When the program start at 12:00AM and my current time show as 1:00AM. The end time show for the program is 6:00AM, so I want to work out between 1:00AM and 6:00AM to take it away then multiply it by 60 to convert it into minutes.
Example: 6 take away 1 which is 5 then I want to multply it by 60 which it is 300 minutes.
Here is the code:
current_time = int(time.strftime("%M"))
prog_width = self.getControl(int(program_id)).getWidth()
prog_length = int(prog_width) / 11.4 - current_time
prog_length = str(prog_length)
prog_length = prog_length.replace('.0', '')
prog_length = int(prog_length)
print prog_length
Can you please show me an example of how I can calculating between 1:00AM and 6:00AM to take it away then convert it into minutes when multply by 60?
You can use the datetime module
from datetime import timedelta
start = timedelta(hours=1)
end = timedelta(hours=6)
duration = end - start
print duration.total_seconds() / 60

Categories

Resources