python - Python 中的日期计算

标签 python datetime

我对 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

最佳答案

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

关于python - Python 中的日期计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3194036/

相关文章:

时钟()无法正常工作

python - 打包带有依赖项的单个 Python 模块

python - pandas - 按列名屏蔽数据框

python - PyQt Python - 为 QPushButton 创建鼠标右键单击

python - Django过滤模块: lookup expression (year) does not return the desired queryset

java - 支持跨时区和夏令时变化的重复事件

ruby-on-rails - Ruby(带 Rails)将一串时间转换成秒?

javascript - 某些设备中的时区错误 - React Native

sql-server - SQL使用静态日期计算一夜之间的小时数

Python 无缘无故地停止写入文件