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
基於年,月,天,小時,分鐘,秒,毫秒的加減計算?
需求:從現在開始,兩天之後,兩個月之後,一年之後分別對於的時間是?
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
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 % 7 #相差的時間
if days_ago == 0:
days_ago = 7
target_date = start_date - timedelta(days=days_ago)
return target_date
print(get_previous_byday('Wednesday'))