python获取date时间
时间: 2023-07-01 10:22:21 浏览: 63
你可以使用 Python 的内置模块 datetime 来获取日期和时间。以下是获取当前日期和时间的代码示例:
```python
from datetime import datetime
now = datetime.now()
print("当前日期和时间:", now)
```
输出结果类似于:
```
当前日期和时间: 2021-09-23 18:30:00.123456
```
你也可以使用 strftime 方法将日期和时间格式化成字符串,例如:
```python
from datetime import datetime
now = datetime.now()
formatted_date = now.strftime("%Y-%m-%d %H:%M:%S")
print("当前日期和时间:", formatted_date)
```
输出结果类似于:
```
当前日期和时间: 2021-09-23 18:30:00
```
在 strftime 方法中,%Y 表示年份,%m 表示月份,%d 表示日期,%H 表示小时,%M 表示分钟,%S 表示秒。你可以根据需要自定义格式。
相关问题
python获取当前时间
可以使用 Python 的 datetime 模块来获取当前时间。下面是一个示例代码:
```python
from datetime import datetime
now = datetime.now()
print("Current date and time:", now)
```
输出结果类似于:
```
Current date and time: 2021-06-24 16:23:45.123456
```
你也可以对时间进行格式化,例如:
```python
from datetime import datetime
now = datetime.now()
formatted_date = now.strftime("%Y-%m-%d %H:%M:%S")
print("Formatted date:", formatted_date)
```
输出结果类似于:
```
Formatted date: 2021-06-24 16:23:45
```
在这个示例中,"%Y-%m-%d %H:%M:%S" 是一个格式化字符串,用于指定输出的日期时间格式。具体的格式化选项可以参考 Python 官方文档。
python获取当前Date/Time格式时间
可以使用datetime模块中的datetime类来获取当前的日期和时间。
示例代码:
```python
import datetime
# 获取当前时间
now = datetime.datetime.now()
# 输出当前时间
print("当前时间为:", now)
# 格式化输出当前时间
print("格式化输出当前时间:", now.strftime("%Y-%m-%d %H:%M:%S"))
```
输出结果:
```
当前时间为: 2021-08-19 15:10:23.998402
格式化输出当前时间: 2021-08-19 15:10:23
```
在上面的示例中,我们首先导入了datetime模块,然后使用now()方法获取当前时间。最后,我们可以使用strftime()方法将时间格式化为我们想要的格式。