-4

I have a function stored into variable and I would like to execute that one into dictionary. Is it possible in Python?

import datetime
x = datetime.date(2021, 8, 23)
item = {
    "dt": x
}
print(item)

Obtained result: {'dt': datetime.date(2021, 8, 23)}

Wanted result: {'dt': '2021-08-23'}

How to do?

Adriano
  • 117
  • 1
  • 11
  • What are you trying to achieve? – Jiří Baum Sep 08 '21 at 14:33
  • 2
    If you want a string as the end result why are you creating a datetime object: `x = datetime.date(2021, 8, 23)`? – It_is_Chris Sep 08 '21 at 14:33
  • 3
    You don't have a _function_ stored in the dictionary. You have a `datetime.date` object. When you print this object, its representation shows up as `datetime.date(...)`. To print a formatted date, format it using `strftime()`. If you don't want an object and only want to save the string in the first place, do that. – Pranav Hosangadi Sep 08 '21 at 14:34
  • 1
    You can check this https://stackoverflow.com/questions/10624937/convert-datetime-object-to-a-string-of-date-only-in-python – Ahmet Burak Sep 08 '21 at 14:35

2 Answers2

0

Try the following code for your desired result:

import datetime

x = datetime.date(2021, 8, 23)

item = {
    "dt": str(x)
}

Converting the date to a string solves the problem you are facing.

0

What you are printing is the pre-defined __ repr __ function of datetime, not a string as you expected. So to keep it short, if you want to print it as a string as your requirement, try this (assuming you do not need to keep datetime data type in the dictionary)

import datetime
x = datetime.date(2021, 8, 23)
item = {
    "dt": x.strftime("%y-%m-%d")
}
print(item)
Long Doan
  • 303
  • 3
  • 10