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
Related
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')))
I would like to write a function that calculate working business hours in python, to do that I don't like to define a class and use python ready function to calculate.
I tried with following code but the code is not working well. I need to modify the code and change it for the hour instead of minutes too.
Do you have any suggestion?
def getminutes(datetime1,datetime2,worktiming=[9, 17]):
day_hours = (worktiming[1]-worktiming[0])
day_minutes = day_hours * 60 # minutes in a work day
weekends=[6, 7]
# Set initial default variables
dt_start = datetime1.datetime # datetime of start
dt_end = datetime2.datetime # datetime of end
worktime_in_seconds = 0
if dt_start.date() == dt_end.date():
# starts and ends on same workday
full_days = 0
if dt_start in [6, 7]:
return 0
else:
if dt_start.hour < worktiming[0]:
# set start time to opening hour
dt_start = datetime.datetime(
year=dt_start.year,
month=dt_start.month,
day=dt_start.day,
hour=worktiming[0],
minute=0)
if dt_start.hour >= worktiming[1] or \
dt_end.hour < worktiming[0]:
return 0
if dt_end.hour >= worktiming[1]:
dt_end = datetime.datetime(
year=dt_end.year,
month=dt_end.month,
day=dt_end.day,
hour=worktiming[1],
minute=0)
worktime_in_seconds = (dt_end-dt_start).total_seconds()
elif (dt_end-dt_start).days < 0:
# ends before start
return 0
else:
# start and ends on different days
current_day = dt_start # marker for counting workdays
while not current_day.date() == dt_end.date():
if not is_weekend(current_day):
if current_day == dt_start:
# increment hours of first day
if current_day.hour < worktiming[0]:
# starts before the work day
worktime_in_seconds += day_minutes*60 # add 1 full work day
elif current_day.hour >= worktiming[1]:
pass # no time on first day
else:
# starts during the working day
dt_currentday_close = datetime.datetime(
year=dt_start.year,
month=dt_start.month,
day=dt_start.day,
hour= worktiming[1],
minute=0)
worktime_in_seconds += (dt_currentday_close
- dt_start).total_seconds()
else:
# increment one full day
worktime_in_seconds += day_minutes*60
current_day += datetime.timedelta(days=1) # next day
# Time on the last day
if not is_weekend(dt_end):
if dt_end.hour >= worktiming[1]: # finish after close
# Add a full day
worktime_in_seconds += day_minutes*60
elif dt_end.hour < worktiming[0]: # close before opening
pass # no time added
else:
# Add time since opening
dt_end_open = datetime.datetime(
year=dt_end.year,
month=dt_end.month,
day=dt_end.day,
hour=worktiming[0],
minute=0)
worktime_in_seconds += (dt_end-dt_end_open).total_seconds()
return int(worktime_in_seconds / 60)
How can I modify the code that works with the following input ?
getminutes(2019-12-02 09:30:00,2019-12-07 12:15:00,worktiming=[9, 17])
You can use pd.bdate_range(datetime1, datetime2) to compute the number of working days. When converting worktiming to a pandas datetime, it is easy to compute the difference (in seconds) between the two datetimes:
import pandas as pd
datetime1 = "2019-12-02 09:30:00"
datetime2 = "2019-12-07 12:15:00"
def getminutes(datetime1, datetime2, worktiming=[9, 17]):
d1 = pd.to_datetime(datetime1)
d2 = pd.to_datetime(datetime2)
wd = pd.bdate_range(d1, d2) # working days
day_hours = (worktiming[1] - worktiming[0])
day_minutes = day_hours * 60 # minutes in a work day
day_seconds = day_minutes * 60 # seconds in a work day
full_days = len(wd)
day1 = datetime1[:10]
day2 = datetime2[:10]
dt1 = pd.to_datetime(day1 + " " + str(worktiming[0]) + ":00")
dt2 = pd.to_datetime(day2 + " " + str(worktiming[1]) + ":00")
ex1, ex2 = 0, 0
if day1 in wd:
ex1 = max(pd.Timedelta(d1 - dt1).seconds, 0)
if day2 in wd:
ex2 = max(pd.Timedelta(dt2 - d2).seconds, 0)
total_seconds = full_days * day_seconds - ex1 - ex2
total_minutes = total_seconds / 60
total_hours = total_minutes / 60
return int(total_minutes)
print(getminutes(datetime1, datetime2))
Output: 2370
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))
What I am trying to do is see if date is in 1 week from currdate
from datetime import datetime, timedelta
import yagmail
year = datetime.now().year
month = datetime.now().month
day = datetime.now().day
currdate = '{}-{}-{}'.format(year, month, day)
currdate = datetime.strptime(currdate, '%Y-%m-%d')
date = '2018-04-01'
days = currdate - timedelta(int(date[-2:]))
days = str(days)
print(days)
if days[8:11] == '07':
yag = yagmail.SMTP("##########gmail.com", "######")
content = ['One Of Your Homework\'s Is Due In 1 Week!']
yag.send('###########gmail.com', 'Homework Due Soon!', content)
else:
print('It Isn\'t')
But it prints:
2018-04-07 00:00:00
It Isnt't
And I'm not sure why. Because days[8:11] is 07.
It is not 07. It's 07 (note the trailing space).
The following change will work:
if int(days[8:11]) == 7:
I'd create a function that you pass the date as a string. Something like this:
import datetime
def check_if_less_than_seven_days(x):
d = datetime.datetime.strptime(x, "%Y-%m-%d") # Add .date() if hour doesn't matter
now = datetime.datetime.now() # Add .date() if hour doesn't matter
return (d - now).days < 7
if check_if_less_than_seven_days("2018-04-18"):
print('Do something') # This will not print
if check_if_less_than_seven_days("2018-04-14"):
print('Do something') # This will print
Will print:
'Do something'
I suppose your first line when you initiate datetime.now() three times is just for testing purposes but dont do this as it could end up over different days (if you run this exactly at the milliseconds around midnight..) this will work better in that regard.
now = datetime.datetime.now()
year = now.year
month = now.month
day = now.day
Anyway, read up on datetime timedelta. Just make you logic around that.
https://docs.python.org/3/library/datetime.html#timedelta-objects
import datetime
test_date_string = "2018-04-10"
d = datetime.datetime.strptime(test_date_string, "%Y-%m-%d")
now = datetime.datetime.now()
delta = d - now
elif delta.days < 7:
print("You have less then 7 days to go")
For days[8:11] you get the following output
>>> days[8:11]
'08 '
So you should use days[8:10]=='07' in case you want to use the same method,as it wont have extra space at the end.
>>> days[8:10]
'08'
so you should use
if days[8:10] == '07':
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)