Home > Mobile >  Difference between today,week start
Difference between today,week start

Time:12-18

How to get the difference between datetime.datetime.utcnow(), and the start of week?

I want start of week of
"date=17,month=12,year=2022,hour=x,minute=y,second=z" to be: "date=12,month=12,year=2022,hour=0,minute=0,second=0", where x,y,z are variables,while they have to be converted to 0,0,0 only.

I tried the following code:

from datetime import datetime as dt,\
    timezone as tz,\
    timedelta as td
print(dt.isoformat(dt.utcnow()-td(days=dt.weekday(dt.now(tz.utc)))))

I used iso format to demonstrate what I mean,
for the 'now' value, I gave above,where date=17,
I get the following output:
"date=12,month=12,year=2022,hour=x,minute=y,second=z"(not what i expected)

Q.s Whats the best way to make these hours,minutes,seconds 0,taking into account all special cases:

  1. A range which includes feb 29, of a leap year
  2. A Example where week day is of previous month, of current day
  3. etc.

CodePudding user response:

Would this help?

from datetime import datetime as dt, timedelta as td

def getStartOfTheWeekDate(someDate: dt):
    return someDate - td(days=someDate.weekday())

def getDifferenceBetweenMyDateAndStartOfTheWeek(someDate: dt):
    return someDate - getStartOfTheWeekDate(someDate)

myStartOfTheWeek = getStartOfTheWeekDate(dt.now())
myStartOfTheWeekISO = dt.isoformat(myStartOfTheWeek)
myStartOfTheWeekStrippedISO = dt.isoformat(dt.combine(myStartOfTheWeek, dt.min.time()))

myDifference = getDifferenceBetweenMyDateAndStartOfTheWeek(dt.now())

print(myStartOfTheWeek)
print(myStartOfTheWeekISO)
print(myStartOfTheWeekStrippedISO)
print(myDifference)

Outputs:

poutput

  • Related