So I can generate random days in a given start-end date relationship, but, if the date happens to be a weekend - currently all I can get working is to print to the user 'it is a weekend'. What I would like to do is, if the random day IS a weekend, rerun the function so the user does not have to manually. Basically - only print out weekdays - currently, if the random day is a weekend, it prints a blank space or None value. Only return/print weekdays is the main goal.
Here is the code so far:
from datetime import datetime, timedelta
from random import randrange
def random_date(start, end):
delta = end - start
random_day = randrange(delta.days)
myresult = start + timedelta(days=random_day)
return myresult
d1 = datetime.strptime('9/1/2018', '%m/%d/%Y')
d2 = datetime.strptime('9/30/2018', '%m/%d/%Y')
myresult = random_date(d1, d2)
if myresult.weekday() not in (5, 6):
print myresult.strftime('%m-%d-%Y')
else:
print "hit a weekend"
An option:
def random_weekday(start, end):
date = None
while (not date or date.weekday() in (5, 6)):
days = randrange((end - start).days)
date = start + timedelta(days=days)
return date
start = datetime.strptime('9/1/2018', '%m/%d/%Y')
end = datetime.strptime('9/30/2018', '%m/%d/%Y')
for i in range(20):
print(random_weekday(start, end).strftime('%m-%d-%Y'))
So, you need a while-loop to keep getting dates until you get one that's not a weekend, like this:
from datetime import datetime
from random import randrange
from datetime import timedelta
def random_date(start, end):
delta = end - start
random_day = randrange(delta.days)
myresult = start + timedelta(days=random_day)
return myresult
while True:
d1 = datetime.strptime('9/1/2018', '%m/%d/%Y')
d2 = datetime.strptime('9/30/2018', '%m/%d/%Y')
myresult = random_date(d1, d2)
if myresult.weekday() not in (5,6):
break
print myresult.strftime('%m-%d-%Y')
Related
recent_cases is supposed to sum the new covid cases in last 10 days for a given location
somehow my code prints None. i cant find the problem
import json
import pandas as pd
import plotly.express as ex
from datetime import *
from datetime import timedelta
class Covid:
dt = timedelta(days=1)
ten_days = timedelta(days=10)
covid_data = pd.read_excel("owid-covid-data.xlsx", usecols="C:F,H,I")
def recent_cases(self, cntry):
today = datetime.today()
temp = today - self.ten_days # 10 days before today
sum_of_cases = 0
for ind in self.covid_data.index:
if temp <= today:
if (self.covid_data["date"][ind] == temp) and (self.covid_data['location'][ind] == cntry):
# if 'date' is temp and 'location' is the location input, sum new cases
sum_of_cases = sum_of_cases + int(self.covid_data["new_cases"][ind])
temp = temp + self.dt # move to the next day
else: # if temp passed today, all past ten days cases are summed
break
if __name__ == '__main__':
c = Covid()
print(c.recent_cases('Italy'))
Can I get some help to create a list of days and months in the folowing format:
collection = ['2108', '2109', '2110', '2111', '2112', '2201']
I am trying in this way:
def make_collections(start_date: Date, end_date: Date):
result = []
date = start_date
while True:
if start_date >= end_date:
return result
date = date.strftime('%y%m%d%H%M%S')
result.append(date[:4])
date = (date.strptime(date, '%y%m%d%H%M%S')) + timedelta(days=1)
# test = MakeDataFrame()
# test.run()
if __name__ == '__main__':
start = datetime.now() - timedelta(days=365)
print(make_collections(start, datetime.now()))
But it doesn't work.
I want to give a start date and end date as an argument in function and make a list as I mentioned above with year and month.
Can I get some help to make a a simple function with start and end date as an arguments?
Thanks
I revised your code a little bit, so that the code will print what you expected. I used dateutil.relativedelta module because timedelta provide only day-based delta. dateutil.relativedelta support to calculate month and year differences.
from datetime import datetime, timedelta
from dateutil.relativedelta import relativedelta
def make_collections(start_date, end_date):
result = []
while start_date <= end_date:
result.append(str(start_date.year)[2:] + str(start_date.month).zfill(2))
start_date += relativedelta(months=1)
return result
if __name__ == '__main__':
start = datetime.now() - timedelta(days=365)
print(make_collections(start, datetime.now()))
#['2101', '2102', '2103', '2104', '2105', '2106', '2107', '2108', '2109', '2110', '2111', '2112', '2201']
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)
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))
I'm trying to work out a way to make a new variable AUTOMATIC_END_TIME based on adding the minimum amount of time onto the start time but I can't figure out the way to allow START_TIME to be turned into a time that can then have time added onto it.
So far my script has the following:
from time import sleep
from datetime import datetime, timedelta
START_TIME = "19:18"
END_TIME = "19:25"
LOGA = ["one", "two"]
TIME_DIFFERENCE = datetime.strptime(END_TIME, "%H:%M") - datetime.strptime(START_TIME, "%H:%M")
TIME_DIFFERENCE = TIME_DIFFERENCE.seconds
if len(LOGA) * (60 * (5 + 1)) >= TIME_DIFFERENCE:
print "Show minimum end time"
AUTOMATIC_END_TIME = "" # Should come out as 19:30
The current script shouldn't change at all except for AUTOMATIC_END_TIME which should be START_TIME + (60 * (5 + 1) It should come out as 19:30
>>> (datetime.strptime(START_TIME, "%H:%M") + timedelta(minutes=12)).strftime('%H:%M')
'19:30'
from time import sleep
from datetime import datetime, timedelta
START_TIME = "19:18"
END_TIME = "19:25"
LOGA = ["one", "two"]
TIME_DIFFERENCE = datetime.strptime(END_TIME, "%H:%M") - datetime.strptime(START_TIME, "%H:%M")
TIME_DIFFERENCE = TIME_DIFFERENCE.seconds
if len(LOGA) * (60 * (5 + 1)) >= TIME_DIFFERENCE:
print "Show minimum end time"
AUTOMATIC_END_TIME = (datetime.strptime(START_TIME, "%H:%M") + timedelta(minutes=12)).strftime('%H:%M')
print AUTOMATIC_END_TIME