一、输入日期, 判断这一天是这一年的第几天?
import datetime
def dayofyear():
year = input("请输入年份: ")
month = input("请输入月份: ")
day = input("请输入天: ")
date1 = datetime.date(year=int(year),month=int(month),day=int(day))
date2 = datetime.date(year=int(year),month=1,day=1)
return (date1-date2).days+1
二、怎么实现时间的加减计算?
保证都是同一个类型才能加减,要么都是datetime,date
基于年,月,天,小时,分钟,秒,毫秒的加减计算?
需求:从现在开始,两天之后,两个月之后,一年之后分别对于的时间是?
1、timedelta
2、dateutil.relativedelta
from datetime import timedelta,datetime
from time import strftime
from dateutil.relativedelta import relativedelta
now_day=datetime.today()
print(now_day)
#todo 5分钟后的日期
min_day=now_day+timedelta(minutes=5)
print(min_day)
#todo 5小时后的日期
hour_5=now_day+timedelta(hours=5)
print(hour_5)
#todo 5周后的日期
week_5=now_day+timedelta(weeks=5)
print(week_5)
#todo 5天后的日期
day_5=now_day+timedelta(days=5)
print(day_5)
#todo 7个月后的日期
month_7=now_day+relativedelta(months=7)
print(month_7)
#todo 5年后的日期
year_5=now_day+relativedelta(years=5)
print(year_5)
执行结果:
2022-08-02 21:25:53.817425
2022-08-02 21:30:53.817425
2022-08-03 02:25:53.817425
2022-09-06 21:25:53.817425
2022-08-07 21:25:53.817425
2023-03-02 21:25:53.817425
2027-08-02 21:25:53.817425
特别注意:dateutil的安装方式为:pip3 install python-dateutil
pip3 install python-dateutil
三、计算上一个周五的日期
from datetime import datetime, timedelta
weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
def get_previous_byday(dayname, start_date=None):
if start_date is None:
start_date = datetime.today()
day_num = start_date.weekday() #是属于一周的第几天,计数从0开始
day_num_target = weekdays.index(dayname) #上周的第几天
days_ago = 7 + day_num - day_num_target #相差的时间
if days_ago == 0:
days_ago = 7
target_date = start_date - timedelta(days=days_ago)
return target_date
print(get_previous_byday('Wednesday'))