Make a string based on timeframe - python

I am trying to understand how to make a string based on the current time, and time ranges in Python. So, if it's between 8am and 11am, for Python to identofy what time it is, and automatically return a "breakfast" string; and if its between 11am to 4pm --> return a lunch string

First of all, please, try to be clear when asking and bring some examples that you tried before.
Getting the time is easy as:
from datetime import datetime
now = datetime.now()
current_time = now.strftime("%H:%M:%S")
print("Current Time =", current_time)
You can see more information about datetime module here
So, current_time brings a string with the time. To select minutes or hours you need to pick up the position that they're at.
For example:
myTime = "12:34:56"
seconds = myTime[-2:]
print(seconds)
56
For more examples on slicing strings, here
You want integers instead of strings?
seconds = int(seconds)

Related

Convert Time data type python

I am trying to transform a time variable that uses strings and integers in one column into a more friendly format. For example my time variable looks like: 30m 32s
I want a variable in format 30:32
or a variable with number of seconds. Thanks.
I'm not sure I fully understood the question, but the following will split your string on the space then separate out the individual minutes / seconds.
def formatTime(time: str):
minutes, seconds = time.split(' ') # Split on the space character
minutes_val = minutes.split('m')[0] # Separate the minutes value
seconds_val = seconds.split('s')[0] # Separate the seconds value
return f"{minutes_val}:{seconds_val}" # Return the formatted string
UPDATE: as Pranav said in his comment, this won't work for minutes or seconds > 59. So, If you have this limitation, you can use this solution
You can do this using datetime module using the following code
from datetime import datetime
time_str = "30m 32s"
time_obj = datetime.strptime(time_str, "%Mm %Ss")
time_in_new_format = time_obj.strftime("%M:%S") # Equals 30:32
Now let's explain it line by line.
In the following line, we create a datetime object from the input string and tell the format is "%Mm %Ss" as %M means minutes and %S means seconds.
time_obj = datetime.strptime(time_str, "%Mm %Ss")
In the following line, we change the datetime object back to a string in the format "%M:%S".
time_in_new_format = time_obj.strftime("%M:%S")
You can check all formats here https://docs.python.org/3/library/time.html#time.strftime

How to get a set of all time between range of start and end time?

I want to get all the time between start time and end time in python, so I was using for loop with range function.
There are 2 variables, a and b which have time in %H:%M:%S format.
These 2 variables are start and end time and I want to print all the time between the start and end time.
import datetime
from datetime import datetime
import time
a = '20:15:16'
b = '20:32:55'
a = datetime.strptime(a,'%H:%M:%S').time()
b = datetime.strptime(b,'%H:%M:%S').time()
for i in range(a,b):
print(i)
For this I am getting an error - datetime.time' object cannot be interpreted as an integer.
I want to print all the time between a and b.
There are infinite moments between two times. I think you might be asking, "How can I print a timestamp for every second or every minute between A and B?"
I don't think you want to be using the range function. The error you are seeing is because range expects integers as input, not whole datetime objects.
Here is something that may do what you want:
from datetime import datetime, timedelta
# Define our times
str_A = '20:15:16'
str_B = '20:32:55'
# Create our datetime objects
A = datetime.strptime(str_A,'%H:%M:%S')
B = datetime.strptime(str_B,'%H:%M:%S')
# Create a loop where you print a time, starting with time A
# and then increase the time stamp by some value, in this case,
# 1 minute, until you reach time B
tmp = a
while tmp <= b:
print(tmp.time())
tmp = tmp + timedelta(minutes=1)
Please notice the line,
print(tmp.time())
where we only extract the time part when we need it, leaving the object as a datetime object for easy manipulation.
I used this question for reference:
What is the standard way to add N seconds to datetime.time in Python?
So this question is really adorable. There is something about reading, 'I need to print "all the time" between these two times' that gives me joy.

How do I extract the Hour/Minute from a datetime object and get rid of the Year/Month/Day/Second section?

I am writing a program to track my working hours as a chef. I'm looking for it to ask when I started, finished and how long a break I had that day. The problem I am running into is I keep getting a value error on line 12 (time data '1900-01-01 10:00:00' does not match format '%H:%M') and I'm having trouble applying the threads on here that try to explain the solution to my own problem. I know what I need to do is extract some of the data from the datetime object as a whole but so far everything I have tried has thrown up an error.
Code below;
from datetime import datetime
fmt = "%H:%M" # The time format i.e hours and minutes
print("Please input your starting and finishing times for the following days.")
print("Wednesday:") # Denotes which day is being asked about
wed_start_in = (input("What time did you start?")) # asks starting time
wed_start = str(datetime.strptime(wed_start_in, "%H:%M")) # converts time start input into a datetime object
wed_finish_in = (input("And what time did you finish?")) # asks finishing time
wed_finish = str(datetime.strptime(wed_start_in, "%H:%M"))
wed_hours = datetime.strptime(wed_start, fmt) - datetime.strptime(wed_finish, fmt)
print(wed_hours)
You're converting back and forth into strings; instead, parse each of the times once, then keep them as times. Only convert them back to strings (if necessary) at the very end.
wed_start_in = input("What time did you start?") # asks starting time
wed_start = datetime.strptime(wed_start_in, "%H:%M") # converts time start input into a datetime object
wed_finish_in = input("And what time did you finish?") # asks finishing time
wed_finish = datetime.strptime(wed_finish_in, "%H:%M")
wed_hours = wed_finish - wed_start
print(wed_hours)

add hours to time string to match time zone in python

I have a string that looks like this
time = "2020-04-15 21:27"
That's based on normal time zone +0
how can i add hours to the string so it become like this
for example let's add 5 hours to the time
the time string will become like this
time = "2020-04-15 02:27"
then the day should be updated
so the final result will look like this
time = "2020-04-15 02:27"
how can i do that ?
Edit:
i also need to change the day because 24 hours have passed
It is unclear if you mean creating your own clock or just updating a string every hour.
Option one:
import time
While True:
t = time.ctime(%h)
print(t)
#the above produces a live clock only showing hours.
#you could add %s for seconds separated by commas and thd like.
Option 2:
import time
T = #whatever you want it to be
time.sleep(300)
T = the prev num bit you want to change + 5
Hope this helps!
Happy coding

Python: execute a function a random number of times per day

I'd like to execute a function a random number of times each day between set periods. Here's what I have so far:
def get_epochtime(dt=datetime.now()):
EPOCH = datetime(1970, 1, 1)
return (dt - EPOCH).total_seconds()
def get_todays_run_schedule(runs_per_day, run_between):
now = datetime.now()
window_start = now.replace(hour=run_between[0])
window_end = now.replace(hour=run_between[1])
the_schedule = [ get_epochtime(radar.random_datetime(start=window_start, stop=window_end)) for t in range(randint(runs_per_day[0], runs_per_day[1])) ]
the_schedule.sort()
print("Today I will run %s times" % len(the_schedule))
for run_at in the_schedule:
print("I will run at " + time.strftime("%Y-%m-%d %H:%M", time.localtime(run_at)))
return the_schedule
# we will run between 2 and 4 times per day between the hours of 10 AM and 5 PM.
schedule = get_todays_run_schedule((2, 4), (10, 17))
while(True):
now = datetime.now()
nowsecs = get_epochtime(now)
if now.hour == 0 and now.minute == 0 and now.second == 0:
schedule = get_todays_run_schedule()
if nowsecs in schedule:
execute_my_function
sleep(1)
Basically the idea is that at midnight and at first run, we come up with a run schedule which is a list of epoch times, the length of which is between two supplied integers. Each second we check the time and if the current time is within the list of run times, we execute our function. Finally, we sleep until the next second.
However, it isn't working at all. I suspect this might be because my datetime objects somehow include microseconds which is throwing off the comparison, but it could be because of something I'm not understanding about the nature of date time comparisons in python.
It's true that microseconds will be a problem for you here—both the objects in your list and the now will have microseconds, and running a loop only about once/second, the chance of any of those nows exactly matching an event timestamp are pretty slim.
But even if you fix that by truncating both now and the values in the list to seconds, that still won't solve the problem, it'll just make it an intermittent problem that's harder to debug. Consider what happens if you have an event at 15:25:26, and you start the loop at 15:25:25.907. You truncate that to 15:25:25, look it up, it's not there. Then you sleep for about a second, and call now(), and you get, say, 15:25:27.033. You truncate that to 15:25:27, look it up, and it's not there either.
Since you've already sorted the list, you can do something a whole lot simpler, which I'll demonstrate below. But first: While we're at it, the whole point of datetime objects is that they can do time comparisons, arithmetic, etc. directly, so you don't need to convert everything to numbers with something like your get_epochtime.
yesterday = datetime.today() - datetime.timedelta(days=1)
while True:
now = datetime.now()
if now.date() > yesterday:
schedule = get_todays_run_schedule()
yesterday = now.date()
while schedule and now >= schedule[0]:
del schedule[0]
execute_my_function
sleep(1)
(Obviously you'll also need to change get_todays_run_schedule to return a list of datetime objects instead of a list of floats to do it this way, but you should be able to figure that out.)
Also, notice that this way, we always know the time until the next event, so we don't need to loop around sleep(1) and keep waking the computer every second while it's on battery. You can just sleep(schedule[0] - now) when there is a next event, or sleep until midnight when there isn't. Or, maybe more simply, generate tomorrow's schedule when schedule goes empty, and then just sleep until its schedule[0].
In fact, if you think about it, you should be able to figure how to turn this into a loop in this form:
while True:
schedule = make_today_or_tomorrow_schedule()
for event in schedule:
while datetime.now() < event:
sleep(event - datetime.now())
execute_my_function

Categories