写一个python获取当前日期
时间: 2023-10-13 14:04:51 浏览: 139
可以使用Python的datetime模块来获取当前日期。
以下是一个示例代码:
```python
import datetime
# 获取当前日期
now = datetime.datetime.now()
# 格式化输出日期
print("当前日期为:", now.strftime("%Y-%m-%d"))
```
运行此代码将输出以下内容:
```
当前日期为: 2021-06-16
```
其中,`now()`方法返回当前日期和时间的datetime对象。`strftime()`方法用于将日期格式化为字符串。在上面的示例中,我们将日期格式化为“年-月-日”的形式(例如:“2021-06-16”)。
相关问题
写一个python获取当前时间
可以使用Python中的datetime模块来获取当前时间。具体实现代码如下:
```python
import datetime
now = datetime.datetime.now()
print("当前时间为:", now)
```
执行以上代码,输出结果如下:
```
当前时间为: 2021-06-07 15:27:32.615691
```
其中,now()方法获取的是当前系统时间,精确到毫秒。如果需要获取当前日期或者时间的某个部分,可以使用datetime模块中的其他方法,例如:
```python
# 获取当前日期
today = datetime.date.today()
print("当前日期为:", today)
# 获取当前时间的小时数
hour = now.hour
print("当前时间的小时数为:", hour)
# 获取当前时间的分钟数
minute = now.minute
print("当前时间的分钟数为:", minute)
# 获取当前时间的秒数
second = now.second
print("当前时间的秒数为:", second)
```
输出结果分别为:
```
当前日期为: 2021-06-07
当前时间的小时数为: 15
当前时间的分钟数为: 27
当前时间的秒数为: 32
```
Python 获取当前日期
你可以使用 Python 中的 datetime 模块来获取当前日期。以下是获取当前日期的示例代码:
```python
from datetime import date
today = date.today()
print("今天的日期是:", today)
```
输出结果应该类似于:
```
今天的日期是: 2021-11-22
```
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pptx](https://img-home.csdnimg.cn/images/20241231044947.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)