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

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

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

  1. row['Fiscal Period'] = datetime.strptime("1-" + row['Fiscal Period']
  2. [3:6] + "-" + row['Fiscal Year'], "%d-%b-%Y").date()

答案1

得分: 1

  1. from datetime import datetime
  2. # 示例数据以进行演示
  3. row = {'Fiscal Period': '22-Nov', 'Fiscal Year': '2022'}
  4. # 提取月份缩写(Nov)并构建日期
  5. row['Fiscal Period'] = datetime.strptime("1-" + row['Fiscal Period'][3:6], "%d-%b").date().replace(year=int(row['Fiscal Year']))
  6. # 格式化日期为所需格式(MM/DD/YYYY)
  7. formatted_date = row['Fiscal Period'].strftime("%m/%d/%Y")
  8. print(formatted_date)

输出:

  1. 11/01/2022
英文:
  1. from datetime import datetime
  2. # Sample data for demonstration
  3. row = {'Fiscal Period': '22-Nov', 'Fiscal Year': '2022'}
  4. # Extract month abbreviation (Nov) and construct the date
  5. row['Fiscal Period'] = datetime.strptime("1-" + row['Fiscal Period'][3:6], "%d-%b").date().replace(year=int(row['Fiscal Year']))
  6. # Format the date as desired (MM/DD/YYYY)
  7. formatted_date = row['Fiscal Period'].strftime("%m/%d/%Y")
  8. print(formatted_date)

Output:

  1. 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:

确定