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:])
Related
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
This question already has answers here:
How can I convert a datetime object to milliseconds since epoch (unix time) in Python?
(14 answers)
Closed 3 years ago.
I want to convert current datetime into Unix time stamp
My Code
import time
import datetime
d = datetime.datetime.now()
unixtime = time.mktime(d.timetuple())
print(unixtime)
My output:
1577098747.0
Expected Output:
1577098747123.0
Above code gives me timestamp upto 10 digits but I want it to be accurate till 13 digits.
Note: I don't want to convert it manually multiplying by 10**3 I want to capture accurate milliseconds.
do it like this
import time
import datetime
d = datetime.datetime.now()
unixtime = datetime.datetime.timestamp(d)*1000
print(unixtime)
or you just use time.time()
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
This question already has answers here:
Format timedelta to string
(33 answers)
Closed 6 years ago.
My database table has a column whose datatype is datetime, so when queried it returns HH:MM:SS. However, using Python it returns (datetime.timedelta(0, 57360),).
This is obviously the time difference in seconds. How do I convert the returned object into a string in the format HH:MM?
What about this solution:
import datetime
td = datetime.timedelta(0, 57360)
print ':'.join(str(td).split(':')[:2])
That's how you can print the time:
import datetime
delta = datetime.timedelta(0, 57360)
sec = delta.seconds
hours = sec // 3600
minutes = (sec // 60) - (hours * 60)
print(hours, ':', minutes)
you can also print the time with seconds by
print(str(delta))
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)