無論是日常生活還是工作中,我們都會頻繁地需要獲取當前時間。Python 作為一種廣泛應用的編程語言,提供了多種方法來獲取當前時間。本文將從多個角度詳細介紹在 Python 中如何獲取當前時間,並提供相應的代碼示例。
一、Python 內置模塊——datetime
Python 標準庫中自帶了 datetime 模塊,可以方便地獲取當前時間和日期。
1、獲取當前時間的日期和時間信息
import datetime
now = datetime.datetime.now()
print("當前時間:", now)
print("年份:", now.year)
print("月份:", now.month)
print("日期:", now.day)
print("小時:", now.hour)
print("分鐘:", now.minute)
print("秒數:", now.second)
2、將時間格式化為字符串
import datetime
now = datetime.datetime.now()
# %Y 表示四位數的年份,例如:2021
# %m 表示兩位數的月份,例如:08
# %d 表示兩位數的日期,例如:15
# %H 表示兩位數的小時,例如:18
# %M 表示兩位數的分鐘,例如:23
# %S 表示兩位數的秒數,例如:45
time_str = now.strftime("%Y-%m-%d %H:%M:%S")
print("格式化後的時間:", time_str)
二、Python 內置模塊——time
與 datetime 模塊類似,Python 中還有一個 time 模塊可以用來獲取當前時間。與 datetime 不同的是,time 模塊返回的是從 1970 年 1 月 1 日 00:00:00 開始計算的秒數,也被稱為 Unix 時間戳。
1、獲取當前時間的 Unix 時間戳
import time
timestamp = time.time()
print("當前時間的 Unix 時間戳為:", timestamp)
2、將時間戳轉換為時間格式
import time
timestamp = time.time()
# 將時間戳轉換為 struct_time 格式
time_tuple = time.localtime(timestamp)
# 將 struct_time 格式的時間轉換為字符串格式
time_str = time.strftime("%Y-%m-%d %H:%M:%S", time_tuple)
print("格式化後的時間:", time_str)
三、第三方庫——arrow
除了 Python 內置模塊外,還有一些第三方庫可以方便地進行時間處理。其中最受歡迎的是 arrow,它提供了更加方便的 API 來進行時間操作。
1、獲取當前時間
import arrow
now = arrow.now()
print("當前時間:", now)
2、將時間轉換為指定格式的字符串
import arrow
now = arrow.now()
time_str = now.format("YYYY年MM月DD日 HH:mm:ss")
print("格式化後的時間:", time_str)
3、進行時間計算
import arrow
now = arrow.now()
# 向前推 2 天
two_days_ago = now.shift(days=-2)
print("兩天前的時間:", two_days_ago)
# 向後推 3 小時
three_hours_later = now.shift(hours=3)
print("三小時後的時間:", three_hours_later)
# 計算兩個時間之間的差
diff = three_hours_later - two_days_ago
print("兩個時間之間的差為:", diff)
總結:
Python 提供了多種方法來獲取當前時間,其中 datetime 和 time 是 Python 內置的模塊,使用起來比較簡單,但是靈活性和擴展性較差。而第三方庫 arrow 提供了更加強大和方便的 API,可以幫助開發人員更好地進行時間操作。選擇哪種方法,可以根據項目需求、開發經驗和個人偏好來決定。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/271394.html