简体   繁体   English

在Python字典中格式化日期

[英]Formatting dates within a Python dict

 if not all(key in payload for key in payloads[template]):
        raise InvalidPayloadException

    if 'order_date' in payload:
        payload['order_date'] = self._get_formatted_date(payload['order_date'])

    if 'payment_date' in payload:
        payload['payment_date'] = self._get_formatted_date(payload['payment_date'])

    if 'shipped_date' in payload:
        payload['shipped_date'] = self._get_formatted_date(payload['shipped_date'])

I have some code that triggers a PDF generation. 我有一些代码可以触发PDF生成。 It accepts a python dict that contains the payload for the PDF. 它接受包含PDF负载的python字典。

There are a good few number of dates that need to be displayed in the PDF but not all documents contain all PDFs. PDF中需要显示很多日期,但是并非所有文档都包含所有PDF。 I need to format the dates before sending it to the PDF. 我需要先格式化日期,然后再将其发送到PDF。 At the moment my code is a lot of different IF statements to catch all the possible dates and format them in the dict. 目前,我的代码是很多不同的IF语句,它们可以捕获所有可能的日期并将其格式化为dict。

Is there a more pythonic way to do it? 有没有更Python的方式来做到这一点?

Use a loop. 使用循环。

for date_key in ('order_date', 'payment_date', 'shipped_date'):
    if date_key in payload:
        payload[date_key] = self._get_formatted_date(payload[date_key])

You don't need any of the if statements. 您不需要任何if语句。

A common methodology in Python is EAFP (Easier to Ask for Forgiveness than Permission) rather than LBYL (Look Before You Leap). 在Python中,一种常见的方法是EAFP(比许可更容易寻求宽恕)而不是LBYL(飞跃前请先看)。 Hence you should prepare a tuple or list of keys you expect to be in the payload dict, and use try-except in case one of the keys is missing. 因此,您应该准备一个元组或键列表,该键或键列表应包含在payload字典中,并使用try-except ,以防丢失其中一个键。

for key in ('order_date', 'payment_date', 'shipped_date'):
    try:
        payload[key] = self._get_formatted_date(payload[key])
    except KeyError:
        print('{} not in payload dict'.format(key))

You could created a tuple of date keys and use a for loop. 您可以创建一个日期键元组并使用for循环。

date_keys = ("order_date", "payment_date", "shipped_date")

for date_key in date_keys:
    if date_key in payload:
        payload[date_key] = self._get_formatted_date(payload[date_key])

You could create a list of all possible dates to format and iterate over them 您可以创建所有可能日期的列表,以对其进行格式化和遍历

dates = [
    "order_date",
    "payment_date",
    "shipped_date"
]

for d in dates:
    if d in payload:
       payload[d] = self._get_formatted_date(payload[d])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM