0

I am writing a program that needs live dates(Means like current date). Here is the code.

from datetime import date
today_date = date.today()
print(list(today_date))

Now I want to convert this date into a list. But it gives me an error because the element obtained using date.today() isn't "iterable". So how do I actually convert the date into a list?

hmood
  • 603
  • 7
  • 25

6 Answers6

6

Perhaps you could use .timetuple for your purposes:

>>> datetime.date.today().timetuple()[:3]
(2020, 6, 25)
juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
3

Each part of the date and time are available as attributes of the datetime object. You can try something like below.

import datetime

today_date = datetime.datetime.today()

date_list = [today_date.year, today_date.month, today_date.day]

You can also access time similarly

Edwin Cruz
  • 507
  • 3
  • 10
2

There is a method called timetuple:

>>> from datetime import date
>>> today_date = date.today()
>>> today_date.timetuple()
time.struct_time(tm_year=2020, tm_mon=6, tm_mday=25, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=177, tm_isdst=-1)

As you can see, because you used date rather than datetime, the time part is zero.

You can convert the first three items to a list:

>>> list(today_date.timetuple()[:3])
[2020, 6, 25]

If you use datetime, then it is used in the same way, but the time part is also populated:

>>> from datetime import datetime
>>> datetime.today().timetuple()
time.struct_time(tm_year=2020, tm_mon=6, tm_mday=25, tm_hour=19, tm_min=39, tm_sec=47, tm_wday=3, tm_yday=177, tm_isdst=-1)

So you could do, for example:

>>> list(datetime.today().timetuple()[:6])
[2020, 6, 25, 19, 40, 35]
alani
  • 12,573
  • 2
  • 13
  • 23
1

You can simply add the year, month and day as elements in the array.

list = [today_date.year, today_date.month, today_date.day]
Rishikesh Dhokare
  • 3,559
  • 23
  • 34
1
from datetime import date
today_date = date.today()
print(str(today_date).split('-'))

OR

from datetime import datetime
print(str(datetime.now()).split()[0].split('-'))

OR

datetime.date.today().timetuple()[:3]
(2020, 6, 25)

OR

import datetime
today_date = datetime.datetime.today()
date_list = [today_date.year, today_date.month, today_date.day]
Shivam Jha
  • 3,160
  • 3
  • 22
  • 36
0

Instead of list(), you can use split():

from datetime import date
today_date = date.today()
print(str(today_date).split('-'))

Output:

['2020', '06', '25']



Another thing you can do:

from datetime import datetime
print(str(datetime.now()).split()[0].split('-'))

Output:

['2020', '06', '25']
Red
  • 26,798
  • 7
  • 36
  • 58