Hướng dẫn how do you get next monday in python? - làm thế nào để bạn có được thứ hai tiếp theo trong python?

Đưa ra một ngày cụ thể, giả sử 2011-07-02, làm thế nào tôi có thể tìm thấy ngày thứ Hai tới (hoặc bất kỳ ngày trong tuần nào cho vấn đề đó) sau ngày đó?

Hướng dẫn how do you get next monday in python? - làm thế nào để bạn có được thứ hai tiếp theo trong python?

hỏi ngày 2 tháng 7 năm 2011 lúc 17:32Jul 2, 2011 at 17:32

1

import datetime
def next_weekday(d, weekday):
    days_ahead = weekday - d.weekday()
    if days_ahead <= 0: # Target day already happened this week
        days_ahead += 7
    return d + datetime.timedelta(days_ahead)

d = datetime.date(2011, 7, 2)
next_monday = next_weekday(d, 0) # 0 = Monday, 1=Tuesday, 2=Wednesday...
print(next_monday)

Đã trả lời ngày 2 tháng 7 năm 2011 lúc 17:38Jul 2, 2011 at 17:38

Phihagphihagphihag

268K68 Huy hiệu vàng441 Huy hiệu bạc463 Huy hiệu Đồng68 gold badges441 silver badges463 bronze badges

2

Đây là một sự thay thế ngắn gọn và chung chung cho các câu trả lời hơi nặng ở trên.

def onDay(date, day):
    """
    Returns the date of the next given weekday after
    the given date. For example, the date of next Monday.

    NB: if it IS the day we're looking for, this returns 0.
    consider then doing onDay(foo, day + 1).
    """
    days = (day - date.weekday() + 7) % 7
    return date + datetime.timedelta(days=days)

Hướng dẫn how do you get next monday in python? - làm thế nào để bạn có được thứ hai tiếp theo trong python?

wjandrea

24.8k8 Huy hiệu vàng53 Huy hiệu bạc73 Huy hiệu đồng8 gold badges53 silver badges73 bronze badges

Đã trả lời ngày 6 tháng 6 năm 2016 lúc 4:56Jun 6, 2016 at 4:56

user1034533user1034533user1034533

1.0189 huy hiệu bạc9 huy hiệu đồng9 silver badges9 bronze badges

4

Thử

>>> dt = datetime(2011, 7, 2)
>>> dt + timedelta(days=(7 - dt.weekday()))
datetime.datetime(2011, 7, 4, 0, 0)

Sử dụng, rằng thứ Hai tuần sau là 7 ngày sau ngày thứ Hai, 6 ngày sau một ngày thứ ba, v.v., và cũng sử dụng, loại

def onDay(date, day):
    """
    Returns the date of the next given weekday after
    the given date. For example, the date of next Monday.

    NB: if it IS the day we're looking for, this returns 0.
    consider then doing onDay(foo, day + 1).
    """
    days = (day - date.weekday() + 7) % 7
    return date + datetime.timedelta(days=days)
5 của Python báo cáo vào thứ Hai là
def onDay(date, day):
    """
    Returns the date of the next given weekday after
    the given date. For example, the date of next Monday.

    NB: if it IS the day we're looking for, this returns 0.
    consider then doing onDay(foo, day + 1).
    """
    days = (day - date.weekday() + 7) % 7
    return date + datetime.timedelta(days=days)
6, ..., Chủ nhật là
def onDay(date, day):
    """
    Returns the date of the next given weekday after
    the given date. For example, the date of next Monday.

    NB: if it IS the day we're looking for, this returns 0.
    consider then doing onDay(foo, day + 1).
    """
    days = (day - date.weekday() + 7) % 7
    return date + datetime.timedelta(days=days)
7.

Đã trả lời ngày 2 tháng 7 năm 2011 lúc 17:43Jul 2, 2011 at 17:43

DirkdirkDirk

30.2k6 Huy hiệu vàng80 Huy hiệu bạc100 Huy hiệu đồng6 gold badges80 silver badges100 bronze badges

5

Đây là ví dụ về các tính toán trong vòng

def onDay(date, day):
    """
    Returns the date of the next given weekday after
    the given date. For example, the date of next Monday.

    NB: if it IS the day we're looking for, this returns 0.
    consider then doing onDay(foo, day + 1).
    """
    days = (day - date.weekday() + 7) % 7
    return date + datetime.timedelta(days=days)
8.

import datetime


def next_day(given_date, weekday):
    day_shift = (weekday - given_date.weekday()) % 7
    return given_date + datetime.timedelta(days=day_shift)

now = datetime.date(2018, 4, 15) # sunday
names = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday',    
         'saturday', 'sunday']
for weekday in range(7):
    print(names[weekday], next_day(now, weekday))

sẽ in:

monday 2018-04-16
tuesday 2018-04-17
wednesday 2018-04-18
thursday 2018-04-19
friday 2018-04-20
saturday 2018-04-21
sunday 2018-04-15

Như bạn thấy, nó cung cấp chính xác cho bạn vào thứ Hai, thứ Ba, thứ Tư, thứ Năm và thứ Bảy tới. Và nó cũng hiểu rằng

def onDay(date, day):
    """
    Returns the date of the next given weekday after
    the given date. For example, the date of next Monday.

    NB: if it IS the day we're looking for, this returns 0.
    consider then doing onDay(foo, day + 1).
    """
    days = (day - date.weekday() + 7) % 7
    return date + datetime.timedelta(days=days)
9 là một Chủ nhật và trở lại vào Chủ nhật hiện tại thay vì tiếp theo.

Tôi chắc rằng bạn sẽ thấy câu trả lời này cực kỳ hữu ích sau 7 năm ;-)

Đã trả lời ngày 15 tháng 4 năm 2018 lúc 8:09Apr 15, 2018 at 8:09

Nổi bậtPeowFeaturedPeowfeaturedpeow

1.8911 Huy hiệu vàng18 Huy hiệu bạc16 Huy hiệu đồng1 gold badge18 silver badges16 bronze badges

Một giải pháp thanh lịch đơn giản khác là sử dụng độ lệch gấu trúc.

Tôi thấy nó rất hữu ích và mạnh mẽ khi chơi với ngày.

  • Nếu bạn muốn Chủ nhật đầu tiên, chỉ cần sửa đổi tần số thành freq = 'w-sun'.
  • Nếu bạn muốn một vài Chủ nhật tiếp theo, hãy thay đổi Offsets.day (ngày).
  • Sử dụng độ lệch của gấu trúc cho phép bạn bỏ qua các ngày lễ, chỉ làm việc với những ngày làm việc và hơn thế nữa.

Bạn cũng có thể áp dụng phương thức này một cách dễ dàng trên toàn bộ dữ liệu bằng phương pháp

>>> dt = datetime(2011, 7, 2)
>>> dt + timedelta(days=(7 - dt.weekday()))
datetime.datetime(2011, 7, 4, 0, 0)
0.

import pandas as pd
import datetime

# 1. Getting the closest monday from a given date
date = datetime.date(2011, 7, 2)
closest_monday = pd.date_range(start=date, end=date + pd.offsets.Day(6), freq="W-MON")[
    0
]

# 2. Adding a 'ClosestMonday' column with the closest monday for each row in
# a pandas df using apply. Requires you to have a 'Date' column in your df
def get_closest_monday(row):
    return pd.date_range(
        start=row.Date, end=row.Date + pd.offsets.Day(6), freq="W-MON"
    )[0]


df = pd.DataFrame([datetime.date(2011, 7, 2)], columns=["Date"])
df["ClosestMonday"] = df.apply(lambda row: get_closest_monday(row), axis=1)
print(df)

Tantrix

1.17810 Huy hiệu bạc13 Huy hiệu đồng10 silver badges13 bronze badges

Đã trả lời ngày 8 tháng 6 năm 2017 lúc 12:18Jun 8, 2017 at 12:18

2

Một cách khác sử dụng rrule

from dateutil.rrule import rrule, WEEKLY, MO
from datetime import date

next_monday = rrule(freq=WEEKLY, dtstart=date.today(), byweekday=MO, count=1)[0]

Tài liệu rrule: https://dateutil.readthedocs.io/en/stable/rrule.html

Đã trả lời ngày 4 tháng 1 năm 2019 lúc 3:41Jan 4, 2019 at 3:41

Bạn có thể bắt đầu thêm một ngày cho đến ngày đối tượng và dừng lại khi là thứ Hai.

>>> d = datetime.date(2011, 7, 2)
>>> while d.weekday() != 0: #0 for monday
...     d += datetime.timedelta(days=1)
... 
>>> d
datetime.date(2011, 7, 4)

Đã trả lời ngày 2 tháng 7 năm 2011 lúc 17:45Jul 2, 2011 at 17:45

Utdemirutdemirutdemir

25.9k10 Huy hiệu vàng61 Huy hiệu bạc81 Huy hiệu đồng10 gold badges61 silver badges81 bronze badges

import datetime

d = datetime.date(2011, 7, 2)
while d.weekday() != 0:
    d += datetime.timedelta(1)

Đã trả lời ngày 25 tháng 6 năm 2017 lúc 23:16Jun 25, 2017 at 23:16

JonathanjonathanJonathan

12.7K16 Huy hiệu vàng85 Huy hiệu bạc119 Huy hiệu đồng16 gold badges85 silver badges119 bronze badges

weekday = 0 ## Monday
dt = datetime.datetime.now().replace(hour=0, minute=0, second=0) ## or any specific date
days_remaining = (weekday - dt.weekday() - 1) % 7 + 1
next_dt = dt + datetime.timedelta(days_remaining)

Đã trả lời ngày 4 tháng 4 năm 2016 lúc 9:03Apr 4, 2016 at 9:03

Saeedgnusaeedgnusaeedgnu

3,8632 huy hiệu vàng30 huy hiệu bạc46 Huy hiệu đồng2 gold badges30 silver badges46 bronze badges

DateUtil có một tính năng đặc biệt cho loại hoạt động này và đó là cách thanh lịch nhất tôi từng thấy. has a special feature for this kind of operation and it's the most elegant way I have ever seen yet.

def onDay(date, day):
    """
    Returns the date of the next given weekday after
    the given date. For example, the date of next Monday.

    NB: if it IS the day we're looking for, this returns 0.
    consider then doing onDay(foo, day + 1).
    """
    days = (day - date.weekday() + 7) % 7
    return date + datetime.timedelta(days=days)
0

Nếu bạn muốn DateTime chỉ

def onDay(date, day):
    """
    Returns the date of the next given weekday after
    the given date. For example, the date of next Monday.

    NB: if it IS the day we're looking for, this returns 0.
    consider then doing onDay(foo, day + 1).
    """
    days = (day - date.weekday() + 7) % 7
    return date + datetime.timedelta(days=days)
1

Đã trả lời ngày 15 tháng 6 lúc 15:54Jun 15 at 15:54

Hướng dẫn how do you get next monday in python? - làm thế nào để bạn có được thứ hai tiếp theo trong python?

Nói chung để tìm bất kỳ ngày nào từ ngày trong tuần kể từ hôm nay:


def onDay(date, day):
    """
    Returns the date of the next given weekday after
    the given date. For example, the date of next Monday.

    NB: if it IS the day we're looking for, this returns 0.
    consider then doing onDay(foo, day + 1).
    """
    days = (day - date.weekday() + 7) % 7
    return date + datetime.timedelta(days=days)
2

Cung cấp đầu ra ở định dạng ngày/tháng/năm

Đã trả lời ngày 7 tháng 1 lúc 15:08Jan 7 at 15:08

AkshaybakshaybAkshayB

131 Huy hiệu bạc6 Huy hiệu đồng1 silver badge6 bronze badges

Điều này sẽ cung cấp vào thứ Hai tuần sau sau ngày được đưa ra:

def onDay(date, day):
    """
    Returns the date of the next given weekday after
    the given date. For example, the date of next Monday.

    NB: if it IS the day we're looking for, this returns 0.
    consider then doing onDay(foo, day + 1).
    """
    days = (day - date.weekday() + 7) % 7
    return date + datetime.timedelta(days=days)
3

2011-07-04 2015-09-07 2015-09-07
2015-09-07
2015-09-07

Đã trả lời ngày 30 tháng 5 năm 2014 lúc 17:48May 30, 2014 at 17:48

Rabin Utamrabin Utamrabin utam

12.8k3 Huy hiệu vàng20 Huy hiệu bạc15 Huy hiệu đồng3 gold badges20 silver badges15 bronze badges

0

thông qua danh sách hiểu?

def onDay(date, day):
    """
    Returns the date of the next given weekday after
    the given date. For example, the date of next Monday.

    NB: if it IS the day we're looking for, this returns 0.
    consider then doing onDay(foo, day + 1).
    """
    days = (day - date.weekday() + 7) % 7
    return date + datetime.timedelta(days=days)
4

Đã trả lời ngày 7 tháng 10 năm 2015 lúc 12:58Oct 7, 2015 at 12:58

Làm thế nào để bạn có được Thứ Hai của tuần Python?

isoweekday () để có được một ngày trong tuần của một ngày trong Python sử dụng phương thức isoweekday () để có được ngày trong tuần như một số nguyên, trong đó Thứ Hai là 1 và Chủ nhật là 7. tức là để bắt đầu từ số ngày trong tuần từ 1, Chúng ta có thể sử dụng isoweekday () thay cho ngày trong tuần (). Đầu ra là 1, tương đương với thứ Hai vì thứ Hai là 1.Use the isoweekday() method to get the day of the week as an integer, where Monday is 1 and Sunday is 7. i.e., To start from the weekday number from 1, we can use isoweekday() in place of weekday() . The output is 1, which is equivalent to Monday as Monday is 1.

Làm thế nào để bạn có được ngày hôm sau ở Python?

Bạn có thể thêm 3 phần sau vào mã để có được ngày hệ thống không định dạng (bao gồm cả dấu thời gian) trong Python:..
Current_date = datetime.ngày giờ.hôm nay().
Trước_date = DateTime.ngày giờ.Hôm nay () - DateTime.Timedelta (ngày = 1).
NEXTDAY_DATE = DateTime.ngày giờ.Hôm nay () + DateTime.Timedelta (ngày = 1).

Làm thế nào để bạn có được Chủ nhật tiếp theo ở Python?

Chủ nhật) NEXTMONDAY = NEXTMONDAY.strftime ('%d/%m/%y') nextSunday = nextSunday.strftime ('%d/%m/%y') để có được vào Chủ nhật tiếp theo sau ngày thứ Hai tiếp theo. strftime('%d/%m/%Y') nextSunday = nextSunday. strftime('%d/%m/%Y') To get next Sunday after the next Monday.

Làm thế nào để bạn có được thứ bảy tuần sau ở Python?

Day ()) % 7 để tính toán đồng bằng theo ngày từ ngày nhất định đến thứ Bảy tới vì ngày trong tuần là từ 0 (thứ Hai) đến 6 (Chủ nhật), vì vậy thứ bảy là 5. Nhưng: 5 và 12 là cùng một modulo 7 (vâng,Chúng tôi có 7 ngày trong một tuần :-)) Vì vậy, 12 - d. to compute the delta in days between given day and next Saturday because weekday is between 0 (Monday) and 6 (Sunday), so Saturday is 5. But: 5 and 12 are the same modulo 7 (yes, we have 7 days in a week :-) ) so 12 - d.