Get the last Thursday of the current month using Python
source link: https://www.codesd.com/item/get-the-last-thursday-of-the-current-month-using-python.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Get the last Thursday of the current month using Python
Following this answer I tried to get the date for last Thursday of the current month. But my code doesn't get out of loop.
from datetime import datetime
from dateutil.relativedelta import relativedelta, TH
todayte = datetime.today()
cmon = todayte.month
nthu = todayte
while nthu.month == cmon:
nthu += relativedelta(weekday=TH(1))
#print nthu.strftime('%d%b%Y').upper()
Looking at the documentation of relativedelta
Notice that if the calculated date is already
Monday
, for example, using(0, 1)
or(0, -1)
won’t change the day.
If nthu
is already Thursday then adding TH(1)
or TH(-1)
won't have any effect but result in the same date and that's why your loop is running infinitely.
I will assume maximum 5 weeks in a month and do it like following:
todayte = datetime.today()
cmon = todayte.month
for i in range(1, 6):
t = todayte + relativedelta(weekday=TH(i))
if t.month != cmon:
# since t is exceeded we need last one which we can get by subtracting -2 since it is already a Thursday.
t = t + relativedelta(weekday=TH(-2))
break
Recommend
-
13
Get the SonarQube Quality Gate status for the current commit2019-08-10When you use SonarQube and want to fail a pipeline if the Quality Gate result for the current git commit is not “OK”, this script might be he...
-
3
In this article we will discuss different ways to get the current date & timestamp in python. Get the current date & time using datetime.now() Python provides a module datetime which has a class datetime. It provides a...
-
8
PPC More Google Ads campaign changes this month; Thursday’s daily brief Plus, Reddit makes good on its adverti...
-
4
How do I check if the current index is the last index in the table? advertisements How do I say?
-
4
How to get the current page url using jQuery 1327 views 2 years ago jQuery Use the syntax $(location)...
-
3
How to Get the Current Year using PHP 1155 views 2 years ago PHP Use the PHP date() Function
-
5
Get First and Last Elements of a List in Python ProgramSkip to content Get First and Last...
-
4
How to Get Current Month Records in Laravel 755 views 9 months ago Laravel You may want to add filter while fetchin...
-
5
How to Get and Use the Current Time in Python Remove ads Getting the current time
-
8
How to Get the Current Time in Python Getting the current time in Python is a nice starting point for many time-related operations. One very important...
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK