python获取时间
时间: 2023-07-01 22:21:05 浏览: 50
可以使用Python中的datetime模块来获取当前时间。以下是获取当前时间的示例代码:
```python
import datetime
now = datetime.datetime.now()
print("当前时间:")
print(now)
```
输出结果为:
```
当前时间:
2021-09-28 16:20:30.581789
```
你还可以使用strftime()方法来格式化时间,以适应你的需要。例如,以下代码将当前时间格式化为年-月-日 时:分:秒的形式:
```python
import datetime
now = datetime.datetime.now()
formatted_time = now.strftime("%Y-%m-%d %H:%M:%S")
print("当前时间:")
print(formatted_time)
```
输出结果为:
```
当前时间:
2021-09-28 16:20:30
```
相关问题
Python获取时间
以下是两种Python获取当前时间的方法:
1. 使用datetime模块获取当前时间:
```python
import datetime
current_time = datetime.datetime.now()
print("当前时间:", current_time)
```
2. 使用time模块获取当前时间的时间戳和可读格式:
```python
import time
# 获取当前时间的时间戳
timestamp = time.time()
# 将时间戳转换为可读格式
current_time = time.ctime(timestamp)
print("当前时间:", current_time)
```
python 获取时间
你可以使用 Python 中的 datetime 模块来获取时间。以下是获取当前时间的示例代码:
```python
import datetime
current_time = datetime.datetime.now()
print("当前时间为:", current_time)
```
你也可以使用 strftime() 方法来格式化时间,例如:
```python
import datetime
current_time = datetime.datetime.now()
formatted_time = current_time.strftime("%Y-%m-%d %H:%M:%S")
print("当前时间为:", formatted_time)
```
这将输出当前时间的格式化字符串,如 "2022-01-01 12:00:00"。