首页 文章

Python中的日期计算

提问于
浏览
1

我是Python的新手,我正在尝试编写以下日期计算功能

  • 找到指定日期时间周一的日期

  • 在指定的日期时间内找到该月的第一个非周末日

  • 在指定的日期时间内找到一年中的第一个非周末日

  • 在指定的日期时间内找到一个月的第N个[星期几]

以下是我到目前为止的尝试 - 如果逻辑可以改进(或纠正)为更多'Pythonic',请告诉我

import datetime

def find_month_first_monday(tstamp = datetime.today()):
    day_of_month = datetime.date.today().timetuple()[2]
    day_of_week = datetime.weekday(tstamp)
    # now I have the dow, and dom, I can index into a 2D array of
    # dates for the month - IF I knew how to get to that array ...


def find_first_gbd_in_month(tstamp = datetime.today()):
    # naive way would be to find the month and year from the passed in arg,
    # calculate the first day for that month/year and iterate until a non-weekend day
    # is found. Not elegant, there must be a better way
    pass


def find_first_gbd_in_year(tstamp = datetime.today()):
   # Ditto, as above.
    pass


def find_ndow_in_month(tstamp = datetime.today()):
    # again, I can get the month and the year from the passed in argument
    # what I need is a 2D array of dates for the month/year, so I can get
    # the nth dow (similar to reading off a calendar)
    pass

2 回答

  • 4

    find_month_first_monday

    我会使用不同的算法 . 首先,找到该月的第一天 .

    first_day_of_month = datetime.date.today().replace(day=1)
    

    并找到 first_day_of_month 的工作日,

    week_day = first_day_of_month.weekday()
    

    并在必要时添加天数 .

    if week_day:
      first_day_of_month += datetime.timedelta(days=7-week_day)
    

    find_first_gbd_in_month

    find_month_first_monday 类似,但仅在 week_day 为5或6(周六和周日)时添加日期 .

    find_first_gbd_in_year

    .replace 中也提供 month=1 参数 .

    find_ndow_in_month

    找到一周的第一天,然后添加n-1 weeks .

  • 4

    使用优秀的dateutil模块 . 用它做这个和其他日期计算非常容易 .

    一些例子:

    import datetime
    from dateutil import rrule
    today = datetime.date.today()
    

    本月的第一个周五,为期10个月:

    print list(rrule.rrule(rrule.MONTHLY, count=10, byweekday=rrule.FR(1),
        dtstart=today)))
    

    结果:

    [datetime.datetime(2010, 8, 2, 0, 0),
     datetime.datetime(2010, 9, 6, 0, 0),
     datetime.datetime(2010, 10, 4, 0, 0),
     datetime.datetime(2010, 11, 1, 0, 0),
     datetime.datetime(2010, 12, 6, 0, 0),
     datetime.datetime(2011, 1, 3, 0, 0),
     datetime.datetime(2011, 2, 7, 0, 0),
     datetime.datetime(2011, 3, 7, 0, 0),
     datetime.datetime(2011, 4, 4, 0, 0),
     datetime.datetime(2011, 5, 2, 0, 0)]
    

    今年的第一个星期一,为期3年:

    print list(rrule.rrule(rrule.YEARLY, count=3, byweekday=rrule.MO(1),
        dtstart=datetime.date.today()))
    

    结果:

    [datetime.datetime(2011, 1, 3, 0, 0),
     datetime.datetime(2012, 1, 2, 0, 0),
     datetime.datetime(2013, 1, 7, 0, 0)]
    

相关问题