[TOC]
<br>
### time & datetime 模塊
time模塊,提供各種函數來操作時間值
datetime模塊,提供各種函數來操作日期值
```python
import time
import datetime
```
#### case1:獲取當前時間并轉換為指定日期格式,如"2018-07-07 22:03:19"
```python
# 獲得當前時間時間戳,如 1530972062
timeStamp = int(time.time())
# 返回 struct time 對象
timeArray = time.localtime(timeStamp)
# 返回格式化時間如:2018-07-07 22:01:02
print(time.strftime("%Y-%m-%d %H:%M:%S", timeArray))
# 返回格式化時間如:2018-07-07 22:03:19
print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
```
#### case2:將字符串的時間轉換為時間戳
```python
now = "2018-07-07 22:01:02"
# 返回 struct_time 對象
timeArray = time.strptime(now, "%Y-%m-%d %H:%M:%S")
# 返回時間戳:1530972062
timeStamp = int(time.mktime(timeArray))
```
#### case3:獲取當前時間并轉換為指定日期格式,如"2018-07-07 22:07:46"
```python
now = datetime.datetime.now()
# 返回格式化日期格式 '2018-07-07 22:07:46'
print(now.strftime("%Y-%m-%d %H:%M:%S"))
```
#### case4:時間戳直接轉成日期格式 2018-07-07
```python
print(datetime.date.fromtimestamp(time.time())) # 2018-07-07
```
#### case5:獲得三天前時間
```python
# datetime.datetime(2018, 7, 4, 22, 9, 45, 791649)
threeDayAgo = (datetime.datetime.now() - datetime.timedelta(days=3))
# 轉換為時間戳 1530713385
timeStamp = int(time.mktime(threeDayAgo.timetuple()))
# 轉為其他字符串格式 '2018-07-04 22:09:45'
otherStyleTime = threeDayAgo.strftime("%Y-%m-%d %H:%M:%S")
```
### 時間轉換過程

<hr style="margin-top:100px">
:-: 
***微信掃一掃,關注“python測試開發圈”,了解更多測試教程!***
- 前言
- chapter01_開發環境
- chapter02_字符串的使用
- chapter03_列表的使用
- chapter04_字典的使用
- chapter05_數字的使用
- chapter06_元組的使用
- chapter07_集合的使用
- chapter08_輸入輸出
- chapter09_控制流程
- chapter10_實例練習_登錄1
- chapter11_python函數入門
- chapter12_python中的類
- chapter13_輕松玩轉python中的模塊管理
- chapter14_掌握學習新模塊的技巧
- chapter15_通過os模塊與操作系統交互
- chapter16_子進程相關模塊(subprocess)
- chapter17_時間相關模塊(time & datetime)
- chapter18_序列化模塊(json)
- chapter19_加密模塊(hashlib)
- chapter20_文件的讀與寫
- chapter21_階段考核2_登錄
- chapter22_小小算法挑戰(排序&二分法)
- chapter23_用多線程來搞事!
- chapter24_HTTP接口請求(requests)
- chapter25_接口測試框架(pytest)
- chapter26_階段考核3_HTTP接口測試
- chapter27_HTML解析(pyquery)
- chapter28_階段考核4_爬蟲下載網易汽車
- chapter29_python中的那些編碼坑
- chapter30_MySQL數據庫操作
- chapter31 高級特性_迭代器與生成器
- chapter32 高級特性_裝飾器
- chapter33 高級特性_列表處理