Getting dates in python between a past datestamp and the present - python

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

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 replace the day in a date with another date?

I'm trying to replace the day in my if statement for my date but I keep getting this output for my year.
05/15/5 besides 05/15/2020 . Code is below:
today_date = datetime.datetime.now()
date = today_date.date()
formatted_date = datetime.date.strftime(date, "%m/%d/%Y")
mmonth = date.month
myear = date.year
mdate = date.day
if mdate < 7:
m0weekend = formatted_date.replace(str(myear),str(mmonth),1)
else:
m0weekend = formatted_date.replace(str(myear),str(mmonth),15)
it's easier to replace the day before converting to a string:
date = date.replace(day=1)
or, in your case:
if mdate < 7:
m0weekend = date.replace(day=1)
else:
m0weekend = date.replace(day=15)
formatted_date is actually a string.
You are using the str.replace() method not the datetime.date.replace() method.
import datetime
today_date = datetime.datetime.now()
pre_formatted_date = today_date.date()
mmonth = pre_formatted_date.month
myear = pre_formatted_date.year
mdate = pre_formatted_date.day
if mdate < 7:
pre_formatted_date = pre_formatted_date.replace(day=1)
else:
pre_formatted_date = pre_formatted_date.replace(day=15)
print(pre_formatted_date)
formatted_date = pre_formatted_date.strftime("%m/%d/%Y")
print(formatted_date)
Which has the following output:
2020-05-15
05/15/2020
You might get today datetime.date directly from datetime rather than creating datetime.datetime and converting to date. After you have today you might create needed datetime.date and turn it into str, i.e.:
import datetime
today = datetime.date.today()
date = datetime.date(today.year, today.month, 1 if today.day < 7 else 15)
formatted_date = datetime.date.strftime(date, "%m/%d/%Y")
print(formatted_date) # 05/15/2020

How to make a count for each day passed from start date in python

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)

calculate the months between two dates

I need to calculate the months between two dates. I know it can be easy but I have a code and I can not complete it.
start_date=fields.Date(string="Startdate", requiered=True)
end_date=fields.Date(string="End_date", requiered=True)
duration=fields.Char(string="Duration", computer="_duration")
#api.multi
#api.depends('start_date','end_date')
def _duration(self):
if self.start_date and self.end_date:
start_dt = fields.Datetime.from_string(self.start_date)
finish_dt = fields.Datetime.from_string(self.end_date)
difference = relativedelta(finish_dt, start_dt)
month = difference.month
Try using this code
from datetime import datetime
def diff_month(d1, d2):
return (d1.year - d2.year) * 12 + d1.month - d2.month
or
from datetime import datetime
from dateutil import relativedelta
def get_months(d1, d2):
date1 = datetime.strptime(str(d1), '%Y-%m-%d')
date2 = datetime.strptime(str(d2), '%Y-%m-%d')
print (date2, date1)
r = relativedelta.relativedelta(date2, date1)
months = r.months + 12 * r.years
if r.days > 0:
months += 1
return months
month = get_months('2018-08-13','2019-06-30')
print(month)
Try this code
from datetime import datetime
from dateutil import relativedelta
date1 = datetime.strptime(str('2019-03-01'), '%Y-%m-%d')
date2 = datetime.strptime(str('2019-07-01'), '%Y-%m-%d')
r = relativedelta.relativedelta(date2, date1)
print(r.months)

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

Categories