📜  python min date from dictionary - Python (1)

📅  最后修改于: 2023-12-03 14:46:00.399000             🧑  作者: Mango

Python Min Date from Dictionary

In this code snippet, we will find the minimum date from a dictionary in Python. Let's assume our dictionary has keys as string dates and values as some corresponding data.

import datetime

def find_min_date(dictionary):
    if len(dictionary) == 0:
        return None

    min_date = datetime.datetime.strptime(min(dictionary.keys()), '%Y-%m-%d')
    return min_date.strftime('%Y-%m-%d')

# Example Usage
data = {
    "2021-01-01": 10,
    "2022-03-15": 20,
    "2020-05-07": 30
}

min_date = find_min_date(data)
print("Minimum Date:", min_date)

In the find_min_date function, we first check if the dictionary is empty. If it is, we return None as there is no date to find. Then, we use the min function to find the minimum date among the dictionary keys. To compare the dates correctly, we utilize the datetime.strptime function from the datetime module. We specify the expected date format as '%Y-%m-%d'.

Finally, we return the minimum date as a string in the specified format using strftime. In the example usage, we create a sample dictionary data with string dates as keys and some data as values. We then call the find_min_date function and print the result.

The output will be:

Minimum Date: 2020-05-07

This code can be useful when working with date-related data stored in dictionaries, and you need to find the minimum date among them.