Datetime format when adding time durations - python

time_1 = datetime.timedelta(hours = hours_1, minutes = minutes_1, seconds = seconds_1)
time_2 = datetime.timedelta(hours = hours_2, minutes = minutes_2, seconds = seconds_2)
when added it gives the answer in days and hours but I really just want the total number of hours.

This should help.
import datetime
time_1 = datetime.timedelta(hours = 10, minutes = 2, seconds = 5)
time_2 = datetime.timedelta(hours = 30, minutes = 5, seconds = 7)
print(time_1 + time_2)
print(((time_1 + time_2).total_seconds()/60)/60)
Output:
1 day, 16:07:12
40.12

Related

Generate random start and end date between a date range

I have written some utility functions to generate a random date start and end date range between a specified date range which will return both the est and the utc times. However I'm not getting consistent results. Sometimes the result is offset by 4 hrs between UTC and EST and sometimes its offset by 5 hrs. Can anyone help whats wrong with the code?
def generate_random_dt_btn_two_dates(start_date,end_date, line_item):
time_between_dates = end_date - start_date
days_between_dates = time_between_dates.days
if line_item:
days_between_dates = round(days_between_dates/2)
if days_between_dates < 1 or days_between_dates is None:
days_between_dates = 1
random_number_of_days = random.randrange(days_between_dates)
utc_date = start_date + timedelta(days=random_number_of_days, hours = random.randrange(24), minutes = random.randrange(60),
seconds = random.randrange(60), microseconds= random.randrange(1000), milliseconds= random.randrange(1000))
est_now = utc_date.astimezone(pytz.timezone("America/New_York"))
return {"utc_date":utc_date, "est_date":est_now}
def generate_random_dt_range(start_date = datetime(2022, 1, 1, 15, 16, 17, 345, tzinfo=timezone.utc),
end_date = datetime(2022, 7, 30, 15, 16, 17, 345, tzinfo=timezone.utc),
line_item = False
):
random_start_date = generate_random_dt_btn_two_dates(start_date , end_date, line_item)
random_end_date = generate_random_dt_btn_two_dates(start_date = random_start_date["utc_date"], end_date = end_date, line_item = line_item)
return {"start_date": random_start_date, "end_date" : random_end_date}
campaign_dates = generate_random_dt_range()
c_end_date = campaign_dates.get("end_date").get("est_date").strftime('%Y-%m-%dT%H:%M:%S.%fZ')
c_start_date = campaign_dates.get("start_date").get("est_date").strftime('%Y-%m-%dT%H:%M:%S.%fZ')
c_end_date_utc = campaign_dates.get("end_date").get("utc_date").strftime('%Y-%m-%dT%H:%M:%S.%fZ')
c_start_date_utc = campaign_dates.get("start_date").get("utc_date").strftime('%Y-%m-%dT%H:%M:%S.%fZ')
print("start_date:", c_start_date,c_start_date_utc)
print("end_date:",c_end_date,c_end_date_utc )

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)

How do I find what the date will be next Sunday 12 am from now and then add 10 hours to it

I have this code
today = datetime.now().date()
# prints: 2022/1/14
rd = REL.relativedelta(days=1, weekday=REL.SU)
nextSunday = today + rd
#prints : 2022/1/16
How do i add 10 hours to the date so i can get a variable nextSunday_10am that i can substract to the current time
difference = nextSunday_10am - today
and schedule what I need to do
You can do the same thing as suggested by #Dani3le_ more directly with the following:
def getSundayTime(tme: datetime.date) -> datetime:
nxt_sndy = tme + timedelta(days= 6 - tme.weekday())
return datetime.combine(nxt_sndy, datetime.strptime('10:00', '%H:%M').time())
This will compute calculate the next Sunday and set time to 10:00
You can add hours to a DateTime by using datetime.timedelta().
nextSunday += datetime.timedelta(hours=10)
For example:
import datetime
today = datetime.datetime.today()
print("Today is "+str(today))
while today.weekday()+1 != 6: #0 = "Monday", 1 = "Tuesday"...
today += datetime.timedelta(1)
nextSunday = today + datetime.timedelta(hours=10)
print("Next sunday +10hrs will be "+str(nextSunday))

Making time schedule by adding time based on user input

I am new to coding! I am trying to make a baking timetable based on when I start the mix. Now, the minutes are showing up as '09:0' and '10:75' depending on input. I cannot figure out how to format the output. I appreciate everyone's help!
from datetime import time
start = input ("What time are you mixing, in format of HH:MM \n")
h,m = map (int, start.split(":"))
print(f"I am starting at {h:02d}:{m:02d}")
add_salt = h + 1, m + 30
first_turn = h + 2, m + 0
second_turn = h + 2, m + 30
bake = h + 4, m + 15
print(f"{add_salt[0]}:{add_salt[1]} >>> Add salt")
print(f"{first_turn[0]}:{first_turn[1]} >>> Turn #1")
print(f"{second_turn[0]}:{second_turn[1]} >>> Turn #2")
print(f"{bake[0]}:{bake[1]} >>> Time to bake!")
Because you are already using datetime library, you might as well could use datetime.time format, following on this and this.
from datetime import datetime, timedelta
start = datetime.now()
add_salt = start + timedelta(hours = 1, minutes = 30) # h + 1, m + 30
first_turn = start + timedelta(hours = 2) # h + 2, m + 0
second_turn = start + timedelta(hours = 2, minutes = 30) # h + 2, m + 30
bake = start + timedelta(hours = 4, minutes = 15) # h + 4, m + 15
print(f"{add_salt.strftime('%H:%M')} >>> Add salt")
print(f"{first_turn.strftime('%H:%M')} >>> Turn #1")
print(f"{second_turn.strftime('%H:%M')} >>> Turn #2")
print(f"{bake.strftime('%H:%M')} >>> Time to bake!")
# out
# 19:17
# 20:47 >>> Add salt
# 21:17 >>> Turn #1
# 21:47 >>> Turn #2
# 23:32 >>> Time to bake!
This is what I did after reading Felipe's answer, and I am happy about it! Honestly, I only understand probably 20% of what is up, but hey, it works! Many, many thanks! Wish you can have my bread!
from datetime import time, datetime, timedelta
start = input ("What time are you mixing, in format of HH:MM \n")
h,m = map (int, start.split(":"))
print(f"I am starting at {h:02d}:{m:02d}")
baseline = datetime.strptime(start, "%H:%M")
add_salt = baseline + timedelta(hours = 1, minutes = 30)
first_turn = add_salt + timedelta(minutes = 30)
second_turn = first_turn + timedelta(minutes = 30)
bake = second_turn + timedelta(hours = 1, minutes = 45)
print(f"{add_salt.strftime('%H:%M')} >>> Add salt")
print(f"{first_turn.strftime('%H:%M')} >>> Turn #1")
print(f"{second_turn.strftime('%H:%M')} >>> Turn #2")
print(f"{bake.strftime('%H:%M')} >>> Time to bake!")

AttributeError: 'str' object has no attribute 'sleep'

I am getting AttributeError: 'str' object has no attribute 'sleep' as specified in the title of this question and I cannot figure out why it is throwing that error message.
Countdown Timer.py
import time, datetime
Year = 2020
Month = 12
Day = 24
Hour = 23
Minute = 18
Second = 50
while True:
Datetime = datetime.datetime(Year, Month, Day, Hour, Minute, Second)
diff = Datetime - datetime.datetime.now()
diff = str(diff)
days, not_useful, time = diff.split()
Day1 = days + " " + "Day" # Day
print(Day1)
time.sleep(1)
That's because you locally erased the variable time that contained the module with a string. Here is a correct code:
import time, datetime
Year = 2020
Month = 12
Day = 24
Hour = 23
Minute = 18
Second = 50
while True:
Datetime = datetime.datetime(Year, Month, Day, Hour, Minute, Second)
diff = Datetime - datetime.datetime.now()
diff = str(diff)
days, not_useful, time_str = diff.split()
Day1 = days + " " + "Day" # Day
print(Day1)
time.sleep(1)
days, not_useful, time = diff.split()
here you will have 'time' as string. change verb name...
It's because you are using Time as a variable in your code:
time = diff.split()
and the above line is locally overwriting the variable timein the time-module.
Try using a different variable:
time_1 = diff.split()

Categories