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 = 周一
    • 1 = 周二
    • 2 = 周三
    • ...
    • 6 = 周日
在 Python 中处理日期和时间

Python 中的日期

在 Python 中处理日期和时间

Preparing Video For Download...