0

I have a date variable calls today_date as below. I need to get the 1st calendar day of the current and next month. In my case, today_date is 4/17/2021, I need to create two more variables calls first_day_current which should be 4/1/2021, and first_day_next which should be 5/1/2021. Any suggestions are greatly appreciated

import datetime as dt    
today_date
'2021-04-17'
user032020
  • 406
  • 2
  • 13
  • 1
    Does this answer your question? [How to get the last day of the month?](https://stackoverflow.com/questions/42950/how-to-get-the-last-day-of-the-month) – itprorh66 Apr 20 '21 at 13:43
  • 1
    I believe this will answer your questions see [How to get the last day of the month?](https://stackoverflow.com/questions/42950/how-to-get-the-last-day-of-the-month) – itprorh66 Apr 20 '21 at 13:44
  • 1
    first day of the month is easy, just replace the day with 1. first day of *next* month: add a [relativedelta](https://dateutil.readthedocs.io/en/stable/relativedelta.html) of one month and *then* replace day with 1. – FObersteiner Apr 20 '21 at 14:03
  • Thanks @itprorh66, I try to avoid hard coding like manually input the date in the month range. The goal is to get all the dates based on the global variable/parameter in the program, but thanks for the ideas. – user032020 Apr 21 '21 at 19:09
  • Thanks @MrFuppes for the ideas. Really appreciated it. – user032020 Apr 21 '21 at 19:11

2 Answers2

1

Getting just the first date of a month is quite simple - since it equals 1 all the time. You can even do this without needing the datetime module to simplify calculations for you, if today_date is always a string "Year-Month-Day" (or any consistent format - parse it accordingly)

today_date = '2021-04-17'
y, m, d = today_date.split('-')
first_day_current = f"{y}-{m}-01"
y, m = int(y), int(m)
first_day_next = f"{y+(m==12)}-{m%12+1}-01"

If you want to use datetime.date(), then you'll anyway have to convert the string to (year, month, date) ints to give as arguments (or do today_date = datetime.date.today(). Then .replace(day=1) to get first_day_current. datetime.timedelta can't add months (only upto weeks), so you'll need to use other libraries for this. But it's more imports and calculations to do the same thing in effect.

gdcodes
  • 266
  • 2
  • 10
0

I found out pd.offsets could accomplish this task as below -

import datetime as dt 
import pandas as pd

today_date #'2021-04-17' this is a variable that is being created in the program
first_day_current = today_date.replace(day=1) # this will be 2021-04-01
next_month = first_day_current + pd.offsets.MonthBegin(n=1)
first_day_next = next_month.strftime('%Y-%m-%d') # this will be 2021-05-01
user032020
  • 406
  • 2
  • 13