I have found some solution but most of them talks about the current date. What I want is that to check if a current time is within 23:00:00
and 07:00:00
next day. I am facing difficulty because date is also involved into this. So if the current time is 00:00:00
then the date would also change and comparing the time with same day 23:00:00
would give me a faulty result. This is what I have come up with now. Please help me in finding the solution
cur_time = dt.strptime('2/9/16 00:00', "%m/%d/%y %H:%M")
prev_date = dt.strftime(cur_time.date() - timedelta(days=1), "%m/%d/%y")
same_date = dt.strftime(cur_time.date(), '%m/%d/%y')
dosta = dt.strptime(prev_date + "22:00", "%m/%d/%y%H:%M")
satta = dt.strptime(same_date + "07:00", "%m/%d/%y%H:%M")
if dosta < cur_time < satta:
tariff = 3
else:
tariff = 6
print(tariff)
This would result the tariff to be 3 but if I change the cur_time
like this
cur_time = dt.strptime('2/9/16 23:00', "%m/%d/%y %H:%M")
this won't yield 3. This would give me 6. Because this is comparing the current time with previous day 00:00
and current day 07:00
and current day 23:00
would obviously be greater.
Edit 1
Input: 2/9/16 06:00:00
Output: 3...because 06:00:00 is less than 07:00:00 that same day(2/9/2016) and more than 22:00:00 previous day(2/8/16)
Input: 2/9/16 23:00:00
Output: 3...because 23:00:00 is more than 22:00:00 that same day(2/9/2016)
Input: 2/10/16 00:30:00
Output: 3...because 00:30:00 is more than 22:00:00 that previous day(2/9/2016) and less than 07:00:00 same day(2/10/2016)
Input: 2/10/16 08:00:00
Output: 6...because 08:00:00 is more than 07:00:00 that same day(2/9/2016) and less than 22:00:00 on the same day(2/9/2016)
Edit 2
It is still not working with timedelta
as pointed out by @a_guest
.
Here is the code
for each in zip(data1, data2):
# client.write_points(json_body_bill_data)
cur_time = dt.strptime(each[1]['Start'], "%m/%d/%y %H:%M")
# print(cur_time.date())
dosta = dt.strptime('2200', '%H%M').time()
# print(dosta)
lower = datetime.datetime.combine(cur_time.date(), dosta)
upper = lower + timedelta(hours=8.5)
print("lower", lower)
print("upper", upper)
print(cur_time, lower < cur_time < upper)
This is giving me false if cur_time
is 00:00:00 9/2/16
Edit 3
The probable answer
from datetime import datetime, time
import csv
import os
CSV_FILE_ASCO = os.path.join('..', 'res', 'ASCO_METER.csv')
with open(CSV_FILE_ASCO, 'r') as f:
reader = csv.DictReader(f)
data = list(reader)
for each in data:
# print()
cur_date = datetime.strptime(each['Start'], "%m/%d/%y %H:%M")
if time(7, 0) <= cur_date.time() < time(22, 0):
tarrif = 6
else:
tarrif = 3
print(cur_date, end=" ")
print(tarrif)
Can It be improved further. I bet there has to be a more pythonic way to do it