Sau câu trả lời này, tôi đã cố gắng để có được ngày cho thứ Năm tuần trước của tháng hiện tại. Nhưng mã của tôi không thoát khỏi vòng lặp. 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()
Khi được hỏi ngày 2 tháng 5 năm 2016 lúc 6:04May 2, 2016 at 6:04
0 Nhìn vào tài liệu của 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
3Lưu ý rằng nếu ngày tính toán đã là 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
4, ví dụ, sử dụng 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
5 hoặc 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
6 won Thay đổi trong ngày.
Nếu 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
7 đã được vào thứ năm thì việc thêm 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
8 hoặc 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
9 sẽ không có bất kỳ ảnh hưởng nào nhưng dẫn đến cùng một ngày và đó là lý do tại sao vòng lặp của bạn chạy vô hạn.Tôi sẽ cho rằng tối đa 5 tuần trong một tháng và làm như sau: 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
Đã trả lời ngày 2 tháng 5 năm 2016 lúc 6:28May 2, 2016 at 6:28 AksaksAKS Huy hiệu vàng 18K340 Huy hiệu bạc 50 Huy hiệu đồng3 gold badges40 silver badges50 bronze badges Dựa trên câu trả lời của Adam Smith về cách tôi có thể nhận được thứ Sáu thứ 3 của một tháng ở Python ?, Bạn có thể nhận được ngày thứ Năm cuối cùng của tháng hiện tại như sau: import calendar
import datetime
def get_thursday(cal,year,month,thursday_number):
'''
For example, get_thursday(cal, 2017,8,0) returns (2017,8,3)
because the first thursday of August 2017 is 2017-08-03
'''
monthcal = cal.monthdatescalendar(year, month)
selected_thursday = [day for week in monthcal for day in week if \
day.weekday() == calendar.THURSDAY and \
day.month == month][thursday_number]
return selected_thursday
def main():
'''
Show the use of get_thursday()
'''
cal = calendar.Calendar(firstweekday=calendar.MONDAY)
today = datetime.datetime.today()
year = today.year
month = today.month
date = get_thursday(cal,year,month,-1) # -1 because we want the last Thursday
print('date: {0}'.format(date)) # date: 2017-08-31
if __name__ == "__main__":
main()
Đã trả lời ngày 2 tháng 8 năm 2017 lúc 20:30Aug 2, 2017 at 20:30 Bạn nên chuyển 2 đến import calendar
import datetime
def get_thursday(cal,year,month,thursday_number):
'''
For example, get_thursday(cal, 2017,8,0) returns (2017,8,3)
because the first thursday of August 2017 is 2017-08-03
'''
monthcal = cal.monthdatescalendar(year, month)
selected_thursday = [day for week in monthcal for day in week if \
day.weekday() == calendar.THURSDAY and \
day.month == month][thursday_number]
return selected_thursday
def main():
'''
Show the use of get_thursday()
'''
cal = calendar.Calendar(firstweekday=calendar.MONDAY)
today = datetime.datetime.today()
year = today.year
month = today.month
date = get_thursday(cal,year,month,-1) # -1 because we want the last Thursday
print('date: {0}'.format(date)) # date: 2017-08-31
if __name__ == "__main__":
main()
0 thay vì 1, vì 1 không thay đổi gì. Sửa đổi mã của bạn thành:while (nthu + relativedelta(weekday=TH(2))).month == cmon:
nthu += relativedelta(weekday=TH(2))
print nthu.strftime('%d-%b-%Y').upper()
# prints 26-MAY-2016
Lưu ý rằng tôi đã sửa đổi điều kiện của vòng lặp để phá vỡ lần xuất hiện cuối cùng trong ngày, nếu không nó sẽ bị hỏng trong tháng tới (trong trường hợp này, tháng 6). Đã trả lời ngày 2 tháng 5 năm 2016 lúc 6:27May 2, 2016 at 6:27
MarounmarounMaroun 92.3k30 Huy hiệu vàng188 Huy hiệu bạc236 Huy hiệu Đồng30 gold badges188 silver badges236 bronze badges 1 from datetime import datetime , timedelta
todayte = datetime.today()
cmon = todayte.month
nthu = todayte
while todayte.month == cmon:
todayte += timedelta(days=1)
if todayte.weekday()==3: #this is Thursday
nthu = todayte
print nthu
Đã trả lời ngày 2 tháng 5 năm 2016 lúc 6:32May 2, 2016 at 6:32 Ohad the ladohad the ladOhad the Lad 1.8251 Huy hiệu vàng16 Huy hiệu bạc23 Huy hiệu đồng1 gold badge16 silver badges23 bronze badges Bạn cũng có thể sử dụng gói import calendar
import datetime
def get_thursday(cal,year,month,thursday_number):
'''
For example, get_thursday(cal, 2017,8,0) returns (2017,8,3)
because the first thursday of August 2017 is 2017-08-03
'''
monthcal = cal.monthdatescalendar(year, month)
selected_thursday = [day for week in monthcal for day in week if \
day.weekday() == calendar.THURSDAY and \
day.month == month][thursday_number]
return selected_thursday
def main():
'''
Show the use of get_thursday()
'''
cal = calendar.Calendar(firstweekday=calendar.MONDAY)
today = datetime.datetime.today()
year = today.year
month = today.month
date = get_thursday(cal,year,month,-1) # -1 because we want the last Thursday
print('date: {0}'.format(date)) # date: 2017-08-31
if __name__ == "__main__":
main()
1. Truy cập lịch dưới dạng import calendar
import datetime
def get_thursday(cal,year,month,thursday_number):
'''
For example, get_thursday(cal, 2017,8,0) returns (2017,8,3)
because the first thursday of August 2017 is 2017-08-03
'''
monthcal = cal.monthdatescalendar(year, month)
selected_thursday = [day for week in monthcal for day in week if \
day.weekday() == calendar.THURSDAY and \
day.month == month][thursday_number]
return selected_thursday
def main():
'''
Show the use of get_thursday()
'''
cal = calendar.Calendar(firstweekday=calendar.MONDAY)
today = datetime.datetime.today()
year = today.year
month = today.month
date = get_thursday(cal,year,month,-1) # -1 because we want the last Thursday
print('date: {0}'.format(date)) # date: 2017-08-31
if __name__ == "__main__":
main()
2. Và lưu ý rằng, thứ sáu là ngày cuối cùng của một tuần.import calendar
import datetime
now = datetime.datetime.now()
last_sunday = max(week[-1] for week in calendar.monthcalendar(now.year,
now.month))
print('{}-{}-{:2}'.format(now.year, calendar.month_abbr[now.month],
last_sunday))
Đã trả lời ngày 2 tháng 5 năm 2016 lúc 7:13May 2, 2016 at
7:13 HootinghootingHooting 1.60111 Huy hiệu bạc20 Huy hiệu đồng11 silver badges20 bronze badges Tôi nghĩ rằng điều này sẽ nhanh nhất có lẽ: end_of_month = datetime.datetime.today() + relativedelta(day=31)
last_thursday = end_of_month + relativedelta(weekday=TH(-1))
Đã trả lời ngày 13 tháng 6 năm 2017 lúc 12:46Jun 13, 2017 at 12:46 DRBUGDRARBUGDrBug
1.9382 Huy hiệu vàng19 Huy hiệu bạc21 Huy hiệu đồng2 gold badges19 silver badges21 bronze badges Bạn có thể làm điều gì đó như thế này: import pandas as pd
from dateutil.relativedelta import relativedelta, TH
expiry_type = 0
today = pd.datetime.today()
expiry_dates = []
if expiry_type == 0:
# Weekly expiry
for i in range(1,13):
expiry_dates.append((today + relativedelta(weekday=TH(i))).date())
else:
# Monthly expiry
for i in range(1,13):
x = (today + relativedelta(weekday=TH(i))).date()
y = (today + relativedelta(weekday=TH(i+1))).date()
if x.month != y.month :
if x.day > y.day :
expiry_dates.append(x)
print(expiry_dates)
Đã trả lời ngày 10 tháng 12 năm 2019 lúc 15:28Dec 10, 2019 at 15:28 Mã này có thể được sử dụng trong Python 3.x để tìm kiếm vào thứ Năm tuần trước của tháng hiện tại. import datetime
dt = datetime.datetime.today()
def lastThurs(dt):
currDate, currMth, currYr = dt, dt.month, dt.year
for i in range(31):
if currDate.month == currMth and currDate.year == currYr and currDate.weekday() == 3:
#print('dt:'+ str(currDate))
lastThuDate = currDate
currDate += datetime.timedelta(1)
return lastThuDate
Artemis 2.4477 Huy hiệu vàng20 Huy hiệu bạc34 Huy hiệu đồng7 gold badges20 silver badges34 bronze badges Đã trả lời ngày 14 tháng 4 năm 2018 lúc 16:46Apr 14, 2018 at 16:46 import datetime
def get_thursday(_month,_year):
for _i in range(1,32):
if _i > 9:
_dateStr = str(_i)
else:
_dateStr = '0' + str(_i)
_date = str(_year) + '-' + str(_month) + '-' + _dateStr
try:
a = datetime.datetime.strptime(_date, "%Y-%m-%d").strftime('%a')
except:
continue
if a == 'Thu':
_lastThurs = _date
return _lastThurs
x = get_thursday('05','2017')
print(x)
Đã trả lời ngày 30 tháng 11 năm 2019 lúc 17:22Nov 30, 2019 at 17:22 1 Nó rất nhanh và dễ hiểu, chúng tôi lấy lần đầu tiên mỗi tháng và sau đó trừ nó bằng 3 coz 3 là số ngày thứ năm và sau đó nhân nó với 4 và kiểm tra xem nó có ở cùng tháng không nếu đó là Thứ Năm tuần trước nếu không chúng tôi nhân nó với 3 và chúng tôi nhận được thứ Năm cuối cùng của chúng tôistraightforward fast and easy to understand, we take the first of every month and then subtract it by 3 coz 3 is Thursday weekday number and then multiply it by either 4 and check if it is in the same month if it is then that is last Thursday otherwise we multiply it with 3 and we get our
last Thursday 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
0 Đã trả lời ngày 20 tháng 8 lúc 21:42Aug 20 at 21:42 Bạn có thể sử dụng lịch để đạt được kết quả của bạn. Tôi thấy nó đơn giản. 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
1Danh sách hàng tuần_thursday sẽ có tất cả các ngày thứ Năm từ tháng. import calendar
import datetime
def get_thursday(cal,year,month,thursday_number):
'''
For example, get_thursday(cal, 2017,8,0) returns (2017,8,3)
because the first thursday of August 2017 is 2017-08-03
'''
monthcal = cal.monthdatescalendar(year, month)
selected_thursday = [day for week in monthcal for day in week if \
day.weekday() == calendar.THURSDAY and \
day.month == month][thursday_number]
return selected_thursday
def main():
'''
Show the use of get_thursday()
'''
cal = calendar.Calendar(firstweekday=calendar.MONDAY)
today = datetime.datetime.today()
year = today.year
month = today.month
date = get_thursday(cal,year,month,-1) # -1 because we want the last Thursday
print('date: {0}'.format(date)) # date: 2017-08-31
if __name__ == "__main__":
main()
3 sẽ cung cấp cho bạn thứ Năm cuối cùng của tháng.
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
2 Đã trả lời ngày 9 tháng 9 lúc 6:42Sep 9 at 6:42
Làm thế nào để tôi có được thứ Năm cuối cùng của tháng ở Python?
Danh sách hàng tuần_thursday sẽ có tất cả các ngày thứ Năm từ tháng. Weekly_thursday [-1] sẽ cung cấp cho bạn thứ Năm cuối cùng của tháng.weekly_thursday[-1] will give you the last Thursday of the month.
Làm thế nào để tôi có được thứ Sáu cuối cùng của tháng ở Python?
DateTime.Date (2024,2,1)+RelativeSelta (Day = 31, Weekay = FR (-1), Tuần = 4) cho ngày 22 tháng 3 năm 2024 nhưng thứ Sáu cuối cùng của tháng đó là 29 tháng 3.Nhưng DateTime.Ngày (2024,2,1)+RelativeSelta (ngày = 31, ngày trong tuần = FR (-1), tháng = 1) cho bạn câu trả lời chính xác. date(2024,2,1)+relativedelta(day=31, weekday=FR(-1), weeks=4) gives 22 March 2024 but the last Friday of that month is 29 March. But datetime. date(2024,2,1)+relativedelta(day=31, weekday=FR(-1), months=1) gives you the correct answer.
Làm thế nào để tôi có được ngày cuối cùng của tháng ở Python?
Phương pháp số 1: Sử dụng thay thế () + TimeDelta () trong này, trích xuất vào tháng tiếp theo và trừ vào ngày của đối tượng tháng tiếp theo được trích xuất từ tháng tiếp theo, dẫn đến 1 ngày trước khi bắt đầu tháng tiếp theo, tức là ngày cuối cùng của tháng hiện tại.Using replace() + timedelta()
In this, extract the next month, and subtract the day of next month object extracted from the next month, resulting in 1 day before beginning of next month, i.e last date of current month.
Làm thế nào để tôi có được ngày cuối cùng của một ngày ở Python?
Nhận ngày hệ thống trước, hiện tại và ngày tiếp theo trong Python.. Ngày hiện tại: Nhập DateTime current_date = datetime.dateTime.today () in (current_date). Ngày trước: Nhập DateTime trước_date = datetime.dateTime.Today () - datetime.timedelta (ngày = 1) in (trước_date). |