Python 的日期

在 Python 處理日期與時間

Max Shron

Data Scientist and Author

課程總覽

  • 第 1 章:日期與行事曆
  • 第 2 章:結合日期與時間
  • 第 3 章:時區與日光節約
  • 第 4 章:Pandas 中的日期與時間
在 Python 處理日期與時間

Python 的日期

在 Python 處理日期與時間

為什麼需要 Python 的日期類別?

two_hurricanes = ["10/7/2016", "6/21/2017"]

你要怎麼:

  • 算出間隔了多少天?
  • 檢查是否已依時間先後排序?
  • 知道各自是星期幾?
  • 篩選出發生在特定日期區間的颶風?
在 Python 處理日期與時間

建立 date 物件

# Import date
from datetime import date

# Create dates two_hurricanes_dates = [date(2016, 10, 7), date(2017, 6, 21)]
在 Python 處理日期與時間

date 的屬性

# Import date
from datetime import date

# Create dates
two_hurricanes_dates = [date(2016, 10, 7), date(2017, 6, 21)]

print(two_hurricanes_dates[0].year) print(two_hurricanes_dates[0].month) print(two_hurricanes_dates[0].day)
2016
10
7
在 Python 處理日期與時間

找出日期是星期幾

print(two_hurricanes_dates[0].weekday())
4
  • Python 的星期編碼:
    • 0 = Monday(星期一)
    • 1 = Tuesday(星期二)
    • 2 = Wednesday(星期三)
    • ...
    • 6 = Sunday(星期日)
在 Python 處理日期與時間

Python 的日期

在 Python 處理日期與時間

Preparing Video For Download...