Python日期转换时间戳
时间: 2023-12-14 19:33:19 浏览: 94
以下是两种Python日期转换时间戳的方法:
1. 使用time模块实现
```python
import time
# 将日期转换为时间戳
date = '2022-01-27 12:00:00'
timeStamp = int(time.mktime(time.strptime(date, '%Y-%m-%d %H:%M:%S')))
print(timeStamp) # 输出:1643270400
# 将时间戳转换为日期
timeStamp = 1643270400
dateArray = time.localtime(timeStamp)
date = time.strftime('%Y-%m-%d %H:%M:%S', dateArray)
print(date) # 输出:2022-01-27 12:00:00
```
2. 使用datetime模块实现
```python
import datetime
# 将日期转换为时间戳
date = '2022-01-27 12:00:00'
timeStamp = int(datetime.datetime.strptime(date, '%Y-%m-%d %H:%M:%S').timestamp())
print(timeStamp) # 输出:1643270400
# 将时间戳转换为日期
timeStamp = 1643270400
dateArray = datetime.datetime.fromtimestamp(timeStamp)
date = dateArray.strftime('%Y-%m-%d %H:%M:%S')
print(date) # 输出:2022-01-27 12:00:00
```
阅读全文