寫一個計算年齡的程式:
from datetime import datetime dob = input("Enter your Date of Birth (yyyy-mm-dd): ") dob_date = datetime.strptime(dob, "%Y-%m-%d") print(dob_date) current_date = datetime.now() age = current_date.year - dob_date.year print(f"Your age is {age}")
datetime.now() -datetime.now() 是 Python 的 datetime 模組中的函數,它以 datetime 物件的形式傳回目前本機日期和時間,包括微秒。
strptime() - Python 中的 strptime() 方法用於將表示日期和/或時間的字串解析(轉換)為日期時間物件。它是日期時間模組的一部分。
Enter your Date of Birth (yyyy-mm-dd): 1993-03-26 1993-03-26 00:00:00 Your age is 31
另一個方法:
如果結果為負數,請使用此方法
from datetime import date birth_year = 1993 birth_month = 3 birth_day = 26 today = date.today() year = today.year - birth_year month = today.month - birth_month days = today.day - birth_day if month<0: year = year - 1 month = 12+month if days<0: month=month-1 days = 30 + days print (f"You are {year} Years {month} Months {days} Days Old")
You are 31 Years 7 Months 29 Days Old
使用relativedelta的替代方法:
from datetime import datetime from dateutil.relativedelta import relativedelta dob = input("Enter date of birth in yyyy-mm-dd format: ") dob_date = datetime.strptime(dob, "%Y-%m-%d") today = datetime.now() difference = relativedelta(today, dob_date) print(difference.years, " Years ", difference.months, " Months ", difference.days, " days")
relativedelta 是 Python 中 dateutil 模組的一部分,它提供了比標準函式庫的 timedelta 更強大的日期和時間操作操作。它允許您執行諸如添加或減去月份和年份之類的操作,而 timedelta 無法直接處理這些操作。
Enter date of birth in yyyy-mm-dd format: 1993-03-26 31 Years 7 Months 30 days
while 循環的一些例子:
no = 1 while no<=5: print(no, end=' ') no+=1
1 1 1 1 1
no = 1 while no<=10: print(no, end=' ') no+=1
1 2 3 4 5 6 7 8 9 10
no = 10 while no>=1: print(no, end=' ') no-=1
10 9 8 7 6 5 4 3 2 1
no = 1 while no<=10: print(no, end=' ') no+=2
1 3 5 7 9
no=2 while no<=10: print(no, end=' ') no+=2
2 4 6 8 10
no = 3 while no<=10: print(no, end=' ') no+=3
3 6 9
no = 1 total = 0 while no<=5: total = total + no no+=1 print(total)
15
no = 1 while no<=5: print(no*3, end=' ') no+=1
3 6 9 12 15
no = 1 while no<=10: print(no,"*5=",no*5, end='\n') no+=1
1 *5= 5 2 *5= 10 3 *5= 15 4 *5= 20 5 *5= 25 6 *5= 30 7 *5= 35 8 *5= 40 9 *5= 45 10 *5= 50
no = 1 while no<=10: print(no, end = ' ') if no==9: no = 0 no+=2
1 3 5 7 9 2 4 6 8 10
以上是日 - 循環的詳細內容。更多資訊請關注PHP中文網其他相關文章!