python - get time in specific format - python

I need to get time in format: hour:minutes:seconds. But if I use:
time.strftime('%H:%M:%S', time.gmtime(my_time))) #my_time is float
hour have a 24-hour clock (00 to 23). And when I have for example 25 hour and 2 minutes, it writes 1:02:00, but I need 25:02:00. How can I solve it? Thank you.

Don't use time.strftime() to format elapsed time. You can only format a time of day value with that; the two types of values are related but not the same thing.
You'll need to use custom formatting instead.
If my_time is elapsed time in seconds, you can use the following function to format it to a hours:minutes:seconds format:
def format_elapsed_time(seconds):
seconds = int(seconds + 0.5) # round to nearest second
minutes, seconds = divmod(seconds, 60)
hours, minutes = divmod(minutes, 60)
return '{:02d}:{:02d}:{:02d}'.format(hours, minutes, seconds)
Demo:
>>> def format_elapsed_time(seconds):
... seconds = int(seconds + 0.5) # round to nearest second
... minutes, seconds = divmod(seconds, 60)
... hours, minutes = divmod(minutes, 60)
... return '{:02d}:{:02d}:{:02d}'.format(hours, minutes, seconds)
...
>>> format_elapsed_time(90381.33)
'25:06:21'

Related

How do I convert integer into a time format

How would I go about converting a float like 3.65 into 4 mins 5 seconds.
I have tried using:
print(datetime.datetime.strptime('3.35','%M%-S'))
However, I get this back:
ValueError: '-' is a bad directive in format '%-M:%-S'
Take a look at the following script, you can figure out how to make it work for days years, etc, this only works if we assume the format is "hours.minutes"
import datetime
# Assuming the 3 represents the hours and the 0.65 the minutes
number = 3.65
# First, we need to split the numbero into its whole decimal part
# and its decimal part
whole_decimal_part = hours = int(number) # 3
decimal_part = number % whole_decimal_part # 0.6499999
# Now, we need to know how many extra hours are in the decimal part
extra_hours = round((decimal_part * 100) / 60) # 1
minutes = round((decimal_part * 100) % 60) # 5
hours += extra_hours # 4
time_str = "%(hours)s:%(minutes)s" % {
"hours": hours,
"minutes": minutes
} # 4:5
final_time = datetime.datetime.strptime(time_str, "%H:%M").time()
print(final_time) # 04:05:00
First, you should complain to whoever is giving you time data expressed like that.
If you need to process minutes and seconds as a standalone value, then the datetime object may not your best choice either.
If you still need to convert "3.65" into a datetime object corresponding to "4-05" you could adjust it to be a valid time representation before passing it to strptime()
m,s = map(int,"3.65".split("."))
m,s = (m+s)//60,s%60
dt = datetime.datetime.strptime(f"{m}-{s}","%M%-S")
Split your time into minute and seconds
If seconds is 60 or more, then add extra minutes (//) ; second is the modulo (%)
t="3.65"
m, s = [int(i) for i in t.split('.')]
if s >= 60:
m += s//60
s = s % 60
print(f'{m} mins {s} seconds') # -> 4 mins 5 seconds
while 65 seconds cannot be parsed correctly so you have to manipulate by yourself to clean the data first before parsing.
NOTE: assuming seconds is not a very very big number which can make minutes>60
import datetime
time= '3.65'
split_time = time.split(".")
minute =int(split_time[0])
seconds = int(split_time[1])
minute_offset, seconds = divmod(seconds, 60);
minute = int(split_time[0]) + minute_offset
print(datetime.datetime.strptime('{}.{}'.format(minute,seconds),'%M.%S')) #1900-01-01 00:04:05
You can alternatively use .time() on datetime object to extract the time
print(datetime.datetime.strptime('{}.{}'.format(minute,seconds),'%M.%S').time()) #00:04:05
A much cleaner and safer solution is (to consider hour as well). Convert everything into seconds and then convert back to hours, minutes, seconds
def convert(seconds):
min, sec = divmod(seconds, 60)
hour, min = divmod(min, 60)
return "%d:%02d:%02d" % (hour, min, sec)
time='59.65'
split_time = time.split(".")
minute =int(split_time[0])
seconds = int(split_time[1])
new_seconds = minute*60 +65
datetime.datetime.strptime(convert(new_seconds),'%H:%M:%S').time()

Get time difference between two datetime objects as hour, min and sec

I want to get the amount of hours, mins and seconds that have passed between two dates using datetime in python3.
This allows for the duration to be calculated, and makes the amount of hours, mins and seconds that have passed.
Note this has not been fully tested.
Code can also be found on Github here
from datetime import datetime
def calculate_time_duration(start_datetime, end_datetime):
"""
Requires two datetime objects,
returns (hours, minutes, seconds)
"""
seconds = (end_datetime - start_datetime).total_seconds()
minutes = seconds // 60
seconds -= minutes * 60
hours = minutes // 60
minutes -= hours * 60
return hours, minutes, seconds

How to convert float into Hours Minutes Seconds?

I've values in float and I am trying to convert them into Hours:Min:Seconds but I've failed. I've followed the following post:
Converting a float to hh:mm format
For example I've got a value in float format:
time=0.6
result = '{0:02.0f}:{1:02.0f}'.format(*divmod(time * 60, 60))
and it gives me the output:
00:36
But actually it should be like "00:00:36". How do I get this?
You can make use of the datetime module:
import datetime
time = 0.6
result = str(datetime.timedelta(minutes=time))
You're not obtaining the hours from anywhere so you'll first need to extract the hours, i.e.:
float_time = 0.6 # in minutes
hours, seconds = divmod(float_time * 60, 3600) # split to hours and seconds
minutes, seconds = divmod(seconds, 60) # split the seconds to minutes and seconds
Then you can deal with formatting, i.e.:
result = "{:02.0f}:{:02.0f}:{:02.0f}".format(hours, minutes, seconds)
# 00:00:36
Divmod function accepts only two parameter hence you get either of the two
Divmod()
So you can try doing this:
time = 0.6
mon, sec = divmod(time, 60)
hr, mon = divmod(mon, 60)
print "%d:%02d:%02d" % (hr, mon, sec)

How can I display timedelta in hours:min:sec?

I am exporting a list of timedeltas to csv and the days really messes up the format. I tried this:
while time_list[count] > datetime.timedelta(days = 1):
time_list[count] = (time_list[count] - datetime.timedelta(days = 1)) + datetime.timedelta(hours = 24)
But it's instantly converted back into days and creates an infinite loop.
By default the str() conversion of a timedelta will always include the days portion. Internally, the value is always normalised as a number of days, seconds and microseconds, there is no point in trying to 'convert' days to hours because no separate hour component is tracked.
If you want to format a timedelta() object differently, you can easily do so manually:
def format_timedelta(td):
minutes, seconds = divmod(td.seconds + td.days * 86400, 60)
hours, minutes = divmod(minutes, 60)
return '{:d}:{:02d}:{:02d}'.format(hours, minutes, seconds)
This ignores any microseconds portion, but that is trivially added:
return '{:d}:{:02d}:{:02d}.{:06d}'.format(hours, minutes, seconds, td.microseconds)
Demo:
>>> format_timedelta(timedelta(days=2, hours=10, minutes=20, seconds=3))
'58:20:03'
>>> format_timedelta(timedelta(hours=10, minutes=20, seconds=3))
'10:20:03'
If you are ignoring the days in the count, you can convert the timedelta directly.
def timedelta_to_time(initial_time: timedelta) -> time:
hour = initial_time.seconds//3600
minute = (initial_time.seconds//60) % 60
second = initial_time.seconds - (hour*3600 + minute*60)
return str(datetime.strptime(
f"{hour}:{minute}:{second}", "%H:%M:%S"
).time())
Example:
timedelta_to_time(timedelta(days=2, hours=10, minutes=20, seconds=3))
>> '10:20:03'
timedelta_to_time(timedelta(hours=10, minutes=20, seconds=3))
>> '10:20:03'

How do i change a timedelta object into seconds only in python 3.4? [duplicate]

I am exporting a list of timedeltas to csv and the days really messes up the format. I tried this:
while time_list[count] > datetime.timedelta(days = 1):
time_list[count] = (time_list[count] - datetime.timedelta(days = 1)) + datetime.timedelta(hours = 24)
But it's instantly converted back into days and creates an infinite loop.
By default the str() conversion of a timedelta will always include the days portion. Internally, the value is always normalised as a number of days, seconds and microseconds, there is no point in trying to 'convert' days to hours because no separate hour component is tracked.
If you want to format a timedelta() object differently, you can easily do so manually:
def format_timedelta(td):
minutes, seconds = divmod(td.seconds + td.days * 86400, 60)
hours, minutes = divmod(minutes, 60)
return '{:d}:{:02d}:{:02d}'.format(hours, minutes, seconds)
This ignores any microseconds portion, but that is trivially added:
return '{:d}:{:02d}:{:02d}.{:06d}'.format(hours, minutes, seconds, td.microseconds)
Demo:
>>> format_timedelta(timedelta(days=2, hours=10, minutes=20, seconds=3))
'58:20:03'
>>> format_timedelta(timedelta(hours=10, minutes=20, seconds=3))
'10:20:03'
If you are ignoring the days in the count, you can convert the timedelta directly.
def timedelta_to_time(initial_time: timedelta) -> time:
hour = initial_time.seconds//3600
minute = (initial_time.seconds//60) % 60
second = initial_time.seconds - (hour*3600 + minute*60)
return str(datetime.strptime(
f"{hour}:{minute}:{second}", "%H:%M:%S"
).time())
Example:
timedelta_to_time(timedelta(days=2, hours=10, minutes=20, seconds=3))
>> '10:20:03'
timedelta_to_time(timedelta(hours=10, minutes=20, seconds=3))
>> '10:20:03'

Categories