0

I have a list of dates and hours. For each date, I would like to extract only the seconds value.

Here is my script :

import datetime

format_string = "%Y-%m-%d %H:%M"
now = datetime.datetime.now()
date = ['2021-01-29 15:15', '2021-01-29 15:50', '2021-01-29 17:00']
date = [(datetime.datetime.strptime(i, format_string)-now) for i in date]
print(date)

And here is the output :

[datetime.timedelta(seconds=7269, microseconds=211221), datetime.timedelta(seconds=9369, microseconds=211221), datetime.timedelta(seconds=13569, microseconds=211221)]

I just want the seconds for the three elements of the list 'data'

ahmedaao
  • 377
  • 1
  • 3
  • 14

2 Answers2

1

Just change

date = [(datetime.datetime.strptime(i, format_string)-now) for i in date]

To

date = [(datetime.datetime.strptime(i, format_string)-now).seconds for i in date]date = [(datetime.datetime.strptime(i, format_string)-now) for i in date]
Eduardo Coltri
  • 506
  • 3
  • 8
  • I am glad to help! You can also use ´total_seconds`, as its shown [here](https://stackoverflow.com/questions/5522031/convert-timedelta-to-total-seconds) – Eduardo Coltri Jan 29 '21 at 12:29
0

It works with :

date = [(datetime.datetime.strptime(i, format_string)-now).seconds for i in date]
ahmedaao
  • 377
  • 1
  • 3
  • 14