Python时间戳 datetime和字符串相互转化
时间: 2024-12-19 08:24:25 浏览: 20
在Python中,你可以使用`datetime`和`time`模块来进行时间戳与日期字符串的相互转换。
1. **从datetime到时间戳**[^1]:
```python
import datetime
import time
# 定义一个datetime对象
t = datetime.datetime(2014, 12, 6, 12, 10, 10)
# 转换为时间戳(以秒为单位)
timestamp = time.mktime(t.timetuple()) # 或者 time.time() 如果需要微秒精度
print(f"Timestamp from datetime: {timestamp}")
```
2. **从时间戳到datetime**:
```python
# 将时间戳还原为datetime对象
dt_from_timestamp = datetime.datetime.fromtimestamp(timestamp)
print(dt_from_timestamp)
# 或者直接创建datetime对象,假设我们有13位时间戳 (毫秒)
timestamp_ms = timestamp * 1000 # 转换为毫秒
dt_with_millis = datetime.datetime.fromtimestamp(timestamp_ms / 1000)
print(dt_with_millis)
```
3. **时间字符串和时间戳的转换**[^2]:
```python
from datetime import datetime
# 从字符串(如 "2022-01-01 00:00:00")转换为时间戳
str_time = "2022-01-01 00:00:00"
timestamp_str = datetime.strptime(str_time, "%Y-%m-%d %H:%M:%S")
timestamp_str = timestamp_str.timestamp()
# 从时间戳转换为字符串
timestamp = 1641033600 # 假设这是某个时间戳
str_time = datetime.utcfromtimestamp(timestamp).strftime("%Y-%m-%d %H:%M:%S")
print(f"Time string from timestamp: {str_time}")
```
阅读全文