Coverage of duration per hour calculation - python

Given a start time Timestamp('2015-05-06 09:40:45') and an end time Timestamp('2015-05-06 011:12:13'), I want to determine the number of minutes covered per hour of this duration.
That is, I want the following output:
hour 9 -- 19.25 minutes
hour 10 -- 60.00 minutes
hour 11 -- 12.22 minutes
I have an algorithm in mind, but I'm stumped comparing int and timestamp.

We are assuming that the start date and end date are the same.
from datetime import datetime
starttime = datetime(year = 2015, month = 5, day =6, hour=9, minute=40, second=45)
endtime = datetime(year = 2015, month = 5, day =6, hour=11, minute=12, second=13)
for i in range(starttime.hour, endtime.hour+1):
if i == starttime.hour:
rightbound = datetime(starttime.year, starttime.month, starttime.day, hour=(i+1), minute=0, second=0)
print starttime.hour, (rightbound - starttime).seconds/60.
elif i == endtime.hour:
leftbound = datetime(starttime.year, starttime.month, starttime.day, hour=(i), minute=0, second=0)
print leftbound.hour, (endtime - leftbound).seconds/60.
else:
print i, "60"
The (nth hour, # of minutes) output is:
9 19.25
10 60
11 12.2166666667

Related

Add hours to workday in python

I need the following script to compute the working hours from 9 am to 6 pm, so that if I add 5 hours it will be added from 9 am the next day.
Example: if it is now 5 pm and I add 5 hours and the working day ends at 6 pm, the output would be: 13 hours.
17 + 1 = 18 and
9 + 4 = 13 hs
So far the script computes hours regardless of the labor restriction.
from datetime import datetime, timedelta
updated = ( datetime.now() +
timedelta( hours = 5 )).strftime('%H:%M:%S')
print( updated )
--22:12:00
Here you are:
workday_begin = time(9)
workday_end = time(18)
# compute workday length
workday_hours = datetime.combine(date.today(), workday_end) - datetime.combine(date.today(), workday_begin)
# this is timedelta from your example
duration_hours = timedelta(hours=17)
# ignore times longer than a workday
day_cnt = 0 # this could be used to know how many day we've skipped, not part of question tho
while duration_hours > workday_hours:
day_cnt += 1
duration_hours -= workday_hours
now = datetime.now()
# now = datetime(2021,12,10,11,25,16)
if workday_begin < now.time() < workday_end:
# now is in work-hours
if datetime.combine(date.today(), workday_end) - now < duration_hours:
# duration would exceed work-hours, jumping to next day
day_cnt += 1
duration_hours -= (datetime.combine(date.today(), workday_end) - now)
updated = datetime.combine(date.today(), workday_begin) + duration_hours
else:
# everything is fine, just add hours
updated = now + duration_hours
else:
# now is not in work-hours. Add remaining duration to workday begin
updated = datetime.combine(date.today(), workday_begin) + duration_hours
# keep just a time part
updated = updated.time().strftime('%H:%M:%S')
print( updated )
I hope I understood your question.

How to caculate time diffs between two date times?

diff = reference_time - topic_time
hour = round((reference_time-topic_time) / datetime.timedelta(hours=1))
if reference_time = '2020-08-23 07:00:10' and topic_time = '2020-08-22 00:00:00', the 'diff' variable is:
days = 1
seconds = 25210
The 'hour' conversion code make the hour = 31, which seems incorrect. The max diff should be less than 24 hours in one day. How to calculate time diffs and convert to hours in this case?
import datetime
firstTime = datetime.datetime.utcnow()
secondTime = datetime.datetime.utcnow() + datetime.timedelta(hours=5)
diff = secondTime - firstTime
hours = diff.total_seconds() // 3600
print(hours) # Answer is 5
reference_time = datetime.datetime(2020,8,23,7)
topic_time = datetime.datetime(2020,8,22,0)
hours = (reference_time - topic_time).total_seconds() // 3600
days = hours // 24
hours = hours - (days*24)
print('days: %d, hours: %d' % (days, hours) ) # days:1, hours:7

Python and check if current datetime is in specific range

I am trying to do something similar to this, but i want to specify the start date and end date by actual weekday names and times. For example, I want to check if the current datetime (datetime.datetime.now()) is in between Tuesday at 4:30pm and Thursday at 11:45am. This would update weekly so it has to be by Tuesday/Thursday mentality.
I have thought about how to do the weekdays (but i don't know how to wrap the time part into it):
TimeNow = datetime.datetime.now()
if TimeNow.weekday() >= 1 and TimeNow.weekday() <= 3:
#runcodehere
Any thoughts on how i would do this?
Neatest way is to use the amount of minutes elapsed in a week:
def mins_in_week(day, hour, minute):
return day * 24 * 60 + hour * 60 + minute
if (mins_in_week(1, 16, 30) <
mins_in_week(TimeNow.weekday(), TimeNow.hour, TimeNow.minute) <
mins_in_week(3, 11, 45)):
....
It's not very neat but something like this should work:
TimeNow = datetime.datetime.now()
if (TimeNow.weekday() == 1 and ((TimeNow.hour() == 4 and TimeNow.minute >= 30) or TimeNow.hour > 4)) or (TimeNow.weekday() == 2) or (TimeNow.weekday() == 3 and (TimeNow.hour() < 11 or (TimeNow.hour() == 11 and TimeNow.minute <= 45)):
#runcodehere
You can use a combination of and and or, and have different conditions for each day:
import datetime
TimeNow = datetime.datetime.now()
day_now = TimeNow.weekday()
time_now = TimeNow.hour*60 + TimeNow.minute
if (day_now == 1 and time_now > 990) or (day_now == 2) or (day_now == 3 and time_now < 705):
# do something

Hour deltatime mistake

now = datetime.now()
d1 = datetime(now.year, now.month, now.day, now.hour, now.minute, 0)
if now.minute in xrange(46, 60):
res = 0
print now.hour
print now.hour+1
d1 = d1 + timedelta(hours=now.hour+1)
print d1
now.hour prints, for example, 15. Second line shows up 16 but d1 after adding timedelta becomes: 2012-07-21 07:57:00. This date is next day at 7am.
What's wrong?
You create a timedelta with a value of 16 hours and then add that to d1. d1 (if already at 15 hours) plus 16 hours will be 07 hours the next day.
You don't say what you are trying to achieve but if you are trying to increment by one hour then you should use d1 = d1 + timedelta(hours=1);

Find time until a date in Python

What's the best way to find the time until a date. I would like to know the years, months, days and hours.
I was hoping somebody had a nice function. I want to do something like: This comment was posted 2month and three days ago or this comment was posted 1year 5months ago.
datetime module, datetime and timedelta objects, it will give you days and seconds.
In [5]: datetime.datetime(2009, 10, 19) - datetime.datetime.now()
Out[5]: datetime.timedelta(2, 5274, 16000)
In [6]: td = datetime.datetime(2009, 10, 19) - datetime.datetime.now()
In [7]: td.days
Out[7]: 2
In [8]: td.seconds
Out[8]: 5262
You should use dateutil.relativedelta.
from dateutil.relativedelta import relativedelta
import datetime
today = datetime.date.today()
rd = relativedelta(today, datetime.date(2001,1,1))
print "comment created %(years)d years, %(months)d months, %(days)d days ago" % rd.__dict__
Let's asume you have the future datetime in a variable named eta:
(eta - datetime.datetime.now()).total_seconds()
Datetime difference results in a timedelta object, which happens to implement a method named total_seconds. That's it :)
I was looking for something more like this ... which took some hard work to find.
import datetime
SECOND = 1
MINUTE = 60 * SECOND
HOUR = 60 * MINUTE
DAY = 24 * HOUR
MONTH = 30 * DAY
def get_relative_time(dt):
now = datetime.datetime.now()
delta_time = dt - now
delta = delta_time.days * DAY + delta_time.seconds
minutes = delta / MINUTE
hours = delta / HOUR
days = delta / DAY
if delta < 0:
return "already happened"
if delta < 1 * MINUTE:
if delta == 1:
return "one second to go"
else:
return str(delta) + " seconds to go"
if delta < 2 * MINUTE:
return "a minute ago"
if delta < 45 * MINUTE:
return str(minutes) + " minutes to go"
if delta < 90 * MINUTE:
return "an hour ago"
if delta < 24 * HOUR:
return str(hours) + " hours to go"
if delta < 48 * HOUR:
return "yesterday"
if delta < 30 * DAY:
return str(days) + " days to go"
if delta < 12 * MONTH:
months = delta / MONTH
if months <= 1:
return "one month to go"
else:
return str(months) + " months to go"
else:
years = days / 365.0
if years <= 1:
return "one year to go"
else:
return str(years) + " years to go"
may be you want something like this:
import datetime
today = datetime.date.today()
futdate = datetime.date(2016, 8, 10)
now = datetime.datetime.now()
mnight = now.replace(hour=0, minute=0, second=0, microsecond=0)
seconds = (mnight - now).seconds
days = (futdate - today).days
hms = str(datetime.timedelta(seconds=seconds))
print ("%d days %s" % (days, hms))

Categories