python 获取年月日
时间: 2023-08-12 14:12:15 浏览: 44
你可以使用Python内置的datetime模块来获取当前的年月日。
以下是一个示例代码:
```python
import datetime
today = datetime.datetime.today()
year = today.year
month = today.month
day = today.day
print(year, month, day)
```
输出结果类似于:
```
2021 10 25
```
你也可以使用strftime()函数来格式化日期字符串,例如:
```python
import datetime
today = datetime.datetime.today()
date_str = today.strftime('%Y-%m-%d')
print(date_str)
```
输出结果为:
```
2021-10-25
```
相关问题
Python获取年月日
你可以使用Python的datetime模块来获取当前的年、月和日。以下是一个示例代码:
```python
from datetime import datetime
now = datetime.now()
year = now.year
month = now.month
day = now.day
print("当前日期:{}年{}月{}日".format(year, month, day))
```
这将打印出当前日期的年、月和日。你也可以根据需要将这些值存储在变量中,以便在代码中进一步使用。
python获取年月日时分秒
以下是两种Python获取当前时间的年月日时分秒的例子:
1. 使用time模块获取当前时间并格式化输出年月日时分秒:
```python
import time
now_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
print(now_time) # 输出:2022-08-09 16:43:35
```
2. 使用datetime模块获取当前时间的年月日时分秒:
```python
import datetime
today = datetime.datetime.today()
currentYear = today.year
currentMonth = today.month
currentDay = today.day
currentHour = today.hour
currentMinute = today.minute
currentSecond = today.second
print(currentYear, currentMonth, currentDay, currentHour, currentMinute, currentSecond) # 输出:2022 8 9 16 45 22
```