python 获取年月日
时间: 2023-10-18 15:09:38 浏览: 72
要获取当前年月日,可以使用 Python 中的 datetime 模块。以下是一个示例代码:
```python
import datetime
now = datetime.datetime.now()
year = now.year
month = now.month
day = now.day
print("当前日期:{}-{}-{}".format(year, month, day))
```
输出结果将类似于:
```
当前日期:2021-12-10
```
你也可以指定一个日期,例如:
```python
import datetime
date_str = "2022-01-01"
date = datetime.datetime.strptime(date_str, "%Y-%m-%d")
year = date.year
month = date.month
day = date.day
print("指定日期:{}-{}-{}".format(year, month, day))
```
输出结果将类似于:
```
指定日期:2022-1-1
```
相关问题
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
```
阅读全文