我想了解以下内容:给定一个日期(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 pandas as pd
from datetime import datetime
print(pd.DatetimeIndex(df['give_date']).day)
其他回答
这是我的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)
以下是如何将小端字符串日期列表转换为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"))
在MATLAB中,高斯方法
day_name={'Sun','Mon','Tue','Wed','Thu','Fri','Sat'}
month_offset=[0 3 3 6 1 4 6 2 5 0 3 5]; % common year
% input date
y1=2022
m1=11
d1=22
% is y1 leap
if mod(y1,4)==0 && mod(y1,100)==0 && mod(y1,400)==0
month_offset=[0 3 4 0 2 5 0 3 6 1 4 6]; % offset for leap year
end
% Gregorian calendar
weekday_gregor=rem( d1+month_offset(m1) + 5*rem(y1-1,4) + 4*rem(y1-1,100) + 6*rem(y1-1,400),7)
day_name{weekday_gregor+1}
0:星期日1:星期一。。6:星期六
import numpy as 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
import datetime
int(datetime.datetime.today().strftime('%w'))+1
这应该会给你一个真实的数字-1=星期天,2=星期一,等等。。。