時間模組練習

2021-09-19 12:40:14 字數 2845 閱讀 4718

給定乙個初始日期,隨意輸入乙個日期,計算兩個日期相差的天數

第一種:自己寫程式實現,不引用datetime包

def trans_date(input_date):

year = int(input_date[0:4])

month = int(input_date[5:7])

day = int(input_date[8:10])

return year, month, day

def leap_year(year):

if year % 400 == 0 or (year % 4 == 0 and year % 100 != 0):

return true

else:

return false

def current_year_days(date):

month_day_dict=

print(date)

year = trans_date(date)[0]

month = trans_date(date)[1]

day = trans_date(date)[2]

count_day=0

if month == 1:

count_day = day

elif month == 2:

count_day = day+31

else:

if leap_year(year):

for i in range(1,month):

if i!=2:

count_day+=month_day_dict[i]

else:

count_day+=29

else:

for i in range(1,month):

count_day+=month_day_dict[i]

count_day+=day

return count_day

init_date = 「1949-10-01」

init_current_year_days = current_year_days(init_date)

#print(init_current_year_days)

init_year = trans_date(init_date)[0]

if leap_year(init_year):

init_year_alldays=366

else:

init_year_alldays=365

input_date = input(「請輸入乙個日期:」)

input_current_year_days = current_year_days(input_date)

#print(input_current_year_days)

input_year = trans_date(input_date)[0]

if leap_year(init_year):

input_year_alldays=366

else:

input_year_alldays=365

interval_day=0

if init_year==input_year:

interval_day=abs(init_current_year_days-input_current_year_days)

elif init_yearinput_year:

interval_day+=init_current_year_days+input_year_alldays-input_current_year_days

for j in range(min(init_year,input_year)+1,max(init_year,input_year)):

if leap_year(j):

interval_day+=366

else:

interval_day += 365

print(「輸入的日期%s與初始日期%s相差%d天」%(input_date,init_date,interval_day))

執行結果:

1949-10-01

請輸入乙個日期:1945-05-01

1945-05-01

輸入的日期1945-05-01與初始日期1949-10-01相差1614天

1949-10-01

請輸入乙個日期:1948-09-02

1948-09-02

輸入的日期1948-09-02與初始日期1949-10-01相差393天

1949-10-01

請輸入乙個日期:1949-05-30

1949-05-30

輸入的日期1949-05-30與初始日期1949-10-01相差124天

1949-10-01

請輸入乙個日期:1949-12-30

1949-12-30

輸入的日期1949-12-30與初始日期1949-10-01相差90天

1949-10-01

請輸入乙個日期:1950-05-30

1950-05-30

輸入的日期1950-05-30與初始日期1949-10-01相差241天

1949-10-01

請輸入乙個日期:2018-10-29

2018-10-29

輸入的日期2018-10-29與初始日期1949-10-01相差25230天

2)第二種使用datetime包

import datetime

t1=datetime.date(1949,10,1)

t2=datetime.date(2018,10,29)

print((t2-t1).days)

執行結果:

時間模組練習

需求 1.獲取當前主機資訊,包含作業系統名,主機名,核心版本,硬體架構等 2.獲取開機時間和開機時長 3.獲取當前登陸使用者 可以實現獲取系統執行的程序和系統利用率 psutil.boot time 獲取開機時間 psutil.users 獲取當前系統使用者登入資訊 import os import...

搶紅包和時間模組練習

保證每個人搶紅包,搶到的所有的金額的概率相同 import random defrand num ran random.sample range 20000 num 1 隨機生成9個數 ran.sort ran.insert 0,0 在下標為0的位置,增加乙個數字0 for i in range l...

Python標準庫模組 時間練習

1 import time23 4 時間戳 從1970年後經過的秒數 5print time.time 6 1558538588.716879878 時間戳 時間元組9 年 月 日 時 分 秒 星期 周一0 周二1 週日6 一年的第幾天 夏令時 10 tuple time time.localtim...