在Python字典中的日期时间格式问题

huangapple go评论69阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年8月4日 01:54:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/76830527.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定