Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Date fixed but variable month and year in python

I have below code:

from datetime import date, datetime, timedelta
from dateutil.relativedelta import relativedelta

c0 = date.today()
c1 = c0 - relativedelta(months=1)
c2 = c0 - relativedelta(months=2)
c3 = c0 - relativedelta(months=3)
c4 = c0 - relativedelta(months=4)
c5 = c0 - relativedelta(months=5)

Now date today is 2023/06/14, however what I am trying to achieve is that no matter what date it is, I should get 16 as day, and actual current month and year.

I have tried adding int to current date but since current date is not fixed, I am not able to get 16 as day.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Please suggest a way where I can convert below to a date:

day = 16
month = datetime.now().month
year = datetime.now().year
date = year/month/day

>Solution :

Use .replace() (on date, datetime) to edit the day component:

>>> import datetime
>>> datetime.datetime.now().replace(day=16)
datetime.datetime(2023, 6, 16, 8, 35, 18, 558127)
>>> datetime.date.today().replace(day=16)
datetime.date(2023, 6, 16)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading