python时间换算
时间: 2023-11-28 10:45:38 浏览: 72
以下是Python中常用的时间换算方法:
1. 将时间戳转换为时间元组
```python
import time
timestamp = 1626840000
time_tuple = time.localtime(timestamp)
print(time_tuple) # 输出:time.struct_time(tm_year=2021, tm_mon=7, tm_mday=21, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=2, tm_yday=202, tm_isdst=0)
```
2. 将时间元组转换为时间戳
```python
import time
time_tuple = (2021, 7, 21, 0, 0, 0, 2, 202, 0)
timestamp = time.mktime(time_tuple)
print(int(timestamp)) # 输出:1626840000
```
3. 将时间元组转换为指定格式的字符串
```python
import time
time_tuple = (2021, 7, 21, 0, 0, 0, 2, 202, 0)
time_str = time.strftime("%Y-%m-%d %H:%M:%S", time_tuple)
print(time_str) # 输出:2021-07-21 00:00:00
```
4. 将指定格式的字符串转换为时间元组
```python
import time
time_str = "2021-07-21 00:00:00"
time_tuple = time.strptime(time_str, "%Y-%m-%d %H:%M:%S")
print(time_tuple) # 输出:time.struct_time(tm_year=2021, tm_mon=7, tm_mday=21, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=2, tm_yday=202, tm_isdst=-1)
```
阅读全文