Python 取得系統當前時間

本篇 ShengYu 將介紹如何使用 Python 取得系統當前時間,可以使用 python 的 time 模組或者 datetime 模組,
這兩種取得系統當前時間的使用方式在本篇都會介紹到。

使用 time 得到系統當前時間

以下範例是一個不斷地印出系統時間的範例,
使用 time.localtime() 來取得本地時間,再將本地時間轉換成想要的格式,最後再列印出來。

Python-get-current-time-and-date.py
1
2
3
4
5
6
7
8
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import time
while True:
localtime = time.localtime()
result = time.strftime("%Y-%m-%d %I:%M:%S %p", localtime)
print(result)
time.sleep(1)

輸出如下:

1
2
3
4
5
6
7
2019-10-11 10:24:13 PM
2019-10-11 10:24:14 PM
2019-10-11 10:24:15 PM
2019-10-11 10:24:16 PM
2019-10-11 10:24:17 PM
2019-10-11 10:24:18 PM
... .. ...

如果要顯示 24 小時制的話,可以把 %I 12 小時制改成 %H 24 小時制。

strftime 常用的格式化字串

以下為 strftime 常用的格式化字串,

格式化符號 說明
%Y 四位數的年份(000-9999)
%y 兩位數的年份(00-99)
%m 月(01-12)
%d 日(01-31)
%H 24 小時制的小時(00-23)
%I 12 小時制的小時(01-12)
%M 分鐘(00-59)
%S 秒(00-59)
%p AM 或 PM

使用 datetime 得到系統當前時間

使用 datetime 模組也可以取得系統當前時間,
直接用 datetime.now() 取得當前系統日期與時間後,再用 strftime 來格式化成字串,

Python-get-current-time-and-date2.py
1
2
3
4
5
6
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from datetime import datetime

result = datetime.now().strftime("%Y-%m-%d %H:%M:%S %p")
print(result)

輸出如下:

1
2019-10-11 22:39:33 PM

參考
Python 中如何得到當前時間 | D棧 - Delft Stack
https://www.delftstack.com/zh-tw/howto/python/how-to-get-the-current-time-in-python/
Python time strftime() 方法 | 菜鸟教程
https://www.runoob.com/python/att-time-strftime.html

其它相關文章推薦
C++ 取得系統當前時間
如果你想學習 Python 相關技術,可以參考看看下面的文章,
Python 新手入門教學懶人包
Python 計算程式執行時間
Python 讓程式 sleep 延遲暫停時間
Python str 字串用法與範例
Python list 串列用法與範例
Python set 集合用法與範例
Python dict 字典用法與範例
Python tuple 元組用法與範例
Python 讀檔,讀取 txt 文字檔
Python 字串分割 split
Python 取代字元或取代字串 replace
Python 讓程式 sleep 延遲暫停時間
Python PIL 讀取圖片並顯示
Python OpenCV resize 圖片縮放