輸出與解析 datetime

在 Python 處理日期與時間

Max Shron

Data Scientist and Author

輸出 datetime

# 建立 datetime
dt = datetime(2017, 12, 30, 15, 19, 13)

print(dt.strftime("%Y-%m-%d"))
2017-12-30
print(dt.strftime("%Y-%m-%d %H:%M:%S"))
2017-12-30 15:19:13
在 Python 處理日期與時間

輸出 datetime

print(dt.strftime("%H:%M:%S on %Y/%m/%d/"))
15:19:13 on 2017/12/30
在 Python 處理日期與時間

ISO 8601 格式

# ISO 8601 格式
print(dt.isoformat())
2017-12-30T15:19:13
在 Python 處理日期與時間

用 strptime 解析 datetime

# 匯入 datetime
from datetime import datetime
在 Python 處理日期與時間

用 strptime 解析 datetime

# 匯入 datetime
from datetime import datetime

dt = datetime.strptime(
在 Python 處理日期與時間

用 strptime 解析 datetime

# 匯入 datetime
from datetime import datetime

dt = datetime.strptime("12/30/2017 15:19:13"
在 Python 處理日期與時間

用 strptime 解析 datetime

# 匯入 datetime
from datetime import datetime

dt = datetime.strptime("12/30/2017 15:19:13", 
                       "%m/%d/%Y %H:%M:%S")
在 Python 處理日期與時間

用 strptime 解析 datetime

# 我們建立了什麼?
print(type(dt))
<class 'datetime.datetime'>
# 列印 datetime 物件
print(dt)
2017-12-30 15:19:13
在 Python 處理日期與時間

用 strptime 解析 datetime

# 匯入 datetime
from datetime import datetime

# 錯誤的格式字串
dt = datetime.strptime("2017-12-30 15:19:13", "%Y-%m-%d")
ValueError: unconverted data remains:  15:19:13
在 Python 處理日期與時間

用 Python 解析 datetime

# 一個時間戳記
ts = 1514665153.0

# 轉為 datetime 並列印 print(datetime.fromtimestamp(ts))
2017-12-30 15:19:13
在 Python 處理日期與時間

輸出與解析 datetime

在 Python 處理日期與時間

Preparing Video For Download...