Requirement: I have to pass start_date and end_date to API and loop b/w range of dates
Example : Range of dates is start_date = '2022-05-23' and end_date ='2022-05-26'
So When I loop data from API, it should first start_date and end_date as below
start_date = '2022-05-23' and end_date ='2022-05-24'
start_date = '2022-05-24' and end_date ='2022-05-25'
start_date = '2022-05-25' and end_date ='2022-05-26'
start_date = '2022-05-26' and end_date ='2022-05-27'
start_date = '2022-05-27' and end_date ='2022-05-28'
start_date = '2022-05-28' and end_date ='2022-05-29'
Tried as below , was able to increment start_date , not sure how to increment end_date by 1 day of start_date
from datetime import datetime, timedelta
start_date = "2022-05-24"
end_date = "2022-05-29"
start_dt = datetime.strptime(start_date, "%Y-%m-%d")
end_dt = datetime.strptime(end_date, "%Y-%m-%d")
delta = timedelta(days=1)
while start_dt <= end_dt:
print(f"start_dt:{start_dt}")
print(f"end_dt:{end_dt}")
start_dt += delta
from datetime import datetime, timedelta
from datetime import date
start_date = "2022-05-24"
end_date = "2022-05-29"
start_dt = datetime.strptime(start_date, "%Y-%m-%d")
end_dt = datetime.strptime(end_date, "%Y-%m-%d")
gap=(end_dt-start_dt).days
print(gap)
end_dt=end_dt- timedelta(gap-1)
delta = timedelta(days=1)
for i in range(gap):
print(f"start_dt:{start_dt}")
print(f"end_dt:{end_dt}")
start_dt += delta
end_dt += delta
[...] not sure how to increment end_date by 1 day of start_date
temp_dt = start_dt + datetime.timedelta(days=1)
print(f"start_dt:{start_dt}")
print(f"end_dt:{temp_dt}")
This should work fine.
Related
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']
python get the quarterly dates from a date range
example :
start date = 01/04/2020
end date = 01/04/2021
Here I need to get the Quaternary dates from this date range.
Try:
start_date = "01/04/2020"
end_date = "01/04/2021"
pd.date_range(start_date, end_date, freq='Q')
DatetimeIndex(['2020-03-31', '2020-06-30', '2020-09-30', '2020-12-31'], dtype='datetime64[ns]', freq='Q-DEC')
pd.date_range(start date, end date, freq='3m').to_period('Q')
With pure Python:
import datetime
start_date_str = "01/04/2020"
end_date_str = "01/04/2021"
start_date = datetime.datetime.strptime(start_date_str, "%d/%m/%Y").date()
end_date = datetime.datetime.strptime(end_date_str, "%d/%m/%Y").date()
print(f"Quarters within {start_date_str} and {end_date_str}:")
start_of_quarter = start_date
while True:
far_future = start_of_quarter + datetime.timedelta(days=93)
start_of_next_quarter = far_future.replace(day=1)
end_of_quarter = start_of_next_quarter - datetime.timedelta(days=1)
if end_of_quarter > end_date:
break
print(f"\t{start_of_quarter:%d/%m/%Y} - {end_of_quarter:%d/%m/%Y}")
start_of_quarter = start_of_next_quarter
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)
how can i convert my string of date to a datetime.timedelta() in Python?
I have this code :
import datetime
date_select = '2011-12-1'
delta = datetime.timedelta(days=1)
target_date = date_select + delta
print target_date
thanks in advance ...
You wouldn't convert date_select to a timedelta, instead, you need a datetime object, which can be added to a timedelta to produce an updated datetime object:
from datetime import datetime, timedelta
date_select = datetime.strptime('2011-12-1', '%Y-%m-%d')
delta = timedelta(days=1)
target_date = date_select + delta
print target_date
Or, if you prefer, without the fancy from ... import ... import line:
import datetime # <- LOOK HERE, same as in your example
date_select = datetime.datetime.strptime('2011-12-1', '%Y-%m-%d')
delta = datetime.timedelta(days=1)
target_date = date_select + delta
print target_date
You use strptime to do this.
from datetime import datetime
target_date = datetime.strptime(date_select, '%Y-%m-%d')
from datetime import datetime, timedelta
date_select = '2011-12-1'
new_data = datetime.strptime(date_select, '%Y-%m-%d')
delta = timedelta(days=1)
target_date = date_select + delta
print target_date
You will get 2011-12-02 00:00:00; to strip off the '00:00:00' and get only the date, just add .date() to target_date
print target_date.date()
This should give you the only the date = 2011-12-02
How to get saturday and sunday dates from given date range.
for example :
start_date = 2011-09-01
end_date = 2011-09-15
Now it should give the out put
2011-09-03
2011-09-04
2011-09-10
2011-09-11
Any help really appreciate.
>>> import datetime
>>> start = datetime.datetime.strptime("2011-09-01", "%Y-%m-%d")
>>> end = datetime.datetime.strptime("2011-09-15", "%Y-%m-%d")
>>> while start <= end:
... if start.weekday() in (5, 6):
... print start.strftime("%Y-%m-%d")
... start += datetime.timedelta(days=1)
...
2011-09-03
2011-09-04
2011-09-10
2011-09-11
>>>
Well, I think this should work:
from datetime import datetime, timedelta
def daterange(start_date, end_date):
for n in range((end_date - start_date).days):
yield start_date + timedelta(n)
start_date = '2011-09-01'
end_date = '2011-09-15'
format = '%Y-%m-%d'
start_date_object = datetime.strptime(start_date, format)
end_date_object = datetime.strptime(end_date, format)
for day in daterange(start_date_object, end_date_object):
if day.weekday() in [5, 6]:
print day.strftime(format)