如何在 Python 中获取当前时间?
时间: 2024-06-01 17:05:10 浏览: 18
在 Python 中获取当前时间可以使用 datetime 模块中的 datetime 类。可以通过以下代码获取当前时间:
```
from datetime import datetime
now = datetime.now()
print("当前时间为:", now)
```
输出结果如下:
```
当前时间为: 2022-03-11 15:34:30.123456
```
其中,now() 方法会返回一个 datetime 对象,包含了当前日期和时间的信息。你也可以通过调用该对象的各种方法来获取特定的信息,例如:
```
year = now.year
month = now.month
day = now.day
hour = now.hour
minute = now.minute
second = now.second
```
相关问题
如何使用Python获取当前时间?
要使用Python获取当前时间,可以使用内置的datetime模块。以下是一个示例代码:
```python
import datetime
# 获取当前日期和时间
current_time = datetime.datetime.now()
# 格式化输出当前时间
formatted_time = current_time.strftime("%Y-%m-%d %H:%M:%S")
print("当前时间为:", formatted_time)
```
这段代码中,我们首先导入了datetime模块。然后,使用`datetime.datetime.now()`函数获取当前日期和时间,保存在`current_time`变量中。接着,使用`strftime()`方法将时间格式化为我们想要的形式,这里使用了"%Y-%m-%d %H:%M:%S"的格式。最后,将格式化后的时间打印出来。
运行以上代码,你将获得当前的日期和时间。
使用Python获取当前时间?
使用Python获取当前时间的方法是使用`datetime`模块中的`datetime`类。下面是一个简单的示例代码:
```python
from datetime import datetime
current_time = datetime.now()
print(current_time)
```
这将打印出当前的日期和时间。你可以根据需要对日期和时间进行格式化,以满足特定的要求。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![py](https://img-home.csdnimg.cn/images/20210720083646.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)