python 取日期中的年的后两位
时间: 2024-02-27 13:56:34 浏览: 25
要取日期中的年的后两位,可以使用 Python 的 datetime 模块。具体代码如下:
```python
from datetime import datetime
# 假设日期为 2022 年 10 月 1 日
date_str = '2022-10-01'
# 将字符串转换为 datetime 对象
date = datetime.strptime(date_str, '%Y-%m-%d')
# 取年的后两位
year = date.strftime('%y')
print(year) # 输出 22
```
上述代码中,首先将字符串类型的日期转换为 datetime 对象,然后使用 strftime 方法,以 '%y' 的格式取出年的后两位。最终输出的结果为 '22'。
相关问题
python 按指定格式取当天日期
可以使用Python中的datetime模块来获取当前日期,然后使用strftime函数来按指定格式输出日期。
下面是一个例子:
```python
import datetime
now = datetime.datetime.now()
formatted_date = now.strftime("%Y-%m-%d")
print(formatted_date)
```
输出:
```
2021-09-21
```
在这个例子中,我们首先使用`datetime.datetime.now()`获取当前日期和时间。然后,我们使用`strftime`函数将日期格式化为`%Y-%m-%d`的字符串格式。`%Y`表示四位数的年份,`%m`表示两位数的月份,`%d`表示两位数的日期。
使用strptime函数,将两位同学的字符型的出生日期转换为日期格式,然后计算出他们的差.
可以使用Python内置的datetime模块中的strptime函数将字符型的出生日期转换为日期格式,并使用日期的减法操作计算他们的差。下面是一个示例代码:
```python
from datetime import datetime
# 两位同学的出生日期(字符串)
student1_dob = "1999-05-15"
student2_dob = "2001-10-22"
# 将字符串转换为日期格式
student1_dob_date = datetime.strptime(student1_dob, "%Y-%m-%d").date()
student2_dob_date = datetime.strptime(student2_dob, "%Y-%m-%d").date()
# 计算两位同学的年龄差
age_diff = abs((student2_dob_date - student1_dob_date).days // 365)
print("两位同学的年龄差为:{}岁".format(age_diff))
```
输出结果为:
```
两位同学的年龄差为:2岁
```
注意,这里使用了`abs`函数取绝对值,因为计算出的差可能为负数(例如第一位同学的出生日期在第二位同学之后)。另外,`//`表示整除,即返回整数部分。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)