Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
4 views
in Python by (33.1k points)

This is my code:

import datetime 

today = datetime.date.today()

print today

This prints: 2008-11-22 which is exactly what I want.

But, I have a list I'm appending this to and then suddenly everything goes "wonky". Here is the code:

import datetime

mylist = [] 

today = datetime.date.today()

mylist.append(today)

print(mylist) 

This prints the following:

[datetime.date(2008, 11, 22)]

How can I get just a simple date like 2008-11-22?

1 Answer

0 votes
by (106k points)

This is why you are getting output like that:- 

  • Actually, you are getting that output because, in Python, dates are objects. Therefore, when you manipulate them, you manipulate objects, not strings, not timestamps nor anything.

This is how you should apply that method:-

for date in mylist : 

     print(str(date))

Your full code with above method:-

import datetime

mylist = []

today = datetime.date.today()

mylist.append(today)

for date in mylist : 

     print (str(date))

image

  • Another thing you can do is:-

This is the shorter way to perform this problem.

import time 

time.strftime("%Y-%m-%d") 


image

 

Related questions

0 votes
1 answer
0 votes
1 answer
asked Jul 3, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer

Browse Categories

...