Python 字符串时间转日期并提取年月
可以使用 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 函数将年份和月份转换为字符串。
原文地址: https://www.cveoy.top/t/topic/eCOr 著作权归作者所有。请勿转载和采集!