Compare the time of datetime.now() object with time string - python

Using Rouble's suggestion and Maulik Gangani's example based on that suggestion:
How do I determine if current time is within a specified range using Python's datetime module?
I have two time strings that have been converted into a datetime object using .strptime as follows:
timeStart = '0300'
timeStart = datetime.strptime(timeStart, '%H%M')
I have a datetime object for time now:
timeNow = datetime.now()
My problem is that unless I convert timeNow (datetime object) into a string and then back again using .strptime , the script will not work:
timeNow = datetime.now()
timeNow = datetime.strftime(timeNow, '%H%M')
timeNow = datetime.strptime(timeNow, '%H%M')
Full code:
from datetime import datetime
def isNowInTimePeriod(startTime, endTime, nowTime):
if startTime < endTime:
return nowTime >= startTime and nowTime <= endTime
else: #Over midnight
return nowTime >= startTime or nowTime <= endTime
timeStart = '0300'
timeEnd = '1000'
timeEnd = datetime.strptime(timeEnd, '%H%M')
timeStart = datetime.strptime(timeStart, '%H%M')
timeNow = datetime.now()
timeNow = datetime.strftime(timeNow, '%H%M')
timeNow = datetime.strptime(timeNow, '%H%M')
My question is, how do I format timeNow = datetime.now() so that I can compare it against a string in 24hr format '0000' without having to convert datetime.now() to a string and back again?

The reason why your code is not working, it's because apart from time, datetime (as the name suggests) holds also information about the date.
When you run the following code:
timeStart = '0300'
timeStart = datetime.strptime(timeStart, '%H%M')
The hour and minute is converted, but the rest (the "date" part) is assumed to be epoch:
repr(timeStart)
# Output: 'datetime.datetime(1900, 1, 1, 3, 0)'
When you run datetime.now(), however, that always assumes the current time + date:
>>> datetime.now()
datetime.datetime(2020, 7, 17, 8, 25, 18, 270848)
The reason why converting to string, and back from string works, is because when you convert your datetime to a string with the format '%H%M, you lose the date part in the resulting string. Converting back from that, there's only hour and minutes to read, so you're losing the date part.
Effectivelly, you should be using datetime.time, instead of datetime.datetime to compare time.
After reading using strptime, try using the .time() method to only extract the time part and lose the date part:
timeStart = '0300'
timeStart = datetime.strptime(timeStart, '%H%M').time()
And same for the timeNow part:
timeNow = datetime.now().time()

If you call datetime.strptime, a default date is added if you only supply a time string. datetime.now() will have today's date. You can remove that by using only the time part of the datetime object - which you get by calling the time() method, e.g.
from datetime import datetime
def isNowInTimePeriod(startTime, endTime, nowTime):
if startTime < endTime:
return nowTime >= startTime and nowTime <= endTime
else: #Over midnight
return nowTime >= startTime or nowTime <= endTime
timeStart = '0300'
timeEnd = '1000'
timeEnd = datetime.strptime(timeEnd, '%H%M').time()
timeStart = datetime.strptime(timeStart, '%H%M').time()
timeNow = datetime.now().time()
print(isNowInTimePeriod(timeStart, timeEnd, timeNow))
# True (my current time is 0823)

Related

Number of 15 minutes intervals between two datetimes

from datetime import datetime, timedelta
now = datetime.now()
start = now + timedelta(minutes = 15)
finish = start + timedelta(minutes = 30)
How can I find the number of 15 minutes intervals exist between start and finish?
from datetime import datetime, timedelta
now = datetime.now()
start = now + timedelta(minutes = 15)
finish = start + timedelta(minutes = 30)
elapsed = finish - start
number_of_intervals = elapsed / timedelta(minutes=15)
elapsed is the timedelta between start and finish. Divide by 15 minutes to calculate how many 15 minute intervals fit in there.
Note that this returns a float, so includes fractional intervals. Round as appropriate.
You need to find the difference between start and finish in minutes, divide by 15, and make that an int:
now = datetime.now()
start = now + timedelta(minutes = 15)
finish = start + timedelta(minutes = 30)
difference = (finish - start).total_seconds()/60
quarters = int(difference/15)
i would write something similar to this:
from datetime import datetime, timedelta
DATE_TIME_STRING_FORMAT = '%Y-%m-%dT%H:%M:%S.%fZ'
from_date_time = datetime.strptime('2016-06-06T05:00:00.000Z',
DATE_TIME_STRING_FORMAT)
to_date_time = datetime.strptime('2016-06-06T06:00:00.000Z',
DATE_TIME_STRING_FORMAT)
date_times = [from_date_time.strftime(DATE_TIME_STRING_FORMAT)]
date_time = from_date_time
while date_time < to_date_time:
date_time += timedelta(minutes=15)
date_times.append(date_time.strftime(DATE_TIME_STRING_FORMAT))
print(date_times)
Output:
['2016-06-06T05:00:00.000000Z', '2016-06-06T05:15:00.000000Z', '2016-06-06T05:30:00.000000Z', '2016-06-06T05:45:00.000000Z', '2016-06-06T06:00:00.000000Z']
Edit:
If you are interested in just the number of 15 minute intervals you can use something like:
from datetime import datetime, timedelta
DATE_TIME_STRING_FORMAT = '%Y-%m-%dT%H:%M:%S.%fZ'
from_date_time = datetime.strptime('2016-06-06T05:00:00.000Z',
DATE_TIME_STRING_FORMAT)
to_date_time = datetime.strptime('2016-06-06T06:00:00.000Z',
DATE_TIME_STRING_FORMAT)
print((to_date_time-from_date_time) / timedelta(minutes=15))
You can use time library instead of date time. time works with seconds and you should convert minutes to seconds:
import time
interval = 45*60
start = time.time()
finish = time.time() + interval
diff = finish - start
print(diff // (15*60))
Simply compare start and finish like so:
from datetime import datetime, timedelta
now = datetime.now()
start = now + timedelta(minutes = 15)
finish = start + timedelta(minutes = 30)
elapsed = finish - start # This is a timedelta object
reference_interval = 15*60 # interval in seconds
number_of_intervals = elapsed.seconds/reference_interval
As pointed out by Sören, this will not work if 'elapsed' is more than one day, in which case, simply compute the number as follow:
number_of_intervals = (elapsed.days*86400+elapsed.seconds)/reference_interval
# (86400 seconds in a day)

Compare only today's date without hours/min/sec

I want to compare todays time with another new time without hour/min or seconds. Ignore hour and minutes...
In other words if both days are the same no matter hours or minutes it is ok (Extra) otherwise it is not good (Too old)... I tried but even with the same day still continue to compare with hour/min and sec. How can I do it?
import datetime
currentdate = datetime.datetime.now()
print(currentdate)
newsdate = "Oct-26-2021"
newsdate = datetime.datetime.strptime(newsdate, "%b-%d-%Y")
print(newsdate)
if currentdate == newsdate:
print("Extra")
else:
print("Too old")`
Compare using only the date component of datetime, accessible via the .date() attribute:
import datetime
currentdate = datetime.datetime.now()
print(currentdate)
newsdate = "Oct-26-2021"
newsdate = datetime.datetime.strptime(newsdate, "%b-%d-%Y")
print(newsdate)
if currentdate.date() == newsdate.date():
print("Extra")
else:
print("Too old")
The above can also be reworded as follows (perhaps to aid in readability for others):
from datetime import date, datetime
currentdate: date = date.today()
print(currentdate)
date_string = "Oct-26-2021"
newsdate: date = datetime.strptime(date_string, "%b-%d-%Y").date()
print(newsdate)
if currentdate == newsdate:
print("Extra")
else:
print("Too old")

Calculating time intervals in Python, a more smarter way

was trying to calculate and a timedelta element with a str concatente, finally got it but feel there should be a smarter way to do this, any idea pls. here are my lines of code:
import datetime
import time
currentTime = datetime.datetime.now()
print("The time now is " + currentTime.strftime('%I:%M %p'))
realTime = currentTime.strftime('%I:%M:%S %p')
realTime was necessary to convert the datetime currentTime to a str to feed to strptime
print(realTime)
meetTime = input("Please input the meeting time in 12hrs timing")
# timeToMeet = datetime.datetime.strptime('11:50PM', '%I:%M%p').time()
timeToMeet = datetime.datetime.strptime(meetTime, '%I:%M%p')
tried both static and input time and they both worked
print(timeToMeet.strftime('%H:%M %p'))
timeNow = datetime.datetime.strptime(realTime, '%I:%M:%S %p')
print("The time now is " + timeNow.strftime('%I:%M%p'))
tdelta = timeToMeet - timeNow
print("Please, your meeting starts in " + str(tdelta))
print(tdelta)

How to make a count for each day passed from start date in python

I'm looking for a way to count each day passed from a start date in python. So if the start date was 21/02/2020 and count equals to 0, when the next day starts count should increment by 1.
Edit: After using Rusty's code I am able to show you a minimal reproducible example.
import datetime
start = datetime.datetime.strptime(input("Choose a start date (mm/dd/yyyy): "), '%m/%d/%Y')
current = datetime.datetime.now()
delta = current - start
count = delta.days
print(count)
import datetime
import time
count = 0
# "...from today..."
today = datetime.datetime.today()
# "...to infinity..."
while True:
now = datetime.datetime.today()
# "...as soon as the next day starts..."
if today.day != now.day:
# "...it would increment count by 1..."
count = count + 1
print(count)
today = now
time.sleep(1)
import datetime
today = datetime.datetime.strptime('03/21/2020', '%m/%d/%Y')
tomorrow = datetime.datetime.strptime('03/22/2020', '%m/%d/%Y')
next_saturday = datetime.datetime.strptime('03/28/2020', '%m/%d/%Y')
delta = tomorrow - today
count = delta.days
print(count)
delta = next_saturday - today
count = delta.days
print(count)

if date is weekend - auto rerun the function

So I can generate random days in a given start-end date relationship, but, if the date happens to be a weekend - currently all I can get working is to print to the user 'it is a weekend'. What I would like to do is, if the random day IS a weekend, rerun the function so the user does not have to manually. Basically - only print out weekdays - currently, if the random day is a weekend, it prints a blank space or None value. Only return/print weekdays is the main goal.
Here is the code so far:
from datetime import datetime, timedelta
from random import randrange
def random_date(start, end):
delta = end - start
random_day = randrange(delta.days)
myresult = start + timedelta(days=random_day)
return myresult
d1 = datetime.strptime('9/1/2018', '%m/%d/%Y')
d2 = datetime.strptime('9/30/2018', '%m/%d/%Y')
myresult = random_date(d1, d2)
if myresult.weekday() not in (5, 6):
print myresult.strftime('%m-%d-%Y')
else:
print "hit a weekend"
An option:
def random_weekday(start, end):
date = None
while (not date or date.weekday() in (5, 6)):
days = randrange((end - start).days)
date = start + timedelta(days=days)
return date
start = datetime.strptime('9/1/2018', '%m/%d/%Y')
end = datetime.strptime('9/30/2018', '%m/%d/%Y')
for i in range(20):
print(random_weekday(start, end).strftime('%m-%d-%Y'))
So, you need a while-loop to keep getting dates until you get one that's not a weekend, like this:
from datetime import datetime
from random import randrange
from datetime import timedelta
def random_date(start, end):
delta = end - start
random_day = randrange(delta.days)
myresult = start + timedelta(days=random_day)
return myresult
while True:
d1 = datetime.strptime('9/1/2018', '%m/%d/%Y')
d2 = datetime.strptime('9/30/2018', '%m/%d/%Y')
myresult = random_date(d1, d2)
if myresult.weekday() not in (5,6):
break
print myresult.strftime('%m-%d-%Y')

Categories