33.md 2.3 KB
Newer Older
W
init  
wizardforcel 已提交
1 2 3 4
# 时间和日期

> 原文: [https://pythonbasics.org/time-and-date/](https://pythonbasics.org/time-and-date/)

W
wizardforcel 已提交
5
Python 可以使用模块`time`获得系统时间。`time`属于标准库。 您可以通过输入`import time`加载此模块。
W
init  
wizardforcel 已提交
6

W
wizardforcel 已提交
7
时间模块具有各种与时间相关的函数。 并非所有函数都存在于所有操作系统上。
W
init  
wizardforcel 已提交
8 9 10

时间模块从 1970 年 1 月 1 日开始。

W
wizardforcel 已提交
11

W
init  
wizardforcel 已提交
12

W
wizardforcel 已提交
13
## 示例
W
init  
wizardforcel 已提交
14 15 16 17 18 19 20

### 当前时间

在下面的示例中,我们输出日,月和年,后跟当前时间。

第一行返回所有必需的变量(年,月,日,小时,分钟)。

W
wizardforcel 已提交
21
```py
W
init  
wizardforcel 已提交
22 23 24 25
timenow = time.localtime(time.time())

```

W
wizardforcel 已提交
26
函数`time.time()`返回时间戳。 时间戳是每台计算机持有的系统时间戳。
W
init  
wizardforcel 已提交
27

W
wizardforcel 已提交
28
```py
W
init  
wizardforcel 已提交
29 30 31 32
timenow = time.localtime(time.time())

```

W
wizardforcel 已提交
33
作为人类,我们不阅读系统时间戳,因此需要将其转换为实际人类时间。函数`localtime()`将这些转换为实际的人类可读值。
W
init  
wizardforcel 已提交
34

W
wizardforcel 已提交
35
```py
W
init  
wizardforcel 已提交
36 37 38 39 40 41
year,month,day,hour,minute = timenow[0:5]

```

转换为:

W
wizardforcel 已提交
42
```py
W
init  
wizardforcel 已提交
43 44 45 46
timenow = time.localtime(time.time())

```

W
wizardforcel 已提交
47
键入下面显示的程序并运行它:
W
init  
wizardforcel 已提交
48

W
wizardforcel 已提交
49
```py
W
init  
wizardforcel 已提交
50 51 52 53 54 55 56 57 58 59 60 61
import time

timenow = time.localtime(time.time())
year,month,day,hour,minute = timenow[0:5]

print(str(day) + "/" + str(month) + "/" + str(year))
print(str(hour) + ":" + str(minute))

```

### 纪元时间

W
wizardforcel 已提交
62
您如何获得自纪元以来的秒数?`time()`方法将为您提供:
W
init  
wizardforcel 已提交
63

W
wizardforcel 已提交
64
```py
W
init  
wizardforcel 已提交
65 66 67 68 69 70 71 72 73 74 75
>>> import time
>>> time.time()
1563018526.7016013
>>> time.time()
1563018527.5820937
>>> 

```

要获取时间序列,请调用`time.gmtime()`

W
wizardforcel 已提交
76
```py
W
init  
wizardforcel 已提交
77 78 79 80 81 82 83
>>> time.gmtime()
time.struct_time(tm_year=2019, tm_mon=7, tm_mday=13, tm_hour=11, tm_min=49, tm_sec=39, tm_wday=5, tm_yday=194, tm_isdst=0)

```

### 字符串时间

W
wizardforcel 已提交
84
方法`asctime()``ctime()`返回 24 个字符串。 没有参数,它将获取当前时间。
W
init  
wizardforcel 已提交
85

W
wizardforcel 已提交
86
```py
W
init  
wizardforcel 已提交
87 88 89 90 91 92 93 94 95 96
>>> time.asctime()
'Sat Jul 13 13:53:00 2019'
>>> time.ctime()
'Sat Jul 13 13:53:01 2019'
>>>

```

### 睡眠

W
wizardforcel 已提交
97
您可以使程序等待。 该程序只会等待,不会执行任何操作。 睡眠函数使您可以执行此操作。
W
init  
wizardforcel 已提交
98

W
wizardforcel 已提交
99
```py
W
init  
wizardforcel 已提交
100 101 102 103 104 105 106 107 108 109 110 111 112
import time

print("Hello")
time.sleep(1)
print("World")
time.sleep(1)

```

## 练习

试试下面的练习

W
wizardforcel 已提交
113
1.  以“年-月-日”格式打印日期
W
init  
wizardforcel 已提交
114 115 116 117

完成这些步骤后,继续下一个练习。

[下载示例](https://gum.co/dcsp)