问题:如何将2024-10-04,转换成2024-10-4
date_str = "2024-10-04"
year, month, day = map(int, date_str.split('-'))
new_date_str = f"{year}-{month if month >= 10 else str(month)[-1]}-{day if day >= 10 else str(day)[-1]}"
print(new_date_str)
返回内容
2024-10-4
将2024-2-1 3:2:8,转换成2024-02-01 03:02:08呢
from datetime import datetime
def normalize_date_time(date_time_str):
parts = date_time_str.split(' ')
date_parts = parts[0].split('-')
time_parts = parts[1].split(':')
# 确保月份、日期和时间部分至少为两位
date_parts[1] = f"{int(date_parts[1]):02d}"
date_parts[2] = f"{int(date_parts[2]):02d}"
time_parts[0] = f"{int(time_parts[0]):02d}"
time_parts[1] = f"{int(time_parts[1]):02d}"
time_parts[2] = f"{int(time_parts[2]):02d}"
normalized_date = '-'.join(date_parts)
normalized_time = ':'.join(time_parts)
normalized_date_time = f"{normalized_date} {normalized_time}"
# 现在可以安全地解析并格式化为标准日期时间格式
parsed_date_time = datetime.strptime(normalized_date_time, '%Y-%m-%d %H:%M:%S')
standard_date_time = parsed_date_time.strftime('%Y-%m-%d %H:%M:%S')
return standard_date_time
input_date_time = "2024-2-11 3:32:08"
print(normalize_date_time(input_date_time))