英文:
datetime formatting issue in python dictionary
问题
'Fiscal Period': datetime.date(2022, 11, 1),我希望得到'Fiscal Period': 11/1/2022。谢谢您提前的帮助。
英文:
I have a dictionary that currently has values that are date periods in the format "YY-MMM" (22-Nov). I'm attempting to replace that with an actual date, but running into issues with the formatting. Below is the code I'm using (in a loop), the key-value that results is 'Fiscal Period': datetime.date(2022, 11, 1), and I'm hoping to get 'Fiscal Period': 11/1/2022. Thanks in advance for assistancee
row['Fiscal Period'] = datetime.strptime("1-" + row['Fiscal Period']
[3:6] + "-" + row['Fiscal Year'], "%d-%b-%Y").date()
答案1
得分: 1
from datetime import datetime
# 示例数据以进行演示
row = {'Fiscal Period': '22-Nov', 'Fiscal Year': '2022'}
# 提取月份缩写(Nov)并构建日期
row['Fiscal Period'] = datetime.strptime("1-" + row['Fiscal Period'][3:6], "%d-%b").date().replace(year=int(row['Fiscal Year']))
# 格式化日期为所需格式(MM/DD/YYYY)
formatted_date = row['Fiscal Period'].strftime("%m/%d/%Y")
print(formatted_date)
输出:
11/01/2022
英文:
from datetime import datetime
# Sample data for demonstration
row = {'Fiscal Period': '22-Nov', 'Fiscal Year': '2022'}
# Extract month abbreviation (Nov) and construct the date
row['Fiscal Period'] = datetime.strptime("1-" + row['Fiscal Period'][3:6], "%d-%b").date().replace(year=int(row['Fiscal Year']))
# Format the date as desired (MM/DD/YYYY)
formatted_date = row['Fiscal Period'].strftime("%m/%d/%Y")
print(formatted_date)
Output:
11/01/2022
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论