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.
I'm just starting out with Python and wondering how I would go about sorting this
list from the earliest time to the latest.
('5:00PM','2:00PM','7:00AM','8:45PM','12:00PM')
Any help is appreciated.
In python3 with standard library only:
import time
hours = ('5:00PM','2:00PM','7:00AM','8:45PM','12:00PM')
format = '%I:%M%p'
time_hours = [time.strptime(t, format) for t in hours]
result = [time.strftime(format, h) for h in sorted(time_hours)]
assert result == ['07:00AM', '12:00PM', '02:00PM', '05:00PM', '08:45PM']
I recommend that you install the PyPi DateTime package and use those facilities for whatever manipulation you desire. The problem at hand would look something like:
stamps = ('5:00PM','2:00PM','7:00AM','8:45PM','12:00PM')
DT_stamps = [DateTime(s) for s in stamps]
DT_stamps.sort()
Implementation details are left as an exercise for the student. :-)
If the times are always going to be in that format, you could split the times into subsections.
x = "12:30PM"
# Use python's string slicing to split on the last two characters
time, day_half = x[:-2], x[-2:]
# Use python's string.split() function to get the difference between hours and minutes
# Because "11" < "2" for strings, we need to convert them to integers
hour, minute = [int(t) for t in time.split(":")]
# Get the remainder because 12 should actually be 0
hour = hour % 12
# Output it as a tuple, which sorts based on each element from left to right
sortable = (day_half, hour, minute)
#: ("PM", 12, 30)
To wrap it all up, use something like:
def sortable_time(time_str):
time, day_half = time_str[:-2], time_str[-2:]
hour, minute = [int(t) for t in time.split(":")]
hour = hour % 12
return day_half, hour, minute
# When sorting, use `key` to define the method we're sorting with
# (The returned list however, will be filled with the original strings)
result = sorted(your_time_list, key=sortable_time)
#: ['7:00AM', '12:00PM', '2:00PM', '5:00PM', '8:45PM']
If you're not guaranteed to have the two letters at the end, or the colon in the middle, you're best off using a library like what is suggested by Prune.
What you're showing isn't a list of times, it's a tuple of strings. Tuples are immutable and can't be sorted, only mutable collections like lists can be. So first you need to convert your tuple to a list:
times = ['5:00PM','2:00PM','7:00AM','8:45PM','12:00PM']
You could try sorting this list now, but the strings won't sort the way you expect. Instead, you need to create a custom sort function that will temporarily convert the values in the list to struct_time objects and sort using those.
import time
time_format = '%I:%M%p' # match hours, minutes and AM/PM
def compare_as_time(time_str1, time_str2):
# parse time strings to time objects
time1 = time.strptime(time_str1, time_format)
time2 = time.strptime(time_str2, time_format)
# return comparison, sort expects -1, 1 or 0 to determine order
if time1 < time2:
return -1
elif time1 > time2:
return 1
else:
return 0
Now you can call sorted() and pass in your list and your custom comparison function and you'll get a list of strings back, sorted by the time in those strings:
sorted_times = sorted(times, compare_as_time)
Note for Python 3: The previous example assumes Python 2. If you're using Python 3, you'll need to convert the comparison function to a key function. This can be done using functools.cmp_to_key() as follows:
form functools import cmp_to_key
sorted_times = sorted(times, key=cmp_to_key(compare_as_time))
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)
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
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)