-1
import datetime

baslangicAni = datetime.datetime.now()
baslangicSaati = datetime.datetime.strftime(baslangicAni, "%X")

bitisAni = datetime.datetime.now()
bitisSaati = datetime.datetime.strftime(bitisAni, "%X")

gecenSure = bitisSaati - baslangicSaati
print(f"Geçen Süre: {gecenSure}")

I want to find the difference between two times in seconds, but I can't find it.

khelwood
  • 55,782
  • 14
  • 81
  • 108
  • You are transforming datetima into string, and so string minus string doesn't make sense. Just keep numeric varsion. `datetime` module has also a deltatime class – Giacomo Catenazzi Oct 03 '22 at 14:40
  • Do you mean the difference in seconds between two *times* such as 09:30 and 11:45? – jarmod Oct 03 '22 at 14:40
  • @jarmod Yes, I wanted to write as you wrote. – Harun Uyguç Oct 03 '22 at 14:45
  • 1
    See https://stackoverflow.com/a/15067787/271415 – jarmod Oct 03 '22 at 14:46
  • @jarmod I've been researching for 2 hours but I didn't understand anything. Anyway, thanks for your help anyway. – Harun Uyguç Oct 03 '22 at 14:50
  • If you have two datetime objects (do you?) subtract the earlier from the latter. The result is a `datetime.timedelta` object. Call its `total_seconds()` method to get the difference in seconds. What is it specifically that you don't understand? – jarmod Oct 03 '22 at 14:59

1 Answers1

2

You can use .total_seconds() of the timedelta object you get, when you substract one datetime from a second one.

import datetime
first_date = datetime.datetime.now()
second_date = datetime.datetime(2022, 1, 1)

difference_in_seconds = (first_date-second_date).total_seconds()
  • Thank you very much indeed, but the app also takes the millisecond into account, I just wanted to take the sec. into account. – Harun Uyguç Oct 04 '22 at 14:25
  • Anyway, thank you again because even so, the app worked the way I wanted. If there is a method that takes seconds into account without taking milliseconds into account, I would appreciate it if you let me know. – Harun Uyguç Oct 04 '22 at 15:58
  • 1
    Seems like there is no default, but there are a few options listed here: https://stackoverflow.com/questions/18470627/how-do-i-remove-the-microseconds-from-a-timedelta-object –  Oct 04 '22 at 21:08