Getting number of Hours between a Date-Time Range in Python - python

So I'm trying to print the total hours in intervals between a start date and an end date in python as follows:
#app.route('/test/')
def test():
date_format = "%Y-%m-%d %H:%M:%S"
start_date_time = datetime.strptime("2018-10-16 07:00:00", date_format)
end_date_time = datetime.strptime("2018-10-18 22:00:00", date_format)
def daterange(start_date_time, end_date_time):
for n in range(int ((end_date_time - start_date_time).days)):
yield start_date_time + timedelta(n)
for single_date in daterange(start_date_time, end_date_time):
def get_delta(start_date_time, end_date_time):
delta = end_date_time - start_date_time
return delta
# Split time in hours
delta = get_delta(start_date_time,end_date_time)
for i in range(delta.days * 24 + 1): # THIS IS ONLY CALCULATING 24HRS FROM TIME GIVEN START TIME NOT TILL THE SELECTED END TIME SO I'M ONLY GETTING AN EXACT 24 HOUR RANGE
currtime = start_date_time + timedelta(hours=i)
print (currtime)
return ("done")
By This i'm only managing to get the first 24 Hours from the selected date, but I wish to keep on counting and get all hours till the selected end date.

You might be overthinking it.
from datetime import datetime, timedelta
date_format = "%Y-%m-%d %H:%M:%S"
start_date_time = datetime.strptime("2018-10-16 07:00:00", date_format)
end_date_time = datetime.strptime("2018-10-18 22:00:00", date_format)
def get_delta(l, r):
return abs(int((l-r).total_seconds())) / 3600
for h in range(int(get_delta(start_date_time, end_date_time))):
print((start_date_time + timedelta(0, h*3600)).strftime(date_format))

Related

Time to next full hour

I have a timestamp like the following:
Timestamp('2022-01-01 19:55:00')
How do i get the time difference to the next full hour (in minutes)?
So in this example the output should be 5 minutes.
You'll need to use the datetime lib :
from datetime import datetime, timedelta
def time_to_next_hour(timestamp):
current_time = datetime.strptime(str(timestamp), '%Y-%m-%d %H:%M:%S')
next_hour = current_time.replace(microsecond=0, second=0, minute=0) + timedelta(hours=1)
time_diff = next_hour - current_time
return int(time_diff.total_seconds() / 60)
print(time_to_next_hour(Timestamp('2022-01-01 19:55:00')))

calculate working hours for current week in django

let us consider start time, end time and Break time as
models.py
class Records(TimeStampedModel):
date = models.DateField()
start_time = models.TimeField(default='08:30')
end_time = models.TimeField(default='08:30')
break_time = models.FloatField(default=0.5, help_text="(Hrs)")
views.py
def record_working hours(request):
records = Records.objects.filter(created_by__client=request.user.client)
now = timezone.now()
today = timezone.now().date()
week_start = today - timedelta(days=(today.weekday()))
date_list = [week_start + timedelta(days=x) for x in range(5)]
week_last = date_list[-1]
working_time = records.filter(date__gte=week_start,date__lte=week_last)
for record in records:
work_hours = record.start_time - record.end_time - record.break_time
return redirect(reverse('record_list'))
Hear i need to calculate total working hours for current week but i am getting the error as " type object 'datetime.datetime' has no attribute 'datetime'" and when i print my start time, end time and break time i am getting as
start_time = datetime.time(8, 30)
end_time = datetime.time(18, 30)
break_time = 0.5
And also calculate total working hours for that week of all records

Python: Hours between two datetimes by day

I tried to develop a Python function that determines the difference between two datetime objects. I need an algorithm that calculates the number of hours per day. Is there a built-in function for this?
from datetime import datetime, timedelta, date
def getHoursByDay(dateA, dateB):
...
dateA = datetime.strptime('2018-09-01 09:00:00', '%Y-%m-%d %H:%M:%S')
dateB = datetime.strptime('2018-09-03 11:30:00', '%Y-%m-%d %H:%M:%S')
hours = getHoursByDay(dateA, dateB)
print hours
# {
# '2018-09-01': 15,
# '2018-09-02': 24,
# '2018-09-03': 11.5,
# }
There is no built-in function, though it is very simple to build one.
from datetime import datetime, timedelta, time
def deltaByDay(dateA, dateB):
dateAstart = datetime.combine(dateA, time())
dateBstart = datetime.combine(dateB, time())
result = {}
oneday = timedelta(1)
if dateAstart == dateBstart:
result[dateA.date()] = dateB - dateA
else:
nextDate = dateAstart + oneday
result[dateA.date()] = nextDate - dateA
while nextDate < dateBstart:
result[nextDate.date()] = oneday
nextDate += oneday
result[dateB.date()] = dateB - dateBstart
return result
def deltaToHours(delta, ndigits=None):
return delta.days * 24 + round(delta.seconds / 3600.0, ndigits)
dateA = datetime.strptime('2018-09-01 09:00:00', '%Y-%m-%d %H:%M:%S')
dateB = datetime.strptime('2018-09-03 11:30:00', '%Y-%m-%d %H:%M:%S')
deltas = deltaByDay(dateA, dateB);
output = {k.strftime('%Y-%m-%d'): deltaToHours(v, 1) for k, v in deltas.items()}
print(output)
# => {'2018-09-01': 15.0, '2018-09-02': 24.0, '2018-09-03': 11.5}
The built in timedelta functions would be able to get you the total days, and the remaining hours difference. If you want the output specifically in that dictionary format posted you would have to create it manually like this:
from datetime import datetime, time, timedelta
def getHoursByDay(dateA, dateB):
if dateA.strftime("%Y-%m-%d") == dateB.strftime("%Y-%m-%d"):
return {dateA.strftime("%Y-%m-%d"): abs(b-a).seconds / 3600}
result = {}
delta = dateB - dateA
tomorrow = dateA + timedelta(days=1)
day1 = datetime.combine(tomorrow, time.min) - dateA
result[dateA.strftime("%Y-%m-%d")] = day1.seconds / 3600
for day in range(1, delta.days):
result[(dateA + timedelta(days=day)).strftime("%Y-%m-%d")] = 24
priorday = dateB - timedelta(days1)
lastday = dateB - datetime.combine(priorday, time.min)
result[dateB.strftime("%Y-%m-%d")] = lastday.seconds / 3600
return result
Essentially this function calculates the first day and the last day values, then populates all the days in between with 24.
There is a kind of simple way to do this.
hours = (dateA - dateB).hours
I've used this to caclulate a difference in days.
https://docs.python.org/2/library/datetime.html#datetime.timedelta

A simple mathematic Operation python

I have a method which returns the number of days within a specified range and excluding some specific days like Friday. here is an example if you take out friday and thursday, from 2016-8-6 to 2016-9-6 the result will be 8 days holiday and 24 working day. in case i want to do the reverse operation how do i find the end date (2016-9-6) if i have only working days and start date.
from datetime import datetime, timedelta
def measure_workingdays(start_date, end_date, off_days):
format = "%Y-%m-%d"
if not isinstance(start_date, datetime):
start_date = datetime.strptime(start_date, format)
if not isinstance(end_date, datetime):
end_date = datetime.strptime(end_date, format)
total_days = (end_date - start_date).days + 1 # + 1 Because it count one day less
holiday = 0
start = start_date
for rec in range(total_days):
day = start.strftime("%a")
if day in off_days:
holiday += 1
start += timedelta(days=1)
print(holiday) # 8
working_days = total_days - holiday
print(working_days) # 24
start_date = "2016-8-6"
start_date = datetime.strptime(start_date, "%Y-%m-%d")
end_date = "2016-9-6"
end_date = datetime.strptime(end_date, "%Y-%m-%d")
off_day = ['Fri','Thu']
working_days = measure_weekdays(start_date, end_date, off_day)
Example of Reverse operation
def measure_weekdays_reverse(start_date, paid, off_days):
format = "%Y-%m-%d"
if not isinstance(start_date, datetime):
start_date = datetime.strptime(start_date, format)
holiday = 0
start = start_date
for rec in range(paid):
day = start.strftime("%a")
if day in off_days:
holiday += 1
start += timedelta(days=1)
print(holiday) # Output 6 instead of 8
last_paid_date = start + timedelta(days=holiday)
print(last_paid_date) # output 2016-09-05 insteaad of 2016-09-06
total_days = measure_weekdays_reverse(start_date, 24, ["Fri","Thu"])
The error is that you only loop a fix number of times (the number of paid days), so if you encounter holidays, you will in fact not iterate enough to find all the true paid days, which may still hide some holidays.
You can fix this by adding an inner loop on the holidays. Change this:
for rec in range(paid):
day = start.strftime("%a")
if day in off_days:
holiday += 1
start += timedelta(days=1)
print(holiday) # Output 6 instead of 8
last_paid_date = start + timedelta(days=holiday)
to this:
for rec in range(paid):
day = start.strftime("%a")
while day in off_days:
holiday += 1
start += timedelta(days=1)
day = start.strftime("%a")
last_paid_date = start
start += timedelta(days=1)
print(holiday)

Converting 12 hour format time string (with am/pm) into UTC in 24 hour format

I have time string 11:15am or 11:15pm.
I am trying to convert this string into UTC timezone with 24 hour format.
FROM EST to UTC
For example: When I pass 11:15am It should convert into 15:15 and when I pass 11:15pm then it should convert to 3:15.
I have this code which I am trying:
def appointment_time_string(time_str):
import datetime
a = time_str.split()[0]
# b = re.findall(r"[^\W\d_]+|\d+",a)
# c = str(int(b[0]) + 4) + ":" + b[1]
# print("c", c)
in_time = datetime.datetime.strptime(a,'%I:%M%p')
print("In Time", in_time)
start_time = str(datetime.datetime.strftime(in_time, "%H:%M:%S"))
print("Start TIme", start_time)
if time_str.split()[3] == 'Today,':
start_date = datetime.datetime.utcnow().strftime("%Y-%m-%dT")
elif time_str.split()[3] == 'Tomorrow,':
today = datetime.date.today( )
start_date = (today + datetime.timedelta(days=1)).strftime("%Y-%m-%dT")
appointment_time = str(start_date) + str(start_time)
return appointment_time
x = appointment_time_string(time_str)
print("x", x)
But this is just converting to 24 hour not to UTC.
To convert the time from 12 hours to 24 hours format, you may use below code:
from datetime import datetime
new_time = datetime.strptime('11:15pm', '%I:%M%p').strftime("%H:%M")
# new_time: '23:15'
In order to convert time from EST to UTC, the most reliable way is to use third party library pytz. Refer How to convert EST/EDT to GMT? for more details
Developed the following script using provided options/solutions to satisfy my requirement.
def appointment_time_string(time_str):
import datetime
import pytz
a = time_str.split()[0]
in_time = datetime.datetime.strptime(a,'%I:%M%p')
start_time = str(datetime.datetime.strftime(in_time, "%H:%M:%S"))
if time_str.split()[3] == 'Today,':
start_date = datetime.datetime.utcnow().strftime("%Y-%m-%d")
elif time_str.split()[3] == 'Tomorrow,':
today = datetime.date.today( )
start_date = (today + datetime.timedelta(days=1)).strftime("%Y-%m-%d")
appointment_time = str(start_date) + " " + str(start_time)
# print("Provided Time", appointment_time)
utc=pytz.utc
eastern=pytz.timezone('US/Eastern')
fmt='%Y-%m-%dT%H:%M:%SZ'
# testeddate = '2016-09-14 22:30:00'
test_date = appointment_time
dt_obj = datetime.datetime.strptime(test_date,'%Y-%m-%d %H:%M:%S')
dt_str = datetime.datetime.strftime(dt_obj, '%m/%d/%Y %H:%M:%S')
date=datetime.datetime.strptime(dt_str,"%m/%d/%Y %H:%M:%S")
date_eastern=eastern.localize(date,is_dst=None)
date_utc=date_eastern.astimezone(utc)
# print("Required Time", date_utc.strftime(fmt))
return date_utc.strftime(fmt)

Categories

Resources