Answers:
使用weekday()
(docs):
>>> import datetime
>>> datetime.datetime.today()
datetime.datetime(2012, 3, 23, 23, 24, 55, 173504)
>>> datetime.datetime.today().weekday()
4
从文档中:
以整数形式返回星期几,其中星期一为0,星期日为6。
int(datetime.datetime.today().strftime('%w'))
如果您想用英文注明日期:
from datetime import date
import calendar
my_date = date.today()
calendar.day_name[my_date.weekday()] #'Wednesday'
my_date.strftime('%A')
如果您想用英文注明日期:
>>> from datetime import datetime
>>> datetime.today().strftime('%A')
'Wednesday'
了解更多:https: //docs.python.org/2/library/datetime.html#strftime-strptime-behavior
我解决了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库有时会因strptime()提供错误,因此我切换到dateutil库。这是一个如何使用它的示例:
from dateutil import parser
parser.parse('January 11, 2010').strftime("%a")
您从中获得的输出是'Mon'
。如果要将输出显示为“星期一”,请使用以下命令:
parser.parse('January 11, 2010').strftime("%A")
这对我来说很快。使用日期时间库时遇到问题,因为我想存储工作日名称而不是工作日编号,并且使用日期时间库的格式引起了问题。如果您对此没有问题,那就太好了!如果您愿意,您绝对可以这样做,因为它也具有更简单的语法。希望这可以帮助。
假设给定日期,月份和年份,则可以执行以下操作:
import datetime
DayL = ['Mon','Tues','Wednes','Thurs','Fri','Satur','Sun']
date = DayL[datetime.date(year,month,day).weekday()] + 'day'
#Set day, month, year to your value
#Now, date is set as an actual day, not a number from 0 to 6.
print(date)
strftime("%A")
,而不是weekday()
假设您有timeStamp:字符串变量,YYYY-MM-DD HH:MM:SS
第1步:将其转换为带有打击代码的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模块,那么此功能将起作用。
注意:假定从儒略历到公历的更改发生在1582年。如果对于您感兴趣的日历不正确,则请更改年份> 1582:的行。
def dow(year,month,day):
""" day of week, Sunday = 1, Saturday = 7
http://en.wikipedia.org/wiki/Zeller%27s_congruence """
m, q = month, day
if m == 1:
m = 13
year -= 1
elif m == 2:
m = 14
year -= 1
K = year % 100
J = year // 100
f = (q + int(13*(m + 1)/5.0) + K + int(K/4.0))
fg = f + int(J/4.0) - 2 * J
fj = f + 5 - J
if year > 1582:
h = fg % 7
else:
h = fj % 7
if h == 0:
h = 7
return h
fg
和fj
,以防止不必要的计算。
如果您不仅仅依赖于datetime
模块,则calendar
可能是更好的选择。例如,这将为您提供日期代码:
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 pandas as pd
如上所述,在问题中,我们有:
datetime(2017, 10, 20)
如果在jupyter笔记本中执行此行,我们将得到如下输出:
datetime.datetime(2017, 10, 20, 0, 0)
使用weekday()和weekday_name:
如果您希望工作日为整数格式,请使用:
pd.to_datetime(datetime(2017, 10, 20)).weekday()
输出将是:
4
而且,如果您希望将其作为星期天,星期一,星期五等天的名称,则可以使用:
pd.to_datetime(datetime(2017, 10, 20)).weekday_name
输出将是:
'Friday'
如果在Pandas数据框中具有日期列,则:
现在假设您有一个熊猫数据框,其日期列如下所示:pdExampleDataFrame ['Dates']。head(5)
0 2010-04-01
1 2010-04-02
2 2010-04-03
3 2010-04-04
4 2010-04-05
Name: Dates, dtype: datetime64[ns]
现在,如果我们想知道星期一,星期二,.. etc等工作日的名称,可以使用.weekday_name
以下方法:
pdExampleDataFrame.head(5)['Dates'].dt.weekday_name
输出将是:
0 Thursday
1 Friday
2 Saturday
3 Sunday
4 Monday
Name: Dates, dtype: object
而且,如果我们想从“日期”列中获取工作日的整数,则可以使用:
pdExampleDataFrame.head(5)['Dates'].apply(lambda x: x.weekday())
输出将如下所示:
0 3
1 4
2 5
3 6
4 0
Name: Dates, dtype: int64
要使星期日为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
这是如何将日期列表转换为日期
import datetime,time
ls={'1/1/2007','1/2/2017'}
dt=datetime.datetime.strptime(ls[1], "%m/%d/%Y")
print(dt)
print(dt.month)
print(dt.year)
使用坎伦达模块
import calendar
a=calendar.weekday(year,month,day)
days=["MONDAY","TUESDAY","WEDNESDAY","THURSDAY","FRIDAY","SATURDAY","SUNDAY"]
print(days[a])
这是我的python3实现。
months = {'jan' : 1, 'feb' : 4, 'mar' : 4, 'apr':0, 'may':2, 'jun':5, 'jul':6, 'aug':3, 'sep':6, 'oct':1, 'nov':4, 'dec':6}
dates = {'Sunday':1, 'Monday':2, 'Tuesday':3, 'Wednesday':4, 'Thursday':5, 'Friday':6, 'Saterday':0}
ranges = {'1800-1899':2, '1900-1999':0, '2000-2099':6, '2100-2199':4, '2200-2299':2}
def getValue(val, dic):
if(len(val)==4):
for k,v in dic.items():
x,y=int(k.split('-')[0]),int(k.split('-')[1])
val = int(val)
if(val>=x and val<=y):
return v
else:
return dic[val]
def getDate(val):
return (list(dates.keys())[list(dates.values()).index(val)])
def main(myDate):
dateArray = myDate.split('-')
# print(dateArray)
date,month,year = dateArray[2],dateArray[1],dateArray[0]
# print(date,month,year)
date = int(date)
month_v = getValue(month, months)
year_2 = int(year[2:])
div = year_2//4
year_v = getValue(year, ranges)
sumAll = date+month_v+year_2+div+year_v
val = (sumAll)%7
str_date = getDate(val)
print('{} is a {}.'.format(myDate, str_date))
if __name__ == "__main__":
testDate = '2018-mar-4'
main(testDate)
使用此代码:
import pandas as pd
from datetime import datetime
print(pd.DatetimeIndex(df['give_date']).day)
将numpy导入为np
def date(df):
df['weekday'] = df['date'].dt.day_name()
conditions = [(df['weekday'] == 'Sunday'),
(df['weekday'] == 'Monday'),
(df['weekday'] == 'Tuesday'),
(df['weekday'] == 'Wednesday'),
(df['weekday'] == 'Thursday'),
(df['weekday'] == 'Friday'),
(df['weekday'] == 'Saturday')]
choices = [0, 1, 2, 3, 4, 5, 6]
df['week'] = np.select(conditions, choices)
return df