【问题标题】:Is there a better way to determine day in future using integer values有没有更好的方法来使用整数值来确定未来的日子
【发布时间】:2021-01-24 15:19:22
【问题描述】:

问题来了:

如果 int 值 [0,7) (0, 1, 2, 3, 4, 5, 6) 指的是星期一到 星期天,今天是星期一,999 是星期几 天?

我是这样解决的:

import datetime
 
#Capture the First Date
day1 = datetime.date(2021, 1, 25)
print('day1:', day1.ctime())

# Capture the Second Date
day2 = datetime.date(2023, 10, 21)
print('day2:', day2.ctime())

# Find the difference between the dates
print('Number of Days:', day1-day2)

返回:

day1: Mon Jan 25 00:00:00 2021
day2: Sat Oct 21 00:00:00 2023
Number of Days: -999 days, 0:00:00

【问题讨论】:

  • 欢迎来到 SO。有关使代码更好的问题更多地在Code Review 的范围内。
  • 感谢@niamulbengali 的礼貌纠正。我会注意未来的。

标签: python python-3.x date integer


【解决方案1】:

使用timedeltan 添加到“开始日期”后的天数:

from datetime import date, timedelta

current = date.today()
future = current + timedelta(days=999)

print(f"{current=}", current.weekday(), current.strftime("%A"))
print(f"{future=}", future.weekday(), future.strftime("%A"))

输出:

current=datetime.date(2021, 1, 24) 6 Sunday
future=datetime.date(2023, 10, 20) 4 Friday

.weekday() 以整数形式返回星期几。
.strftime("%A") 将日期对象格式化为工作日名称。

【讨论】:

  • 能否请您解释一下如何从datetime 对象中获取day? OP 的问题是找出日期:*"(0, 1, 2, 3, 4, 5, 6) 指周一到周日,今天是周一,在 999 天内 一周中的哪一天"*`
  • 我导入了日历并定义了一种查找日期的方法: def findDay(date): day, month, year = (int(i) for i in date.split(' ')) dayNumber = calendar.weekday(year, month, day) days =["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] return (days[dayNumber]) # Driver program date = '20 10 2023' print(findDay(date)) 结果返回:(2023, 10, 20) Friday
猜你喜欢
  • 2016-08-30
  • 1970-01-01
  • 1970-01-01
  • 2010-09-21
  • 1970-01-01
  • 2011-07-30
  • 1970-01-01
  • 1970-01-01
  • 2017-11-29
相关资源
最近更新 更多