How do I add exceptions/constraints to this? - python

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:

Related

Calculation of business working hour in python

I would like to write a function that calculate working business hours in python, to do that I don't like to define a class and use python ready function to calculate.
I tried with following code but the code is not working well. I need to modify the code and change it for the hour instead of minutes too.
Do you have any suggestion?
def getminutes(datetime1,datetime2,worktiming=[9, 17]):
day_hours = (worktiming[1]-worktiming[0])
day_minutes = day_hours * 60 # minutes in a work day
weekends=[6, 7]
# Set initial default variables
dt_start = datetime1.datetime # datetime of start
dt_end = datetime2.datetime # datetime of end
worktime_in_seconds = 0
if dt_start.date() == dt_end.date():
# starts and ends on same workday
full_days = 0
if dt_start in [6, 7]:
return 0
else:
if dt_start.hour < worktiming[0]:
# set start time to opening hour
dt_start = datetime.datetime(
year=dt_start.year,
month=dt_start.month,
day=dt_start.day,
hour=worktiming[0],
minute=0)
if dt_start.hour >= worktiming[1] or \
dt_end.hour < worktiming[0]:
return 0
if dt_end.hour >= worktiming[1]:
dt_end = datetime.datetime(
year=dt_end.year,
month=dt_end.month,
day=dt_end.day,
hour=worktiming[1],
minute=0)
worktime_in_seconds = (dt_end-dt_start).total_seconds()
elif (dt_end-dt_start).days < 0:
# ends before start
return 0
else:
# start and ends on different days
current_day = dt_start # marker for counting workdays
while not current_day.date() == dt_end.date():
if not is_weekend(current_day):
if current_day == dt_start:
# increment hours of first day
if current_day.hour < worktiming[0]:
# starts before the work day
worktime_in_seconds += day_minutes*60 # add 1 full work day
elif current_day.hour >= worktiming[1]:
pass # no time on first day
else:
# starts during the working day
dt_currentday_close = datetime.datetime(
year=dt_start.year,
month=dt_start.month,
day=dt_start.day,
hour= worktiming[1],
minute=0)
worktime_in_seconds += (dt_currentday_close
- dt_start).total_seconds()
else:
# increment one full day
worktime_in_seconds += day_minutes*60
current_day += datetime.timedelta(days=1) # next day
# Time on the last day
if not is_weekend(dt_end):
if dt_end.hour >= worktiming[1]: # finish after close
# Add a full day
worktime_in_seconds += day_minutes*60
elif dt_end.hour < worktiming[0]: # close before opening
pass # no time added
else:
# Add time since opening
dt_end_open = datetime.datetime(
year=dt_end.year,
month=dt_end.month,
day=dt_end.day,
hour=worktiming[0],
minute=0)
worktime_in_seconds += (dt_end-dt_end_open).total_seconds()
return int(worktime_in_seconds / 60)
How can I modify the code that works with the following input ?
getminutes(2019-12-02 09:30:00,2019-12-07 12:15:00,worktiming=[9, 17])
You can use pd.bdate_range(datetime1, datetime2) to compute the number of working days. When converting worktiming to a pandas datetime, it is easy to compute the difference (in seconds) between the two datetimes:
import pandas as pd
datetime1 = "2019-12-02 09:30:00"
datetime2 = "2019-12-07 12:15:00"
def getminutes(datetime1, datetime2, worktiming=[9, 17]):
d1 = pd.to_datetime(datetime1)
d2 = pd.to_datetime(datetime2)
wd = pd.bdate_range(d1, d2) # working days
day_hours = (worktiming[1] - worktiming[0])
day_minutes = day_hours * 60 # minutes in a work day
day_seconds = day_minutes * 60 # seconds in a work day
full_days = len(wd)
day1 = datetime1[:10]
day2 = datetime2[:10]
dt1 = pd.to_datetime(day1 + " " + str(worktiming[0]) + ":00")
dt2 = pd.to_datetime(day2 + " " + str(worktiming[1]) + ":00")
ex1, ex2 = 0, 0
if day1 in wd:
ex1 = max(pd.Timedelta(d1 - dt1).seconds, 0)
if day2 in wd:
ex2 = max(pd.Timedelta(dt2 - d2).seconds, 0)
total_seconds = full_days * day_seconds - ex1 - ex2
total_minutes = total_seconds / 60
total_hours = total_minutes / 60
return int(total_minutes)
print(getminutes(datetime1, datetime2))
Output: 2370

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)

parse time to proper format python

I'm having issue parsing time from a website.
Time is given in this format (9-10:40AM, 11-1:30PM, 6:30-7:20PM)
If the time is not available it will show as TBA
I want to parse that to start and end time in 12H format.
This method doesn't return the correct values
For example, if the string is "11:25-12:15PM" I expect to get [11:25AM, 12:15PM] But what I actually get is [11:25PM, 12:15PM]
def insertTime(initialTime):
if "TBA" in initialTime:
return ["TBA", "TBA"]
startTime,endTime = initialTime.split("-")
try:
if "PM" in endTime:
startTimeHours = startTime.split(":")[0]
if ":" in startTime:
startTimeMinutes = ":" + startTime.split(":")[1]
else:
startTimeMinutes = ":00"
if int(startTimeHours) in range(9,12):
startTimeHours += startTimeMinutes + "AM"
if ":" not in startTime:
startTime +=":00"
if "AM" not in startTime:
startTime += endTime[-2:]
return [startTime, endTime]
except Exception as e:
print(f"Error insertTime: Start-> {startTime}, endTime->{endTime}")
print(e)
return [0,0]
Thank you
I think it would be easiest if you explicitly handled two possible cases (AM and PM) for the start time:
import datetime
def parse_time(text):
pm = None # unknown
if text[-2:] in ('AM', 'PM'):
pm = (text[-2:] == 'PM')
text = text[:-2]
if ':' not in text:
text += ':00'
hours, minutes = text.split(':')
hours = int(hours)
minutes = int(minutes)
if pm and hours < 12:
hours += 12
return datetime.time(hours, minutes), pm is not None
def parse_interval(text):
if 'TBA' in text:
return None, None
start, end = text.split('-')
start, is_exact = parse_time(start)
end, _ = parse_time(end) # end time should be exact
# If both the start and end times are known then there's nothing left to do
if is_exact:
return start, end
# start2 = start + 12 hours
start2 = start.replace(hour=(start.hour + 12) % 24)
start_AM, start_PM = sorted([start, start2])
# Pick the most reasonable option
if start_AM < end < start_PM:
return start_AM, end
elif start_AM < start_PM < end:
return start_PM, end
else:
raise ValueError('This cannot happen')
if __name__ == '__main__':
for text in [
'9-10:40AM',
'11-1:30PM',
'6:30-7:20PM',
'11:25-12:15PM',
'2AM-12:15PM',
]:
print(text.rjust(15), ':', *parse_interval(text))

Python Time Math

I want to write a program that allows the user to enter in a start time hour, end time hour, and number of divisions.
So they might enter 9, 10, and 4 which should mean a start time of 9:00AM, end of 10:00AM and to split the range 4 times, resulting in an output of 9:00, 9:15, 9:30, 9:45.
I've tried using the time module and datetime, but cannot get the addition of time to work. I do not care about date.
I can calculate the time split, but the actual addition to the start time is evading me.
I have a hodge-podge of code, and the following is mostly me experimenting trying to figure out how to make this work. I've tried adding the minutes, tried converting to seconds, delved into datetime, tried the time module, but can't seem to get it to work. There are plenty of examples of how to "add 15 minutes to now" but the issue is I don't want to start at the "now", but rather let the user decide start time.
Thank you.
time_start = "9"
time_end = "10"
time_split = "4"
if len(time_start) == 1:
time_start = "0" + str(time_start) + ":00"
else:
time_start = str(time_start) + ":00"
if len(time_end) == 1:
time_end = "0" + str(time_end) + ":00"
else:
time_end = str(time_end) + ":00"
print time_start
print time_end
s1 = time_start + ':00'
s2 = time_end + ':00'
FMT = '%H:%M:%S'
tdelta = datetime.strptime(s2, FMT) - datetime.strptime(s1, FMT)
divided = tdelta / int(time_split)
print tdelta
print divided
s3 = str(divided)
print "s1 time start: " + str(s1)
print "s2 time end: " + str(s2)
print "s3 time divided: " + str(s3)
ftr = [3600,60,1]
add_seconds = sum([a*b for a,b in zip(ftr, map(int,s3.split(':')))])
print "s3 time divided seconds: " + str(add_seconds)
print "time delta: " + str(tdelta)
EDIT: I did a small bit of research and found a much better solution that elegantly handles resolution to the millisecond. Please implement this code instead (though I will save the old code for posterity)
import datetime
start_time = 9 # per user input
end_time = 10 # per user input
divisions = 7 # per user input
total_time = end_time - start_time
start_time = datetime.datetime.combine(datetime.date.today(),datetime.time(start_time))
end_time = start_time + datetime.timedelta(hours=total_time)
increment = total_time*3600000//divisions # resolution in ms
times = [(start_time+datetime.timedelta(milliseconds=increment*i)).time()
for i in range(divisions)]
from pprint import pprint
pprint(list(map(str,times)))
# ['09:00:00',
# '09:08:34.285000',
# '09:17:08.570000',
# '09:25:42.855000',
# '09:34:17.140000',
# '09:42:51.425000',
# '09:51:25.710000']
If I were you, I'd do my math as raw minutes and use datetime.time only to save the results as something more portable.
Try this:
import datetime
start_time = 9 # per user input
end_time = 10 # per user input
divisions = 4 # per user input
total_minutes = (end_time-start_time)*60
increment = total_minutes // divisions
minutes = [start_time*60]
while minutes[-1] < end_time*60:
# < end_time*60 - increment to exclude end_time from result
minutes.append(minutes[-1] + increment)
times = [datetime.time(c//60,c%60) for c in minutes]
# [09:00:00,
# 09:15:00,
# 09:30:00,
# 09:45:00,
# 10:00:00]

Categories

Resources