1

I use datetime, i have:

delta = ((datetime.date.today() + datetime.timedelta(days=1)) - datetime.timedelta(???)).isoformat()

I need replace ??? with day to end of the month.

How to do it?

Nips
  • 13,162
  • 23
  • 65
  • 103

3 Answers3

5

To compute the end-of-the-current-month date, take the first of the current month, add 1 month and subtract 1 day. For example, for 28 September, you'll end up with

1 September + 1 month = 1 October
1 October - 1 day = 30 September.
Aleks G
  • 56,435
  • 29
  • 168
  • 265
3
import datetime

d = datetime.date(2013,12,8)

last_day = datetime.date(d.year, (d.month+1)%12, 1) - datetime.timedelta(1,0,0)
Stefano Altieri
  • 4,550
  • 1
  • 24
  • 41
rocksportrocker
  • 7,251
  • 2
  • 31
  • 48
  • Author/editor didn't notice this breaks for November: if d.month == 11, then (11 + 1) % 12 = 0, but the month value must be between 1 and 12. Don't think there's a nice way around this other than an ugly if-branch or obfuscated oneliner. – trujello Jul 14 '21 at 23:30
0

To properly deal with dates around a new year, I found dateutil.relativedelta to be a better alternative.

See also How to increment datetime month in python.

import datetime
from dateutil.relativedelta import relativedelta

d = datetime.date(2013,12,8)

last_day = datetime.date(d.year, d.month, 1)+relativedelta(months=1, days=-1)
Community
  • 1
  • 1