0

How do I put the current date into a list in the format I want?

import datetime
today = datetime.date.today()
lst=[]
lst.append(today)

lst[0]
>>> datetime.date(2018, 6, 22)
print(lst[0]) #found this code on another post (I have no idea how it works)
>>> 2018-06-22

I am trying to get "2018-06-22", which is the output of print(lst[0]), into my list but I can only get "datetime.date(2018, 6, 22)". Thanks in advance!

Update:

lst.append(str(today))

Using this code gets me the same results and I have no idea how it works.

Jay Man
  • 31
  • 6

3 Answers3

1

I would use the strftime() function built into the datetime module. To do this with your code above, you only need to make one change:

import datetime
today = datetime.date.today()
lst=[]
lst.append(today.strftime('%Y-%m-%d'))
lst[0]

For more info, check out the docs: https://docs.python.org/3/library/datetime.html

dblclik
  • 406
  • 2
  • 8
0

print is creating a string version of the object. Try casting it yourself:

str(lst[0])
>>> '2018-06-21'

https://docs.python.org/3/library/functions.html#print https://docs.python.org/3/library/stdtypes.html#str

dashiell
  • 812
  • 4
  • 11
0

The issue is that in Python, all dates or objects. Essentially, when you are are referencing it, you are referencing the instance of the object. If you want to get the value (the actual date), you need to do what the others have recommended and cast it as a String, changing it from the actual date object into something useable. For instance, try:

x = str(lst[0])
x -> "2018-06-21"

I know the following doesn't actually answer your question directly, but it does provide some good info about date times if you are trying to learn more about them. I assume this is where you got your code from, so just browse again.

How to print date in a regular format in Python?

HunBurry
  • 113
  • 14