我想了解以下内容:给定一个日期(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(因为现在是星期五)
当前回答
我为CodeChef问题解决了这个问题。
import datetime
dt = '21/03/2012'
day, month, year = (int(x) for x in dt.split('/'))
ans = datetime.date(year, month, day)
print (ans.strftime("%A"))
其他回答
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')
如果您不完全依赖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)]
一个简单、直接但尚未提及的选项:
import datetime
...
givenDateObj = datetime.date(2017, 10, 20)
weekday = givenDateObj.isocalendar()[2] # 5
weeknumber = givenDateObj.isocalendar()[1] # 42
这不需要每周的评论。我推荐这个代码~!
import datetime
DAY_OF_WEEK = {
"MONDAY": 0,
"TUESDAY": 1,
"WEDNESDAY": 2,
"THURSDAY": 3,
"FRIDAY": 4,
"SATURDAY": 5,
"SUNDAY": 6
}
def string_to_date(dt, format='%Y%m%d'):
return datetime.datetime.strptime(dt, format)
def date_to_string(date, format='%Y%m%d'):
return datetime.datetime.strftime(date, format)
def day_of_week(dt):
return string_to_date(dt).weekday()
dt = '20210101'
if day_of_week(dt) == DAY_OF_WEEK['SUNDAY']:
None
假设您有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)