python 時間模組

2021-09-25 08:35:30 字數 3377 閱讀 2327

import os

import time

s = '2019-7-14'

print(time.strptime(s,'%y-%m-%d'))

s_time = '09:00:00'

print(time.strptime(s_time,'%h:%m:%s'))

#把元組的時間轉換為時間戳

tuple_time = time.localtime() #元組時間為本地時間

print(tuple_time)

print(time.mktime(tuple_time))

#把元組時間轉換為字串時間

print(time.strftime('%m-%d',tuple_time))

print(time.strftime('%y-%m-%d',tuple_time))

print(time.strftime('%f',tuple_time))

print(time.strftime('%t',tuple_time))

#把時間戳型別轉換為字串時間

pwd_time = os.path.getctime('/etc/passwd')

print('pwd_time',pwd_time)

print(time.ctime(pwd_time))

#將時間戳轉換為元組

print(time.localtime(pwd_time))

#元組轉換為時間戳

tuple_time = time.localtime()

print(time.mktime(tuple_time))

實驗過程如下:把元組的時間轉換為時間戳

把元組時間轉換為字串時間

把時間戳型別轉換為字串時間

將時間戳轉換為元組/元組轉換為時間戳

#計算幾天前的時間

d = date.today()

delta = timedelta(days=3)

print(d + delta)

print(d - delta)

#計算幾個小時前或後的時間

now_time = datetime.now()

delta = timedelta(hours=2)

print(now_time + delta)

print(now_time - delta)

now_time = datetime.now()

print(now_time)

pwd_time = os.path.getmtime('/etc/passwd')

print(pwd_time)

pwd_time_obj = datetime.fromtimestamp(pwd_time)

print(pwd_time_obj)

delta = now_time - pwd_time_obj

print(delta)

實驗操作如下:

計算三天前的時間

計算兩個小時前或者後的時間

需求:

1.獲取當前主機資訊(作業系統名、主機名、核心版本、硬體架構)

2.獲取開機時間和開機時長

3.獲取當前登入使用者

import os

import psutil

from datetime import datetime

print('主機資訊'.center(50,'*'))

info = os.uname()

# print(info)

print(

"""作業系統:%s

主機名稱:%s

核心版本:%s

硬體架構:%s

""" %(info.sysname,info.nodename,info.release,info.machine)

)print('開機資訊'.center(50,'*'))

boot_time = psutil.boot_time() #返回乙個時間戳

boot_time_obj = datetime.fromtimestamp(boot_time)

# print(boot_time_obj)

#當前時間

now_time = datetime.now()

delta_time = datetime.now()

delta_time1 = now_time - boot_time_obj

print('開機時長:',str(delta_time1).split('.')[0])

print('當前登入使用者'.center(50,'*'))

python 時間模組

格式化時間字串 y 兩位數的年份表示 00 99 y 四位數的年份表示 0000 9999 m 月份 01 12 d 月內的一天 0 31 h 24小時制的小時數 0 23 i 12小時制的小時數 01 12 m 分鐘數 00 59 s 秒 00 59 a 本地簡化星期名稱 a 本地完整星期名稱 b...

python 時間模組

時間的一般表示 import time s 2019 7 14 print time.strptime s,y m d 1.時間戳 print time.time 2.字串時間 print time.ctime 3.元組型別的時間 print time.localtime info time.loc...

python 時間模組

時間表示的幾種形式 1.時間戳 2.字串時間 3.元組型別的時間 import os import time 1.時間戳 print time.time 2.字串時間 print time.ctime 3.元組時間 print time.localtime info time.localtime p...