1

I am trying to automate a code. I would like to have the code pull data starting at the beginning of the month to end of the previous day. Currently I am using the following command to get the enddate:

dateEnd = pd.to_datetime('today')

How do tell the code, based on what today is to go back to the beginning of the month? AND, how do I tell the code if its the first of the month to return the previous months data?

For a bonus, once I have the start and end date, how do return find the number of days in the month? I have tried this command, but it does not want to work on a single date.

startTime_date.dt.daysinmonth
Zoe
  • 27,060
  • 21
  • 118
  • 148
getaglow
  • 343
  • 4
  • 15
  • 2
    Re: "for a bonus", SO isn't a quiz. Can you ask one *specific* question and show us your latest attempts? – jpp Oct 10 '18 at 15:46
  • Here is how to find the first day of the month: https://stackoverflow.com/questions/37396329/finding-first-day-of-the-month-in-python – Nathan Clement Oct 10 '18 at 15:49
  • Here is how to find the last day of the month: https://stackoverflow.com/questions/42950/get-last-day-of-the-month-in-python – Nathan Clement Oct 10 '18 at 15:49
  • You can use an "if" statement to go to the previous month if today is the first day of the month. – Nathan Clement Oct 10 '18 at 15:50

1 Answers1

0

This will give you the wanted dates:

import datetime

end = datetime.date.today() - datetime.timedelta(1)
start = end.replace(day=1)
daysInMonth = (datetime.date(start.year, start.month + 1, 1) - datetime.timedelta(1)).day

start
#2018-10-01

end
#2018-10-09

daysInMonth
#31
zipa
  • 27,316
  • 6
  • 40
  • 58