This question already has answers here:
How do I convert seconds to hours, minutes and seconds?
(18 answers)
Closed 6 years ago.
So I wrote a python code that converts seconds into hour minutes and secs, but the code doesn't look neat. What would be a better way of doing what my script is doing?
from fractions import Fraction as Frac
from decimal import Decimal as Deci
def Hrs(mins,hr=[],deci=[],hrs=True):
return(Seperator(mins/60))
def Seperator(Decimal,num=[],deci=[],nums=True):
del num[:],deci[:]
for item in str(Decimal):
if item == '.':
deci.append(item)
nums = False
continue
num.append(item)if nums else deci.append(item)
return''.join(num),''.join(deci)
def Mins(secs):
t = Deci(float(Frac(secs,60)))
return t
def Secs(deci):
r = Deci(float(deci*60))
return r
def Clean(decimal,deci=[],p=True):
del deci[:]
for item in str(decimal):
if item == '.':
if p:deci.append(item);p=False;continue
else: break
deci.append(item)
return float(''.join(deci))
if __name__ == '__main__':
Seconds = 6033
Hours = Hrs(Mins(Seconds))[0]
Minutes = int(Secs(Clean(Hrs(Mins(Seconds))[1])))
Seconds = int(eval(Seperator(Secs(Clean(Hrs(Mins(Seconds))[1])))[1])*60)
print '{}:{}:{}'.format(Hours,Minutes,Seconds)
Absolutely. Here you go:
def convert(total):
secs = total%60
total /= 60
minutes = total%60
total /= 60
hours = total%24
days = total/24
return (days, hours, minutes, secs)
convert(13246345)
Output: (153, 7, 32, 25)
This should do the trick
import time
localtime = time.localtime()
timeString = time.strftime("%Y%m%d%H%M%S", localtime)
timeString = time.strftime("%H:%M:%S")
print timeString
Related
Is it possible to convert seconds into minutes and seconds with this format "mm:ss"?
I try to use datetime.timedelta(seconds=seconds) but it returns hh:mm:ss format.
Thanks in advance!
You can use divmod for this.
hours, remainder = divmod(someSecondsValue, 3600)
minutes, seconds = divmod(remainder, 60)
print(f"{minutes:02}:{seconds:02}")
You can get number of minutes by dividing by 60
and number of seconds by calculating reminder by 60.
total_seconds = 10000
minutes = int(total_seconds / 60)
seconds = total_seconds % 60
print(f"{minutes}:{seconds}")
You could also make a small custom time class and use __format__ to control how you wanna print it out:
class MyTime:
def __init__(self, seconds: int):
self.total_seconds = seconds
def __format__(self, format_spec: str) -> str:
if format_spec == 'm':
minutes = self.total_seconds // 60
seconds = self.total_seconds % 60
return f'{minutes:02}:{seconds:02}'
if format_spec == 'h':
hours = self.total_seconds // 3600
minutes = (self.total_seconds - hours * 3600) // 60
seconds = self.total_seconds % 60
return f'{hours:02}:{minutes:02}:{seconds:02}'
# ...other formats...
return str(self.total_seconds)
x = MyTime(3674)
print(f'Seconds: {x}') # 3674
print(f'Minutes & seconds: {x:m}') # 61:14
print(f'Hours & minutes & seconds: {x:h}') # 01:01:14
def seconds_to_label_converter(seconds):
hours = divmod(seconds,3600)[0]
minutes = divmod(seconds-(hours*3600),60)[0]
remaining_seconds = seconds-((hours*3600)+(minutes*60))
if remaining_seconds == 0 and hours == 0 and minutes == 0:
time_label = "No info"
elif hours > 1:
time_label = f"{hours} Hours {minutes} Minutes {remaining_seconds} Seconds"
elif hours == 1:
time_label = f"{hours} Hour {minutes} Minutes {remaining_seconds} Seconds"
elif hours == 0 and minutes > 1:
time_label = f"{minutes} Minutes {remaining_seconds} Seconds"
elif hours == 0 and minutes == 1:
time_label = f"{minutes} Minute {remaining_seconds} Seconds"
elif hours == 0 and minutes == 0:
time_label = f"{remaining_seconds} Seconds"
print(time_label)
seconds_to_label_converter(21254)
I have a "seconds to label converter" like this. Now I need a function that will do the opposite. But I don't know how to do it.
for example:
label_to_seconds_converter("5 Hours 54 Minutes 14 Seconds")
# >>> OUTPUT = 21254
Try this. Extract specific strings using re and then extract numbers
import re
def seconds_to_label_converter(seconds):
x=re.findall(r'\b\d+\s*hour[s]?\b',seconds.lower())
y=re.findall(r'\b\d+\s*minute[s]?\b',seconds.lower())
z=re.findall(r'\b\d+\s*second[s]?\b',seconds.lower())
secs=0
if x:
for i in re.findall(r'\d+',''.join(x)):
secs +=3600*int(i)
if y:
for i in re.findall(r'\d+',''.join(y)):
secs +=60*int(i)
if z:
for i in re.findall(r'\d+',''.join(z)):
secs +=int(i)
return secs
print(seconds_to_label_converter('4 hours 50 seconds'))
Returns
14450
print(seconds_to_label_converter('4 hours 10 minutes 50 seconds'))
returns
15050
print(seconds_to_label_converter('5 Hours 54 Minutes 14 Seconds'))
Returns
21254
You could do something like this:
def text_to_second(txt: str):
items = [int(x) if x.isnumeric() else x for x in txt.split() ]
seconds = 0
for i in range(0,len(items),2):
a = items[i+1]
if a.lower()=="hours" or a.lower()=="hour":
seconds += 3600*items[i]
elif a.lower()=="minutes" or a.lower()=="minute":
seconds += 60*items[i]
elif a.lower()=="seconds" or a.lower()=="second":
seconds += items[i]
return seconds
print(text_to_second("5 Hours 54 Minutes 14 Seconds"))
#output: 21254
Another option would be to use the zip function:
def label_to_seconds_converter(label: str) -> int:
label_list = label.split()
seconds = 0
for amount, word in zip(label_list[::2], label_list[1::2]):
if "hour" in word.lower():
seconds += int(amount) * 3600
elif "minute" in word.lower():
seconds += int(amount) * 60
else:
seconds += int(amount)
return seconds
print(label_to_seconds_converter("5 Hours 54 Minutes 14 Seconds"))
result
21254
try this :
def label_to_seconds(label):
times = re.findall(r'\b\d+\s*[hours|minutes|seconds]?\b', label.lower())
list_len = len(times)
if list_len == 3:
return int(times[0].strip()) * 3600 + int(times[0].strip()) * 60 + int(times[0].strip())
if list_len == 2:
return int(times[0].strip()) * 60 + int(times[1].strip())
if list_len == 1:
return int(times[0].strip())
else:
print('Invalid Format')
I am trying to program a calendar that checks how many days from now/ ago (past and present) from raw_input. I need a loop that counts the days through the current year and adds it to a variable called: Total_days and this loop has to go through each year until it hits the current date that the code ran on. The end result is that the output gives you the date you entered in a complete sentence: eg. "10/08/1700 was ___ days ago" Basically my teacher explained that the past days has to add up until it hits that certain date using a loop(loops are required. This is an assignment, i cant use any other functions like delta, but loops and datetime stuff is good!) and then for the future it has to say how many days from now until that futuristic date happens using loops. I am very stumped and i need your guys' help.
Heres what i got so far:
import datetime
input_date = raw_input("Enter in full format (mm/dd/yyyy):")
year = input_date[6:10]
yeara = int(year)
montha = int(input_date[1:2])
daya = int(input_date[4:5])
from datetime import datetime
from datetime import date
now = datetime.now()
year = now.year
month = now.month
day = now.day
def isleapYear(year):
if year % 4 == 0:
check = True
if year % 100 == 0:
check = False
if year % 400 == 0:
check = True
total_days = 0
n = 12
moNum = [0,31,28,31,30,31,30,31,31,30,31,30,31]
while n > montha:
if yeara > year:
if year == isleapYear(year):
total_days += 366
elif year != isleapYear(year):
total_days += 365
if montha == month:
break
total_days += int(moNum[n])
if n == 02:
if isleapYear(year) == True:
total_days += 1
n -= 1
ny = 365
h = total_days
if yeara > year:
if year == isleapYear(year):
total_days += 366
elif year != isleapYear(year):
total_days += 365
if yeara>year:
time = "future"
if yeara<year:
time = "past"
if yeara==year:
if montha>month:
time = "future"
if montha<month:
time = past
if montha == month:
if daya>day:
time = "future"
if daya<day:
time = "past"
if daya==day:
time = "present"
print str(h.days) + " days in the " + str(time)
Thanks for helping out! i appreciate your help :)
Must you use a loop? Else, you can build from the following:
refdatestr = "2010/08/23"
refdate = datetime.strptime(refdatestr, "%Y/%m/%d")
now = datetime.now()
difference_days = (now-refdate).days
difference_days is a datetime.timedelta object. If refdate (or refdatestr) was in the future, this would be negative.
Here is an updated code, with everything fixed:
import datetime
input_date = raw_input("Enter in full format (mm/dd/yyyy):")
year = input_date[6:10]
yeara = int(year)
montha = int(input_date[1:2])
daya = int(input_date[4:5])
from datetime import datetime
from datetime import date
now = datetime.now()
year = now.year
month = now.month
day = now.day
def isleapYear(year):
if year % 4 == 0:
check = True
if year % 100 == 0:
check = False
if year % 400 == 0:
check = True
end_date = input_date
start_date = now
delta = date(year,month,day)
delta2 = date(yeara,montha,daya)
h = delta-delta2
if yeara>year:
time = "future"
if yeara<year:
time = "past"
if yeara==year:
if montha>month:
time = "future"
if montha<month:
time = past
if montha == month:
if daya>day:
time = "future"
if daya<day:
time = "past"
if daya==day:
time = "present"
print str(h.days) + " in the " + str(time)
The most important thing that you forgot is that there are functions in datetime that will automatically find the number of days till the input...
Hope this helps!!!
I have a function hello_world () that I would like to call every hour (1:00, 2:00, 3:00, etc).
I'm a beginner here and not totally comfortable with writing loops.
I have the following code, but it stops after 23 hours. I am not sure how to loop the loop such that everything repeats at the end of the day!
def sched ():
i = 0
for (i <= 23):
x = datetime.today()
current_hour = datetime.now().hour
y=x.replace(day=x.day+1, hour=i, minute=00, second=00, microsecond=00)
delta_t=y-x
secs=delta_t.seconds+1
t=Timer(secs, hello_world)
t.start()
i = i + 1
I also realize this may not be the most efficient way of writing this code, so I am open to suggestions on how to improve.
Do you know about modulo operator (%)? i % 24 will return the remainder after dividing by 24, so i will be 0, 1, .. 23, 0 .. etc
def sched ():
i = 0
while True:
x = datetime.today()
current_hour = datetime.now().hour
y=x.replace(day=x.day+1, hour=i, minute=00, second=00, microsecond=00)
delta_t=y-x
secs=delta_t.seconds+1
t=Timer(secs, hello_world)
t.start()
i = i + 1
i = i % 24
That is because you limited your loop to i <= 23. You can change it to this:
i = 0
while True:
x = datetime.today()
current_hour = datetime.now().hour
y=x.replace(day=x.day+1, hour=i, minute=00, second=00, microsecond=00)
delta_t=y-x
secs=delta_t.seconds+1
t=Timer(secs, hello_world)
t.start()
i = (i + 1) % 24
Using (i + 1) % 24 guarentees that i will never be greater than 23. More about the modulus operator here.
So I have this here.
import sys
import os
import time
def clock():
Minutes = 0
Hours = 1
while True:
Minutes += 1
if Minutes == 60:
Minutes = 0
Hours = 2
if Hours == 12:
Hours = 1
Minutes = 0
break
ReadLine = ("\t{0:>2} : {1:>2}\r").format(Hours, Minutes)
sys.stdout.write(ReadLine)
sys.stdout.flush()
time.sleep(60)
clock()
Just for the record, I have made sure that the indentations are correct, they look a little screwy here. And I realize that I have nothing set for A.M./P.M. as of yet.. Any help is appreciated for this noob.
Thank you - Matt.
Edit:
>>> 2: 0 2: 0 2: 0
This is what is printing out now, the minutes have not updated. I'm obviously missing something. Once again thanks for any help, and I am sorry if this is a repeat, I have searched for an answer, but none was found. Thanks - Matt.
Edit #2- I figured it out. I used a bit of both of the answers, and whilst I accept the fact that it will be slow it does what I want it to do.
import sys
import os
import time
def clock():
Minutes = 0
Hours = 1
AM_PM = "AM" if Hours < 12 else "P.M"
while True:
Minutes += 1
if Minutes == 60:
Minutes = 0
Hours += 1
if Hours == 24:
Hours = 1
Minutes = 0
break
ReadLine = ("\t{:>2} : {:>2} {}\r").format(Hours, Minutes, AM_PM)
sys.stdout.write(ReadLine)
sys.stdout.flush()
time.sleep(60)
clock()
You know, it seems no matter how hard I try, I cannot get this darned indentation to look right. Oh well, I hope you can understand it's just tabbed a bit to the right.
your code print nothing because you put the code that print to stdout inside the if statements. so it would print only when Minutes == 60 and Hours == 12 (which will never happend because of you dont increament Hours as meantioned in the comments.
try this:
import sys
import os
import time
def clock():
Minutes = 0
Hours = 1
ampm = "AM"
while True:
Minutes += 1
if Minutes == 60:
Minutes = 0
Hours += 1
if Hours == 12:
Hours = 1
Minutes = 0
ampm = ("AM" if (ampm == "PM") else "PM")
ReadLine = ("\t{0:>2} : {1:>2} {2} \r").format(Hours, Minutes,ampm)
sys.stdout.write(ReadLine)
sys.stdout.flush()
time.sleep(60)
clock()
import datetime
then = now = datetime.datetime.now()
minutes = 0
hours = 0
while True:
now = datetime.datetime.now()
if (now-then).total_seconds() > 60:
then += datetime.timedelta(minutes=1)
minutes += 1
if minutes == 60:
minutes = 0
hours += 1
if hours == 24:
hours = 0
am_pm = "AM" if hours < 12 else "PM"
print("{:>2}:{:>02} {}".format((hours+11)%12+1, minutes, am_pm))
Note that I do away with time.sleep as it's not guaranteed to sleep for exactly the time requested (indeed you will always be running slightly slow by that clock) and instead compare a current time to the last time a minute passed and see if the total seconds are more than 60. If so, increment minutes, if minutes is 60, increment hours and check for rollover and am_pm switch. Afterwards, print the time.
If you're wanting to stretch your legs a little, try implementing it in a class! Ooh ooh, and threading too!
import datetime
import threading
import queue
class Clock(object):
def __init__(self, current_time=None):
if isinstance(current_time, datetime.datetime):
hours, minutes = current_time.hour, current_time.minute
else:
hours = minutes = 0
self.hours = hours
self.minutes = minutes
self.q = queue.Queue()
def checkTime(self):
try:
self.q.get_nowait() # time has updated, or exception thrown
self.updateTime()
self.q.task_done()
except queue.Empty:
pass # time hasn't updated
def updateTime(self, num_mins=1):
self.minutes += 1
if self.minutes == 60:
self.minutes = 0
self.hours += 1
if self.hours == 24:
self.hours = 0
print(self)
def minutePassed(self):
then = datetime.datetime.now()
while True:
now = datetime.datetime.now()
if (now-then).total_seconds() > 60:
then += datetime.timedelta(minutes=1)
self.q.put('_') # put something there, doesn't matter what
def __str__(self):
am_pm = "AM" if self.hours < 12 else "PM"
return "{:>2}:{:>02} {}".format((self.hours+11)%12+1,
self.minutes, am_pm)
def start(self):
t = threading.Thread(target=self.minutePassed)
t.daemon=True
t.start()
while True:
self.checkTime()
clock = Clock(datetime.datetime.now())
clock.start()