我想了解以下内容:给定一个日期(datetime对象),一周中对应的日期是什么?
例如,星期天是第一天,星期一是第二天。。等等
然后如果输入的内容类似于今天的日期。
实例
>>> today = datetime.datetime(2017, 10, 20)
>>> today.get_weekday() # what I look for
产量可能是6(因为现在是星期五)
我想了解以下内容:给定一个日期(datetime对象),一周中对应的日期是什么?
例如,星期天是第一天,星期一是第二天。。等等
然后如果输入的内容类似于今天的日期。
实例
>>> today = datetime.datetime(2017, 10, 20)
>>> today.get_weekday() # what I look for
产量可能是6(因为现在是星期五)
当前回答
下面是解决此问题的简单代码片段
import datetime
intDay = datetime.date(year=2000, month=12, day=1).weekday()
days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
print(days[intDay])
输出应为:
Friday
其他回答
以下是如何将小端字符串日期列表转换为datetime:
import datetime, time
ls = ['31/1/2007', '14/2/2017']
for d in ls:
dt = datetime.datetime.strptime(d, "%d/%m/%Y")
print(dt)
print(dt.strftime("%A"))
下面是解决此问题的简单代码片段
import datetime
intDay = datetime.date(year=2000, month=12, day=1).weekday()
days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
print(days[intDay])
输出应为:
Friday
如果您希望生成一个包含日期范围(Date)的列,并生成一个指向第一个日期并指定周日(Week Day)的列(我将使用从2008-01-01到2020-02-01的日期):
import pandas as pd
dr = pd.date_range(start='2008-01-01', end='2020-02-1')
df = pd.DataFrame()
df['Date'] = dr
df['Week Day'] = pd.to_datetime(dr).weekday
输出如下:
工作日从0到6不等,其中0对应于周一,6对应于周日。
1700/1/1之后的日期不需要导入的解决方案
def weekDay(year, month, day):
offset = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334]
week = ['Sunday',
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday']
afterFeb = 1
if month > 2: afterFeb = 0
aux = year - 1700 - afterFeb
# dayOfWeek for 1700/1/1 = 5, Friday
dayOfWeek = 5
# partial sum of days betweem current date and 1700/1/1
dayOfWeek += (aux + afterFeb) * 365
# leap year correction
dayOfWeek += aux / 4 - aux / 100 + (aux + 100) / 400
# sum monthly and day offsets
dayOfWeek += offset[month - 1] + (day - 1)
dayOfWeek %= 7
return dayOfWeek, week[dayOfWeek]
print weekDay(2013, 6, 15) == (6, 'Saturday')
print weekDay(1969, 7, 20) == (0, 'Sunday')
print weekDay(1945, 4, 30) == (1, 'Monday')
print weekDay(1900, 1, 1) == (1, 'Monday')
print weekDay(1789, 7, 14) == (2, 'Tuesday')
这是一个新的方法。星期天是0。
from datetime import datetime
today = datetime(year=2022, month=6, day=17)
print(today.toordinal()%7) # 5
yesterday = datetime(year=1, month=1, day=1)
print(today.toordinal()%7) # 1