I am trying to get the Seconds since midnight: 86339 - python

I am trying to get the Seconds since midnight: 86339
I tried writing a program and i get the results
Enter hour:11
Enter minute:58
Enter second:59
Enter frame:PM
Seconds since midnight: 43139
hour = input("Enter hour:")
minute = input("Enter minute:")
second = input("Enter second:")
frame = raw_input("Enter frame:")
time = ( 3600 * hour + minute * 60 + second )
print "Seconds since midnight:",time
This is the actual results i want to produce
Enter hour: 11
Enter minute: 58
Enter second: 59
Enter AM or PM: PM
Seconds since midnight: 86339
Enter hour: 12
Enter minute: 7
Enter second: 20
Enter AM or PM: AM
Seconds since midnight: 440
Enter hour: 12
Enter minute: 14
Enter second: 57
Enter AM or PM: PM
Seconds since midnight: 44097

PM needs to add 12 hours
Python 2.X :
hour = input("Enter hour:")
minute = input("Enter minute:")
second = input("Enter second:")
frame = input("Enter frame:")
time = ( 3600 * hour + minute* 60 + second )
if frame == "PM":
time += 12 * 60 * 60
print "Seconds since midnight:",time
Python 3.x:
hour = input("Enter hour:")
minute = input("Enter minute:")
second = input("Enter second:")
frame = input("Enter frame:")
time = ( 3600 *int( hour) + int( minute)* 60 + int( second ))
if frame == "PM":
time += 12 * 60 * 60
print("Seconds since midnight:",time)

Change your time calculation to something like this:
time = ( 3600 * hour + minute * 60 + second )
if "PM" == frame:
time += 12 * 60 * 60

Related

How do I add exceptions/constraints to this?

In this code, it translates a 24-hour time to a 12-hour time.
How would I disallow numbers that don't make sense? Ex: 25:60:60/3495:3413:3144
The hours shouldn't be over 24, and the minutes/seconds shouldn't be over 59
`# Python program to convert time from 24 hour
# to 12 hour format
# Convert Function which takes in
# 24hour time and convert it to
# 12 hour format
def convert12(str):
# Get Hours
h1 = ord(str[0]) - ord('0')
h2 = ord(str[1]) - ord('0')
hh = h1 * 10 + h2
# Finding out the Meridien of time
# ie. AM or PM
Meridien=""
if (hh < 12):
Meridien = "AM"
else:
Meridien = "PM"
hh %= 12
# Handle 00 and 12 case separately
if (hh == 0):
print("12", end = "")
# Printing minutes and seconds
for i in range(2, 8):
print(str[i], end = "")
else:
print(hh,end="")
# Printing minutes and seconds
for i in range(2, 8):
print(str[i], end = "")
# After time is printed
# cout Meridien
print(" " + Meridien)
# Driver code
if __name__ == '__main__':
# 24 hour format
str = input(str("Please enter the time, in format 00:00:00: "))
convert12(str)
`
I've tried things like,
if "25" in str:

Python Timer Cooldown Example

I'm looking for a cooldown timer for python, basically just to print days,hours,minutes,seconds left from a certain date.
Thanks very much!
You can get the counter with the help of time delta function.
import datetime
import time
future_date = datetime.datetime.now()+ datetime.timedelta(seconds=3)
while True:
curr_date = datetime.datetime.now()
rem_time = future_date - curr_date
total_seconds = int(rem_time.total_seconds())
if total_seconds > 0:
days, h_remainder = divmod(total_seconds, 86400)
hours, remainder = divmod(h_remainder, 3600)
minutes, seconds = divmod(remainder, 60)
print("Time Left: {} days, {} hours, {} minutes, {} seconds".format(days, hours, minutes, seconds))
time.sleep(1)
else:
break
sample output will be:
Time Left: 0 days, 0 hours, 0 minutes, 2 seconds
Time Left: 0 days, 0 hours, 0 minutes, 1 seconds
Try this. The module datetime is preinstalled on Python, I believe.
import datetime
while True:
print("\033[H\033[J")
present = datetime.datetime.now()
future = datetime.datetime(2022, 3, 31, 8, 0, 0)
difference = future - present
print(difference)
The format for datetime's future is: year, month, day, hour, minute, second.
Or, if you'd like to have user input:
import datetime
year = int(input('Enter the year of the end date: '))
month = int(input('Enter the month of the end date: '))
day = int(input('Enter the day of the end date: '))
hour = int(input('Enter the hour of the end date: '))
minute = int(input('Enter the minute of the end date: '))
second = int(input('Enter the second of the end date (a little tricky): '))
future = datetime.datetime(year, month, day, hour, minute, second)
while True:
print("\033[H\033[J")
present = datetime.datetime.now()
difference = future - present
if present >= future:
break
print(difference)
print('Time reached!')
You can use the seconds from a timedelta from subtracting two dates to calculate the days, hours, minutes and seconds like this:
from datetime import datetime
import time
totalSecs = 1 #So the while loop doesn't stop immidiately
while totalSecs > 0:
startDate = datetime.now() #Can be any date
endDate = datetime(2021, 12, 25)
delta = endDate - startDate
totalSecs = delta.total_seconds()
days = divmod(totalSecs, 86400)
hrs = divmod(days[1], 3600)
mins = divmod(hrs[1], 60)
seconds = divmod(mins[1], 1)
print("{:02d}:{:02d}:{:02d}:{:02d}".format(int(days[0]), int(hrs[0]), int(mins[0]), int(seconds[0]))) #Zero pad all the numbers
time.sleep(1) #Print every second.
Thank you all for your replies, i've done a mistake when i made the post. Is not from a date. Is a countdown in day,hours,minutes,seconds from a certain amount of seconds. Let's say i've got 31104000 seconds and i want to print how many days,hours,minutes,seconds left from that amount of seconds.
The code i've got now is a bit trivial and i can't print seconds in realtime.
def SecondToDHM(time):
if time < 60:
return "%.2f %s" % (time, SECOND)
second = int(time % 60)
minute = int((time / 60) % 60)
hour = int((time / 60) / 60) % 24
day = int(int((time / 60) / 60) / 24)
text = ""
if day > 0:
text += str(day) + DAY
text += " "
if hour > 0:
text += str(hour) + HOUR
text += " "
if minute > 0:
text += str(minute) + MINUTE
text += " "
if second > 0:
text += str(second) + SECOND
return text
import datetime
a = datetime.datetime.now()
"%s:%s.%s" % (a.minute, a.second, str(a.microsecond))

Task with forwarding time

I am having troubles completing a task.The task requires a user to put in time(between 1 and 12),then to declare if its am or pm, and how much hours to forward it to.The forwarded time should also show am/pm time stamp depending on how much is it forwarded.Example:
Input time: 8
am or pm : am
forward: 5
new time: 1pm
I have tried this:
time = eval(input('Input time(1-12):'))
ampm = eval(input('am or pm?'))
forward = eval(input('Forward:'))
if ampm == am:
if time + forward > 24:
new time = (time + forward)%24
x = 'am'
else:
new time = (time + forward)%12
x = 'pm'
print('New time is:' , new time , x)
if ampm == pm:
if time + forward > 12:
new time = (time + forward)%12
x = 'pm'
else:
new time = (time + forward)%24
x = 'am'
print('New time is:' , new time , x)
I suggest simply converting the time to 24h format, forwarding, then converting back to 12h(am/pm) format.
Here's how I'd do it:
time = int(input('Input time(1-12):'))
ampm = input('am or pm?')
forward = int(input('Forward:'))
# first get the 24h formatted time
time_24 = time + 12 if ampm == 'pm' else time
# then forward time to max 24, else start over from 0
time_24 = (time_24 + forward) % 24
# finally convert back to 12h(am/pm) format
time_12 = f'{time_24-12}pm' if time_24 > 12 else f'{time_24}am'
# print out the forwarded time
print(time_12)

How to validate time format input?

So basically, i needed to write a program that takes the time of how fast you run a kilometer, and turn it into how long it takes to run a marathon. I got that done, but the problem is that it is supposed to handle if someone inputs the time incorrectly (ex 888 or 5:2555 instead of 8:30)
print "Marathon Time Calculator"
str_pace = raw_input("At what pace do you run a km? (e.g. 5:30): ")
if str_pace.isalpha():
print 'invalid time'
split_pace = str_pace.split(":")
minutes = int(split_pace[0])
seconds = int(split_pace[1])
str_pace = minutes * 60 + seconds
totalTime = str_pace * 42
hours = totalTime // 3600
timeLeft = totalTime % 3600
minutes = timeLeft // 60
seconds = timeLeft % 60
if len(split_pace[1]) >= 3:
print "Too many digits"
else:
print "You should complete a marathon in " + str(hours) + ":" + str(minutes) + ":" + str(seconds)
I have done this in python3
import re
import sys
print("Marathon Time Calculator")
str_pace = input("At what pace do you run a km? (e.g. 5:30): ")
# this is looking for a decimal value of 1 number, then a colon then another decimal value of 1 - 2 numbers
pattern = '\d{1}\:\d{1,2}'
# this is doing the actual check against the pattern for us
match = re.match(pattern, str_pace)
# we now check if there is a match to our pattern
if not match:
print('Invalid Time Input Try Again')
sys.exit
else:
# yes we are entering the value correctly continue the code
split_pace = str_pace.split(":")
minutes = int(split_pace[0])
seconds = int(split_pace[1])
str_pace = minutes * 60 + seconds
totalTime = str_pace * 42
hours = totalTime // 3600
timeLeft = totalTime % 3600
minutes = timeLeft // 60
seconds = timeLeft % 60
print("You should complete a marathon in {}:{}:{}".format(hours, minutes, seconds))

Comparing times in a list and to give the time between instances

I have a log that outputs the time stamps for time of boot. I want to compare the time between each boot in to mins and seconds.
Here is the format of the list below.
16:18:17.10
16:20:31.48 = 2 mins 14.38 seconds <-- This what i want
the output to show.
16:27:52.06 = 3 mins 20.18 seconds <-- This what i want
the output to show.
16:33:33.06
16:35:50.94
Any help would be greatly appreciated.
Edit:
Thanks #smallwat3r
the finished code is
def split_format(var1, var2):
hour = int(var1.split(':')[0]) - int(var2.split(':')[0])
minute = int(var1.split(':')[1]) - int(var2.split(':')[1])
seconds = float(var1.split (':')[2]) - float(var2.split(':')[2])
time = '{} hours {} minutes {} seconds'.format(
hour, minute, round(seconds, 2)
)
return time
def getFile():
prose = str(input('Please enter the file path for your text file: '))
dictionary = {}
infile = open(prose, 'r')
line_num = 1
line_num2 = 2
for line in infile:
dictionary[line_num]=line
line_num += 1
line_num2 += 1
base = 1
base2 = 2
for x in dictionary:
print(dictionary[base2],(split_format(dictionary[base2],dictionary[base])))
base += 1
base2 += 1
infile.close()
getFile()
You use the below which returns 0 hours 2 minutes 14.38 seconds
time1 = '16:18:17.10'
time2 = '16:20:31.48'
def split_format(var1, var2):
hour = int(var1.split(':')[0]) - int(var2.split(':')[0])
minute = int(var1.split(':')[1]) - int(var2.split(':')[1])
seconds = float(var1.split (':')[2]) - float(var2.split(':')[2])
time = '{} hours {} minutes {} seconds'.format(
hour, minute, round(seconds, 2)
)
return time
print(split_format(time2, time1))

Categories

Resources