Convert datetime.timedelta Object to HH:MM [duplicate] - python

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))

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

How to convert current datetime into 13 digits Unix timestamp? [duplicate]

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()

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

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)

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:])

Convert datetime since a given date to minutes [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Python datetime to Unix timestamp
Is there a way to convert a datetime to int, representing the minutes since, for example, January 2012, so that this int can be modified, written to a database, compared and so on?
EDIT:
The server I am running this on uses Python 2.6.6
Subtracting two datetime.datetime objects gives you a timedelta object, which has a .total_seconds() method (added in Python 2.7). Divide this by 60 and cast to int() to get minutes since your reference date:
import datetime
january1st = datetime.datetime(2012, 01, 01)
timesince = datetime.datetime.now() - january1st
minutessince = int(timesince.total_seconds() / 60)
or in a python shell:
>>> import datetime
>>> january1st = datetime.datetime(2012, 01, 01)
>>> timesince = datetime.datetime.now() - january1st
>>> minutessince = int(timesince.total_seconds() / 60)
>>> minutessince
346208
For python 2.6 and earlier, you'll have to use the .days and .seconds attributes to calculate the minutes:
minutessince = timesince.days * 1440 + timesince.seconds // 60
which gives you an integer as well.
By substracting datetimes, you can have a timedelta. This timedelta can be divided itself to give you what you want :
(datetime.datetime.now() - datetime.datetime(2012, 1, 1)) // datetime.timedelta(minutes=1)
(this code is only valid with python3, and that's why everybody should switch to python3 ;-) )
If you want the minutes of the delta between two dates, you can make a datetime.timedelta object by subtracting the two dates (see here), and then retrieve the minutes as shown in this question:
Convert a timedelta to days, hours and minutes
>>> import datetime
>>> now = datetime.datetime.now()
>>> then = datetime.datetime(year=2012, month=1, day=1)
>>> delta=now-then
This is a timedelta object representing an interval of time.
>>> print delta
240 days, 11:05:25.507000
To count the minutes during that interval, use:
>>> print delta.total_seconds() / 60
346265.42511666665

Categories

Resources