1. 程式人生 > 其它 >速戰速決 Python - python 標準庫: 日期和時間

速戰速決 Python - python 標準庫: 日期和時間

速戰速決 Python - python 標準庫: 日期和時間

速戰速決 Python https://github.com/webabcd/PythonSample
作者 webabcd

速戰速決 Python - python 標準庫: 日期和時間

示例如下:

standardLib/time.py

# 通過 import time, datetime 實現日期和時間

import time, datetime

# datetime 是對 time 的封裝,用起來比較簡單

# 獲取當前本地時間
print(datetime.datetime.now()) # 2022-01-17 16:22:09.279780

# 獲取當前 utc-0 的時間
print(datetime.datetime.utcnow()) # 2022-01-17 08:22:09.279780

# 通過指定年月日時分秒構造 datetime 物件
a = datetime.datetime(2012, 12, 21, 10, 11, 12, 123456)
print(a) # 2012-12-21 10:11:12.123456

# 格式化 datetime 物件
b = a.strftime('%Y-%m-%d %H:%M:%S.%f')
print(b) # 2012-12-21 10:11:12.123456

# 字串轉 datetime 物件
c = datetime.datetime.strptime("2012-12-21 10:11:12.123456", '%Y-%m-%d %H:%M:%S.%f')
print(c) # 2012-12-21 10:11:12.123456


# 距 1970.1.1 的秒數,是一個浮點型
print(time.time()) # 1642406929.1009686

# 獲取當前本地時間,是一個 struct_time 物件
print(time.localtime()) # time.struct_time(tm_year=2022, tm_mon=1, tm_mday=17, tm_hour=16, tm_min=8, tm_sec=49, tm_wday=0, tm_yday=17, tm_isdst=0)

# 獲取當前 GMT 時間,是一個 struct_time 物件
print(time.gmtime()) # time.struct_time(tm_year=2022, tm_mon=1, tm_mday=17, tm_hour=8, tm_min=8, tm_sec=49, tm_wday=0, tm_yday=17, tm_isdst=0)

# 將指定的“距 1970.1.1 的秒數”轉為本地時間,是一個 struct_time 物件
print(time.localtime(1600000000)) # time.struct_time(tm_year=2020, tm_mon=9, tm_mday=13, tm_hour=20, tm_min=26, tm_sec=40, tm_wday=6, tm_yday=257, tm_isdst=0)

# 獲取 struct_time 物件中的資料
print(time.localtime().tm_year) # 2022

# 格式化 struct_time 物件
print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) # 2022-01-17 16:25:42

# 在當前執行緒阻塞指定的秒數
time.sleep(0.1)

# 獲取裝置開機到現在經過的秒數
print(time.perf_counter())


速戰速決 Python https://github.com/webabcd/PythonSample
作者 webabcd