Reputation: 81
I have a weekly date as a range and I want to calculate missing dates between that period. The date range is starting from 1992, so can't put it manually. The date data is available in excel in the below format.
1992-12-18
1992-12-25
1993-01-08
when I run the below code by putting the first two date as start and end, I got the correct result.
I have tried to convert this date as pd.to_datetime(dates[0]).dt.date also pd.to_datetime(dates[0]).dt.normalize()
import datetime
import pandas as pd
data = pd.read_excel("-------------------",header=None)
for t in data[0]:
start = datetime.datetime.strptime(str(t), %Y-%m-%d %H:%M:%S")
end = datetime.datetime.strptime(str(t+1), %Y-%m-%d %H:%M:%S")
date = (start + datetime.timedelta(days = x) for x in range(0,(end-
start).days))
for data_ob in date:
print(data_ob.strftime("%Y-%m-%d"))
ValueError: cannot add integral value to Timestamp without freq
Upvotes: 1
Views: 602
Reputation: 9257
Here is a solution to get all the missing dates between two ranges of dates using datetime
and calendar
modules, without returning duplicate dates and also without returning any date found in the input date's list:
from datetime import datetime
from calendar import monthrange
from pprint import pprint
def get_missing_dates(dates: list) -> list:
"""Find missing dates"""
out = set()
for date in dates:
_date = datetime.strptime(date, '%Y-%m-%d')
year, month, day = _date.year, _date.month, _date.day
for missing in range(*monthrange(year, month)):
to_add = datetime(year, month, missing).strftime('%Y-%m-%d')
if date not in out and not day == missing and to_add not in dates:
out.add(to_add)
return sorted(list(out))
dates = ['1992-12-18', '1992-12-25']
missing_dates = get_missing_dates(dates)
pprint(missing_dates)
output:
['1992-12-01',
'1992-12-02',
'1992-12-03',
'1992-12-04',
'1992-12-05',
'1992-12-06',
'1992-12-07',
'1992-12-08',
'1992-12-09',
'1992-12-10',
'1992-12-11',
'1992-12-12',
'1992-12-13',
'1992-12-14',
'1992-12-15',
'1992-12-16',
'1992-12-17',
'1992-12-19',
'1992-12-20',
'1992-12-21',
'1992-12-22',
'1992-12-23',
'1992-12-24',
'1992-12-26',
'1992-12-27',
'1992-12-28',
'1992-12-29',
'1992-12-30']
Upvotes: 2