python-3.x 我找到了一个计算星期一之前天数的脚本,但我不知道如何将result转换为int

mutmk8jj  于 2023-01-06  发布在  Python
关注(0)|答案(3)|浏览(71)

下面是脚本:

from datetime import datetime, timedelta

today = now = datetime.today()
today = datetime(today.year, today.month, today.day)
print (timedelta(days=7-now.weekday()) + today - now)

我需要结果为int,因为程序要求日期为int。

s4n0splo

s4n0splo1#

你的结果是一个timedelta。你可以用days属性得到timedelta的天数:

delta = timedelta(days=7-now.weekday()) + today - now)
print(delta.days)
rta7y2nd

rta7y2nd2#

如果你指的是整数表示天数--用timedelta.days,如果你指的是秒--这里有一个两者的解决方案。

from datetime import datetime, timedelta

today = now = datetime.today()

today = datetime(today.year, today.month, today.day)

td = timedelta(days=7-now.weekday()) + today - now

print(td.days)

td_seconds = td.total_seconds() 

print(round(td_seconds)) # rounded
iyzzxitl

iyzzxitl3#

对脚本的目标有点困惑,但我假设您希望找到当前日期和下一个星期一之间的天数。
假设:

  • 天数计算到星期一上午12点。换句话说,天数计数不包括星期一。

仅计算星期一之前的完整天数的代码:

from datetime import datetime, timedelta
today = datetime.today()
print(int(6 - today.weekday()))

输出(当前日期为星期三1:29AM):第一个月
用于计算天数(包括部分天数)的代码(例如,当前星期三1:29,到星期一12am大约有4.91天)。
详细视图:

from datetime import datetime, timedelta

# Get current date
today = datetime.today()

# Calculate number of days until Monday (partial days count as full day)
days_until_monday = timedelta(days=int(6 - today.weekday()) + 1)

# Get date of next Monday
next_monday = today + days_until_monday

# Format dates
today = datetime(today.year, today.month, today.day, today.hour, today.minute, today.second)
next_monday = datetime(next_monday.year, next_monday.month, next_monday.day, 0, 0, 0)

# Difference up to the nearest second
delta = next_monday - today
delta = delta.total_seconds()

# Convert to days
delta = delta / 86400

# Print result
print(float(delta))

输出:4.912685185185185
希望这有帮助:)

相关问题