如何设置日期,如果它是星期一,它将显示星期一的最近日期。
以此类推。
答案 0 :(得分:0)
一个相当冗长的解决方案,因此您可以查看步骤并根据需要轻松进行修改。请注意pandas库的大量使用,这使查找表和进行日期时间操作变得容易。
import pandas as pd
def get_date(dayname):
"""
dayname is a string like 'monday'
returns a string of the most recent date with the corresponding dayname
"""
# get the dates of the pastweek dates (last 7 days)
past_week_dates = pd.date_range(end=pd.datetime.now(), periods=7)
# convert dates to day names
day_names = past_week_dates.day_name().tolist()
# create dataframe for use as lookup table
df = pd.DataFrame(past_week_dates, index=day_names)
# lookup the date of the desired dayname
date = df.loc[dayname.capitalize()]
# convert the date into the desired format
date = list(date.dt.strftime('%d %B %Y'))
return date[0]
用法:
get_date('Tuesday')
# returns '01 January 2019'
get_date('Friday')
# returns '28 December 2018'