2

Python 的日期时间 datetime 库

 3 years ago
source link: https://zhiqiang.org/coding/python-datetime.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

datetime 是 Python 的标准库:

import datetime

1. 日期和时间对象

包含下面三个类:

  • datetime.date 日期,包含 year, month, day 三个成员。
  • datetime.time 时间,包含 hour, minute, second, microsecond, tzinfo (时区)。
  • datetime.datetime 日期和时间的复合体。

注意这三类实例都是不可变对象,即自身是不能被修改的,要想修改只能生成新的对象。比如 datetime.date 可以简单理解为(year, month, day) 的不可变三元组。

1.1. 直接初始化

date = datetime.date(2020, 11, 12)
time = datetime.time(1, 2, 59)
datetime = datetime.datetime(2020, 11, 12, 1, 2, 59)

1.2. 其它共同初始化函数

下面这几个可同时作用在三个类上:

  • today()
  • now()
  • fromtimestampe(timestamp), timestamp 是秒时间撮。
  • fromordinal(index), index 是序号,公元 1 年 1 月 1 日为 1 ,每过一天增加 1。
  • fromisoformat("2020-11-12 01:02:59.123")

1.3. 互相之间转换函数

下面 dt 表示为一个 datetime.datetime 对象, d 表示为 datetime.date 对象, t 为 datetime.time 对象。

  • d = dt.date()
  • t = dt.time()
  • dt = datetime.datetime.combine(d, t)

1.4. 其它一些函数

1.5. 修改

注意所有修改都返回新的对象,原对象是不可变对象。

date = date.repleace("day", 12)

1.6. 与字符串的转换 - 格式化和反格式化

主要是 strptime 和 strftime ,在 date, time, datetime 里都有。

date = datetime.date.strptime("2020-1112", "%Y-%m-%d")
date.strftime("%Y-%m-%d %H-%M-%S")

其中常用格式控制符:%Y (四位数年份)、%y (两位数年份)、%m (两位数月份)、%d (两位数日)、%H (两位数 24 禁止小时数)、%M (两位数的分钟)、%S (两位数的秒数)%f (六位数微妙)

然后一个通用格式函数为:

  • isoformat(),等价于 strftime("%Y-%m-%d %H:%M:%s.%f")。

2. 日期时间操作 - 加减法

2.1. datetime.timedelta 对象

datetime.timedelta 表示两个 datetime 之间差,在内部表示上,为一个(days, seconds, microseconds)的三元组,可以通过 days, seconds, microseconds 获取到成员值(只读)。另外可以通过 total_seconds() 函数获取到总秒数。

它可以直接初始化:

def datetime.timedelta(days=0, seconds=0, microseconds=0, 
                       milliseconds=0, minutes=0, hours=0, weeks=0):
    pass 

two_day = datetime.timedelta(days=2)

但更多的时候作为两个日期或时间之间的差:

td = d1 - d2;
td = t1 - t2;
td = dt1 - dt2;

注意 date 和 time 之间的减法是非法的!

2.2. 调整时间日期

有了 timedelta ,就可以很方便地调整时间和日期对象了,但仍需注意,必须使用返回值:

d = datetime.date.today()
d = d + datetime.timedelta(days=100)

dt = datetime.datetime.now()
dt -= datetime.timedelta(weeks=2, minutes=60)

Q. E. D.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK