我想了解以下内容:给定一个日期(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(因为现在是星期五)
当前回答
要让星期天1点到星期六7点,这是解决问题的最简单方法:
datetime.date.today().toordinal()%7 + 1
所有这些:
import datetime
today = datetime.date.today()
sunday = today - datetime.timedelta(today.weekday()+1)
for i in range(7):
tmp_date = sunday + datetime.timedelta(i)
print tmp_date.toordinal()%7 + 1, '==', tmp_date.strftime('%A')
输出:
1 == Sunday
2 == Monday
3 == Tuesday
4 == Wednesday
5 == Thursday
6 == Friday
7 == Saturday
其他回答
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')
使用Canlendar模块
import calendar
a=calendar.weekday(year,month,day)
days=["MONDAY","TUESDAY","WEDNESDAY","THURSDAY","FRIDAY","SATURDAY","SUNDAY"]
print(days[a])
这是一个新的方法。星期天是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
假设您有timeStamp:字符串变量YYYY-MM-DD HH:MM:SS
步骤1:使用blow代码将其转换为dateTime函数。。。
df['timeStamp'] = pd.to_datetime(df['timeStamp'])
步骤2:现在您可以提取所有必需的功能,如下所示,这将为每个字段创建新的列-小时、月、星期、年、日期
df['Hour'] = df['timeStamp'].apply(lambda time: time.hour)
df['Month'] = df['timeStamp'].apply(lambda time: time.month)
df['Day of Week'] = df['timeStamp'].apply(lambda time: time.dayofweek)
df['Year'] = df['timeStamp'].apply(lambda t: t.year)
df['Date'] = df['timeStamp'].apply(lambda t: t.day)
如果您不完全依赖datetime模块,日历可能是更好的选择。例如,这将为您提供日期代码:
calendar.weekday(2017,12,22);
这将给你一天:
days = ["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"]
days[calendar.weekday(2017,12,22)]
或者以python的风格,作为一行:
["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"][calendar.weekday(2017,12,22)]