Files
ailearning/docs/da/068.md
2020-10-19 21:08:55 +08:00

187 lines
2.5 KiB
Markdown
Raw Permalink Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# datetime 模块
In [1]:
```py
import datetime as dt
```
`datetime` 提供了基础时间和日期的处理。
## date 对象
可以使用 `date(year, month, day)` 产生一个 `date` 对象:
In [2]:
```py
d1 = dt.date(2007, 9, 25)
d2 = dt.date(2008, 9, 25)
```
可以格式化 `date` 对象的输出:
In [3]:
```py
print d1
print d1.strftime('%A, %m/%d/%y')
print d1.strftime('%a, %m-%d-%Y')
```
```py
2007-09-25
Tuesday, 09/25/07
Tue, 09-25-2007
```
可以看两个日期相差多久:
In [4]:
```py
print d2 - d1
```
```py
366 days, 0:00:00
```
返回的是一个 `timedelta` 对象:
In [5]:
```py
d = d2 - d1
print d.days
print d.seconds
```
```py
366
0
```
查看今天的日期:
In [6]:
```py
print dt.date.today()
```
```py
2015-09-10
```
## time 对象
可以使用 `time(hour, min, sec, us)` 产生一个 `time` 对象:
In [7]:
```py
t1 = dt.time(15, 38)
t2 = dt.time(18)
```
改变显示格式:
In [8]:
```py
print t1
print t1.strftime('%I:%M, %p')
print t1.strftime('%H:%M:%S, %p')
```
```py
15:38:00
03:38, PM
15:38:00, PM
```
因为没有具体的日期信息,所以 `time` 对象不支持减法操作。
## datetime 对象
可以使用 `datetime(year, month, day, hr, min, sec, us)` 来创建一个 `datetime` 对象。
获得当前时间:
In [9]:
```py
d1 = dt.datetime.now()
print d1
```
```py
2015-09-10 20:58:50.148000
```
给当前的时间加上 `30` 天,`timedelta` 的参数是 `timedelta(day, hr, min, sec, us)`
In [10]:
```py
d2 = d1 + dt.timedelta(30)
print d2
```
```py
2015-10-10 20:58:50.148000
```
除此之外,我们还可以通过一些指定格式的字符串来创建 `datetime` 对象:
In [11]:
```py
print dt.datetime.strptime('2/10/01', '%m/%d/%y')
```
```py
2001-02-10 00:00:00
```
## datetime 格式字符表
| 字符 | 含义 |
| --- | --- |
| `%a` | 星期英文缩写 |
| `%A` | 星期英文 |
| `%w` | 一星期的第几天,`[0(sun),6]` |
| `%b` | 月份英文缩写 |
| `%B` | 月份英文 |
| `%d` | 日期,`[01,31]` |
| `%H` | 小时,`[00,23]` |
| `%I` | 小时,`[01,12]` |
| `%j` | 一年的第几天,`[001,366]` |
| `%m` | 月份,`[01,12]` |
| `%M` | 分钟,`[00,59]` |
| `%p` | AM 和 PM |
| `%S` | 秒钟,`[00,61]` (大概是有闰秒的存在) |
| `%U` | 一年中的第几个星期,星期日为第一天,`[00,53]` |
| `%W` | 一年中的第几个星期,星期一为第一天,`[00,53]` |
| `%y` | 没有世纪的年份 |
| `%Y` | 完整的年份 |