可以使用datetime模块来进行字符串时间转换成日期的操作,然后再使用strftime方法将日期转换为字符串。

以下是一个示例代码:

from datetime import datetime

# 字符串时间
str_time = "2021-12-31 23:59:59"

# 将字符串时间转换为日期
date_time = datetime.strptime(str_time, "%Y-%m-%d %H:%M:%S")

# 提取年月
year = date_time.year
month = date_time.month

# 将年月转换为字符串
str_year = str(year)
str_month = str(month)

# 打印结果
print("年份:", str_year)
print("月份:", str_month)

输出结果:

年份: 2021
月份: 12

在这个示例中,首先将字符串时间"2021-12-31 23:59:59"使用strptime方法转换为日期。然后使用year和month属性提取年份和月份。最后使用str函数将年份和月份转换为字符串。

python 字符串时间转换成日期在提取年月后转换为字符串

原文地址: https://www.cveoy.top/t/topic/i4Mp 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录