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()
Related
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)
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))
I'm looking for a way to count each day passed from a start date in python. So if the start date was 21/02/2020 and count equals to 0, when the next day starts count should increment by 1.
Edit: After using Rusty's code I am able to show you a minimal reproducible example.
import datetime
start = datetime.datetime.strptime(input("Choose a start date (mm/dd/yyyy): "), '%m/%d/%Y')
current = datetime.datetime.now()
delta = current - start
count = delta.days
print(count)
import datetime
import time
count = 0
# "...from today..."
today = datetime.datetime.today()
# "...to infinity..."
while True:
now = datetime.datetime.today()
# "...as soon as the next day starts..."
if today.day != now.day:
# "...it would increment count by 1..."
count = count + 1
print(count)
today = now
time.sleep(1)
import datetime
today = datetime.datetime.strptime('03/21/2020', '%m/%d/%Y')
tomorrow = datetime.datetime.strptime('03/22/2020', '%m/%d/%Y')
next_saturday = datetime.datetime.strptime('03/28/2020', '%m/%d/%Y')
delta = tomorrow - today
count = delta.days
print(count)
delta = next_saturday - today
count = delta.days
print(count)
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)
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))