I have a question about a better way to do this as what I've written seems clunky. I'm trying to generate 2 variables here that will be used as the date in a BETWEEN clause in MySQL. In order to get the proper construction (YYYYMMDD) I am converting to a string and slicing. But because I use the first date (endwk) as a reference to calculate the second (startwk) I need to also store the result of endwk as its original datetime (endwkdate) type in order to use it in the calculation of startwk because I get an error if I just use endwk. This seems like a rookie workaround to me, but it does work.

However I'm new to python and trying to develop good habits, so I'd be interested to know a more efficient way to do this. Any ideas, or am I just being too picky? Here's the code:

## Goal is to produce 2 dates:  Date of last Tuesday (or today if this is Tuesday)
## Date of Tuesday a week before last Tuesday

import datetime

#  day of week as an integer to be used as an offset.  If 0 then its Monday
#  Looking for Tuesday so subtract 1 from day of week return for Tuesday offset
wkday = datetime.date.weekday(datetime.datetime.now()) - 1

nowdate= datetime.datetime.date(datetime.datetime.now())

# gets date of last Tuesday
endwkdate = nowdate - datetime.timedelta(days = wkday)  # need this later as a datetime object

endwk= str(nowdate - datetime.timedelta(days = wkday))  # as a string for slicing
d1 = endwk[:4] + endwk[5:7] + endwk[8:10]


# gets date of the Tuesay a week before last Tuesday
startwk = str(endwkdate - datetime.timedelta(days = 7)) 
d2 = startwk[:4] + startwk[5:7] + startwk[8:10]


# For debug, to see that dates are correct
print('d1 =  ' + d1 + '\n')
print('d2 =  ' + d2 + '\n')

Thanks

Did a bit more research and discovered the magic of strftime which I think solves my problem.

I replaced lines 12 thru 21 in my original example with:

# gets date of last Tuesday
endwk = nowdate - datetime.timedelta(days = wkday)  # need this later as a datetime object
d1 = endwk.strftime("%Y%m%d")


# gets date of the Tuesday a week before last Tuesday
startwk = endwk - datetime.timedelta(days = 7) 
d2 = startwk.strftime("%Y%m%d")
commented: excellent ! +13
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.