Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List elements to time format and calculate the time diff from today

I am using python 3.6 and got some problems to calculate date.

I have a list composed of date elements like below:

dates = [['2017','01','15'], ['2017','01','14'], ['2017','01','13'],...]

I would like to make it to time format and calculate the days from today.

How can I fix my code?

Below is my code:

dates = [['2017', '01', '15'], ['2017', '01', '14'], ['2017', '01', '13']]

for date in dates:
    date_cand = "-".join(date)
    date_cand_time = time.strptime(date_cand,"%Y-%m-%d")
    (datetime.date.today() - datetime.date(date_cand_time)).days

I have this error message now:

TypeError: an integer is required (got type time.struct_time)

The result that I would like to have is:

4
5
6

Please help me to work this out.

like image 984
신종원 Avatar asked Dec 05 '25 06:12

신종원


1 Answers

date_cand_time is not an integer, it is a tuple with integers. You can't just pass that to the datetime.date() object. You'd have to pass in the first 3 elements as separate arguments instead:

(datetime.date.today() - datetime.date(*date_cand_time[:3])).days

The * tells Python to apply the values of the lst_reg_date_cand_time[:3] expression as separate arguments.

However, I'd not take a detour via time.strptime(); just map the 3 strings to integers and pass them in directly:

date_cand = datetime.date(*map(int, date))
(datetime.date.today() - date_cand).days

The arguments to datetime.date() are, after all, year, month and day, in the same order you have your strings.

If you must use strptime, then use datetime.datetime.strptime() and extract the date object from that:

date_cand = datetime.datetime.strptime("-".join(date), "%Y-%m-%d")
(datetime.date.today() - date_cand.date()).days

Demo:

>>> import datetime
>>> dates = [['2017','01','15'], ['2017','01','14'], ['2017','01','13']]
>>> for date in dates:
...     # using map, produces a date
...     date_cand = datetime.date(*map(int, date))
...     print(date_cand, (datetime.date.today() - date_cand).days)
...     # using datetime.datetime.strptime, produces a datetime
...     date_cand = datetime.datetime.strptime("-".join(date), "%Y-%m-%d")
...     print(date_cand, (datetime.date.today() - date_cand.date()).days)
...
2017-01-15 4
2017-01-15 00:00:00 4
2017-01-14 5
2017-01-14 00:00:00 5
2017-01-13 6
2017-01-13 00:00:00 6
like image 143
Martijn Pieters Avatar answered Dec 07 '25 20:12

Martijn Pieters