Express time in hours units to verbose time - python

I need express my time in Hours and minutes. This is what I have:
0.0425 hours
~153 seconds, How can I show this as 0 Hours 2 minutos 33 seconds?

Here is one way.
time = '0.0425 hours'
# Extract time from string
time = time.split()[0]
# Convert time to a number of hours, then a number of seconds
time = float(time)
time = int(time * 3600)
# Compute the constituent elements of the time
hours = time // 3600
minutes = (time // 60) % 60
seconds = time % 60
# Print the result
print '{hours} Hours {minutes} minutos {seconds} seconds'.format(
hours=hours, minutes=minutes, seconds=seconds)

import time
import re
secs = int(re.sub('\D', '','~153'))
print '%d hours %d minutos %s seconds'%(time.gmtime(secs)[3:6])

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

This question is related to the datetime module of Python

I wrote a Python function that prints the number of days remaining in birthday of a user - the value of which is entered by the user. The code is as follows:
"""
Created on Thu Feb 20 16:01:33 2020
#author: hussain.ali
"""
import datetime as dt
import pytz
def days_to_birthday():
a = (input('Enter your birthday in YYYY, MM, DD format with the year being the current year:'))
td = dt.datetime.today()
#td2= td.replace(hour=0, minute =0, second =0, microsecond =0)
birthday = dt.datetime.strptime(a, '%Y,%m,%d')
days_to_birthday = birthday - td
print("There are", days_to_birthday, ' remaining until your next birthday!')
days_to_birthday()
This script or code works well except that it gives the number of days plus hours as well as minutes, seconds and even microseconds remaining until the next birthday.
The output seems like:
Enter your birthday in YYYY, MM, DD format with the year being the current year:2020,3,7
There are 15 days, 6:11:07.020133 remaining until your next birthday!
I want either only the days remaining to be displayed in the output
OR the output as:
There are 15 days, 6 hours, 11minutes, 07seconds, and 020133 microseconds remaining until your next birthday!
What one needs to do to attain the desired output? Please advise.
change your print statement to this code below.
print("There are", days_to_birthday.days, 'days remaining until your next birthday!')
timedelta doesn't have strftime() to format it so you can do one of two things:
get total_seconds() and calculate all values using divmod() or using // and %
total = days_to_birthday.seconds
rest, seconds = divmod(total, 60)
hours, minutes = divmod(rest, 60)
days = days_to_birthday.days
microseconds = days_to_birthday.microseconds
print('{} days {:02} hrs {:02} mins {:02} secs {:06} microseconds'.format(days, hours, minutes, seconds, microseconds))
get string 15 days, 6:11:07.020133, split it and use parts to create new string
days = days_to_birthday.days
parts = str(days_to_birthday).split(', ')[1].replace('.', ':').split(':')
print('{} days {} hrs {} mins {} secs {} microseconds'.format(days, *parts))
import datetime as dt
import pytz
#a = input('Enter your birthday in YYYY,MM,DD format with the year being the current year:')
a = '2020,06,01'
print('date:', a)
td = dt.datetime.today()
birthday = dt.datetime.strptime(a, '%Y,%m,%d')
days_to_birthday = birthday - td
print(days_to_birthday)
total = days_to_birthday.seconds
rest, seconds = divmod(total, 60)
hours, minutes = divmod(rest, 60)
days = days_to_birthday.days
microseconds = days_to_birthday.microseconds
print('{} days {:02} hrs {:02} mins {:02} secs {:06} microseconds'.format(days, hours, minutes, seconds, microseconds))
days = days_to_birthday.days
parts = str(days_to_birthday).split(', ')[1].replace('.', ':').split(':')
print('{} days {} hrs {} mins {} secs {} microseconds'.format(days, *parts))
Result
date: 2020,06,01
93 days, 21:35:15.056351
93 days 21 hrs 35 mins 15 secs 056351 microseconds
93 days 21 hrs 35 mins 15 secs 056351 microseconds

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

Python time format with three-digit hour

How can I parse the time 004:32:55 into a datetime object? This:
datetime.strptime("004:32:55", "%H:%M:%S")
doesn't work becaush %H expects two digits. Any way to add the third digit?
Three options :
s = "004:32:55"
from datetime import datetime
datetime.strptime(s[1:], "%H:%M:%S") # from second 0 to the end
datetime.strptime(s, "0%H:%M:%S") # add 0 in formatting
from dateutil import parser # use dateutil
parser.parse(s)
There are 24 hours in a day so you can divide and get the modulus to figure out how many days and hours are in the time, then subtract the days, this needs some tweaking will get you started.
s = "04:32:55"
s = s.split(":",1)
hours, days = divmod(int(s[0]),24)
new_time = "{}:{}".format(hours,s[1])
past = datetime.now() - timedelta(days=days)
final = "{} {}".format(past.date().isoformat(),new_time)
print datetime.strptime(final,"%Y-%m-%d %H:%M:%S")
I chose a more pragmatic approach in the end and converted the time stamp to seconds:
hours = (0 if time_string.split(":")[0] == "000" else int(time_string.split(":")[0].lstrip("0")) * 3600)
mins = (0 if time_string.split(":")[1] == "00" else int(time_string.split(":")[1].lstrip("0")) * 60)
secs = (0 if time_string.split(":")[2] == "00" else int(time_string.split(":")[2].lstrip("0")))
return hours + mins + secs
Converting back to hours, minutes, and seconds is easy with datetime.timedelta(seconds=123).
EDIT:
A better solution (thanks to Ben):
hours = int(time_string.split(":")[0]) * 3600
mins = int(time_string.split(":")[1]) * 60
secs = int(time_string.split(":")[2])
return hours + mins + secs

python - get time in specific format

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'

Categories