Time of Day Calculation Python - python

I have a script that downloads files from a site each day. There is one file per day and a new file is added 16:00. The file names use year, month date in title of file so I use that to know which files to get.
I am trying write in my script that if the current time today is before 4pm then find:
year = 2020
month = 4
day = 15
But if it is past 4pm then find:
year = 2020
month = 4
day = 16
I have tried:
timerightnow = datetime.now()
today4pm = timerightnow.replace(hour=16, minute=0, second=0, microsecond=0)
But then doing timerightnow < today4pm gives me a syntax error?
Any ideas would be great!
Thanks

For those wondering the solution:
timerightnow = datetime.now()
today4pm = timerightnow.replace(hour=16, minute=0, second=0, microsecond=0)
if timerightnow < today4pm:
year = timerightnow.year
month = timerightnow.month
day = timerightnow.day -1
else:
year = timerightnow.year
month = timerightnow.month
day = timerightnow.day

Related

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))

How to convert a string of dates to a date object?

I'm doing a chatbot to book rooms. I've created a function to check if the room asked is free while looking in the database. At some point I try to convert the entry starting and ending meeting hour to a tupple with from_pendulum_to_tupple(day_startinghour) with day_startinghour beeing for instance 2019-04-18T14:00:00+00:00
def from_pendulum_to_tupple(date):
print("date: ")
print(date)
print("type : " + str(type(date)))
year = date.year
month = date.month
day = date.day
hour = date.hour
minute = date.minute
return (year, month, day, hour, minute)
Yet I have an AttributeError: str object has no attribute year. Indeed, the error message is:
File
"C:\Users\antoi\Documents\Programming\Nathalie\18_2_2019\starter-pack-rasa-stack\actions.py",
line 43, in run
booking_answer = make_a_booking(name_room, day, hour_start, duration)
File "C:\Users\antoi\Documents\Programming\Nathalie\18_2_2019\starter-pack-rasa-stack\booking.py",
line 94, in make_a_booking
room_available = is_the_room_available(name_room, day_only, pendulum_combined_day_and_hour_start,
pendulum_combined_day_and_hour_end, cnx)
File "C:\Users\antoi\Documents\Programming\Nathalie\18_2_2019\starter-pack-rasa-stack\booking.py",
line 52, in
is_the_room_available
starting_hour_list.append(from_pendulum_to_tupple(start_time))
File "C:\Users\antoi\Documents\Programming\Nathalie\18_2_2019\starter-pack-rasa-stack\booking.py",
line 14, in
from_pendulum_to_tupple
year = date.year
AttributeError: 'str' object has no attribute 'year'
127.0.0.1 - - [2019-04-17 16:42:01] "POST /webhook HTTP/1.1" 500 412 1.050171
day_startinghour was created with make_a_booking which takes room, a day and an hour before calling for the above function to know if the room is used on the times we want to book it:
def make_a_booking(name_room, day, hour_start, duration):
print(name_room, day, hour_start, duration)
# connect to the localhost database
cnx = mysql.connector.connect(password='MySQL.2019', user="root", database="alex")
#day_only : get the parsed date
day_only = str(dateparser.parse(day).date())
# parse the hour in string inputed by the user and convert it the a pendulum object
hour_start_parsed = dateutil.parser.parse(hour_start, fuzzy_with_tokens=True)
pendulum_combined_day_and_hour_start = pendulum.parse(str(day_only) + " " + hour_start, strict=False)
# convert the duration in string inputed by the user and to seconds then in minutes
duration_in_seconds = convert_time(duration)
duration_in_minutes = duration_in_seconds / 60
# add the duration_in_minutes to the starting hour to get the hour start pendulum object
pendulum_combined_day_and_hour_end = pendulum_combined_day_and_hour_start.add(minutes = duration_in_minutes)
#print(pendulum_combined_day_and_hour_end)
# check if the room is available
room_available = is_the_room_available(name_room, day_only, pendulum_combined_day_and_hour_start, pendulum_combined_day_and_hour_end, cnx)
Using dparser:
import dateutil.parser as dparser
def from_pendulum_to_tupple(date):
print("date: {}".format(date))
date = dparser.parse(date,fuzzy=True)
year = date.year
month = date.month
day = date.day
hour = date.hour
minute = date.minute
return (year, month, day, hour, minute)
s = '2019-04-18T14:00:00+00:00'
print(from_pendulum_to_tupple(s))
OUTPUT:
date: 2019-04-18T14:00:00+00:00
(2019, 4, 18, 14, 0)

Getting dates in python between a past datestamp and the present

Language Python
I am wondering if anyone can help me print out some dates.
i cam trying to create a loop in which i pass in a date say 01/1/2017 and the loop will then output the first and last day in every month between then and the present day.
Example
01/01/2017
31/01/2017
01/02/2017
28/02/2017
etc
Any help will be appreciated
Hope this will help,
Code:
from datetime import date
from dateutil.relativedelta import relativedelta
from calendar import monthrange
d1 = date(2018, 2, 26)
d2 = date.today()
def print_month_day_range(date):
first_day = date.replace(day = 1)
last_day = date.replace(day = monthrange(date.year, date.month)[1])
print (first_day.strftime("%d/%m/%Y"))
print (last_day.strftime("%d/%m/%Y"))
print_month_day_range(d1)
while (d1 < d2):
d1 = d1 + relativedelta(months=1)
print_month_day_range(d1)
Output:
01/02/2018
28/02/2018
01/03/2018
31/03/2018
...
01/07/2018
31/07/2018
you can use calendar module. Below is the code:
import datetime
from calendar import monthrange
strt_date = '01/1/2017'
iter_year = datetime.datetime.strptime(strt_date, '%m/%d/%Y').year
iter_month = datetime.datetime.strptime(strt_date, '%m/%d/%Y').month
cur_year = datetime.datetime.today().year
cur_month = datetime.datetime.today().month
while cur_year > iter_year or (cur_year == iter_year and iter_month <= cur_month):
number_of_days_in_month = monthrange(iter_year, iter_month)[1]
print '/'.join([str(iter_month) , '01', str(iter_year)])
print '/'.join([str(iter_month), str(number_of_days_in_month), str(iter_year)])
if iter_month == 12:
iter_year += 1
iter_month = 1
else:
iter_month += 1
this could work, as long as the first date you give is always the first of the month
from datetime import datetime
from datetime import timedelta
date_string = '01/01/2017'
date = datetime.strptime(date_string, '%d/%m/%Y').date()
today = datetime.now().date()
months = range(1,13)
years = range(date.year, today.year + 1)
for y in years:
for m in months:
new_date = date.replace(month=m, year=y)
last_day = new_date - timedelta(days=1)
if (date < new_date) & (new_date <= today):
print last_day.strftime('%d/%m/%Y')
print new_date.strftime('%d/%m/%Y')
elif (date <= new_date) & (new_date <= today):
print new_date.strftime('%d/%m/%Y')
This code would print the first and last days of all months in a year.
Maybe add some logic to iterate through the years
import datetime
def first_day_of_month(any_day):
first_month = any_day.replace(day=1)
return first_month
def last_day_of_month(any_day):
next_month = any_day.replace(day=28) + datetime.timedelta(days=4)
return next_month - datetime.timedelta(days=next_month.day)
for month in range(1, 13):
print first_day_of_month(datetime.date(2017, month, 1))
print last_day_of_month(datetime.date(2017, month, 1))

Count summer days between two dates

I want to count summer days between two dates. Summer is May first to August last.
This will count all days:
import datetime
startdate=datetime.datetime(2015,1,1)
enddate=datetime.datetime(2016,6,1)
delta=enddate-startdate
print delta.days
>>517
But how can only count the passed summer days?
You could define a generator to iterate over every date between startdate and enddate, define a function to check if a date represents a summer day and use sum to count the summer days:
import datetime
startdate = datetime.datetime(2015,1,1)
enddate = datetime.datetime(2016,6,1)
all_dates = (startdate + datetime.timedelta(days=x) for x in range(0, (enddate-startdate).days))
def is_summer_day(date):
return 5 <= date.month <= 8
print(sum(1 for date in all_dates if is_summer_day(date)))
# 154
Thanks to the generator, you don't need to create a huge list in memory with every day between startdate and enddate.
This iteration still considers every single day, even if it's not needed. For very large gaps, you could use the fact that every complete year has 123 summer days according to your definition.
You can create a few functions to count how many summer days you have between two days:
from datetime import date
def get_summer_start(year):
return date(year, 5, 1)
def get_summer_end(year):
return date(year, 8, 31)
def get_start_date(date, year):
return max(date, get_summer_start(year))
def get_end_date(date, year):
return min(date, get_summer_end(year))
def count_summer_days(date1, date2):
date1_year = date1.year
date2_year = date2.year
if date1_year == date2_year:
s = get_start_date(date1, date1_year)
e = get_end_date(date2, date1_year)
return (e - s).days
else:
s1 = max(date1, get_summer_start(date1_year))
e1 = get_summer_end(date1_year)
first_year = max(0,(e1 -s1).days)
s1 = get_summer_start(date2_year)
e1 = min(date2, get_summer_end(date2_year))
last_year = max(0,(e2 -s2).days)
other_years = date2_year - date1_year - 1
summer_days_per_year = (get_summer_end(date1_year) - get_summer_start(date1_year)).days
return first_year + last_year + (other_years * summer_days_per_year)
date1 = date(2015,1,1)
date2 = date(2016,6,1)
print count_summer_days(date1, date2)
Here is a better solution for large periods:
first_summer_day = (5,1)
last_summer_day = (8,31)
from datetime import date
startdate = date(2015,1,1)
enddate = date(2016,6,1)
# make sure that startdate > endate
if startdate > enddate:
startdate, endate = endate, startdate
def iter_yearly_summer_days(startdate, enddate):
for year in range(startdate.year, enddate.year+1):
start_period = startdate if year == startdate.year else date(year, 1, 1)
end_period = enddate if year == enddate.year else date(year, 12, 31)
year_first_summer_day = date(year, *first_summer_day)
year_last_summer_day = date(year, *last_summer_day)
summer_days_that_year = (min(year_last_summer_day, end_period) - max(year_first_summer_day, start_period)).days
print('year {} had {} days of summer'.format(year, summer_days_that_year))
yield summer_days_that_year
print(sum(iter_yearly_summer_days(startdate, enddate)))

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