Search code examples
pythondatetimeintegerseconds

How to convert the time of a datetime object to an integer?


I need the time between two points as integer, to calculate the speed of an object. My first thought was to do it with an datetime object, but I can’t convert it from string to int:

from datetime import datetime


#this is already the right format in HH:MM:SS:MS 

d = (datetime.now()).time().isoformat() 
coverted = int(d) # not working because of the ":"

i already found an solution here (see below), but the if i print the code, I just get a weird number which doesn't help me at all.

import time
from datetime import datetime
timestamp = int(time.mktime(datetime.now().timetuple())

Solution

  • First use your date format and cut the strings that you're looking for: (using Sub-String)

    d = (datetime.now()).time().isoformat()   
    min = d[3:-10]
    seconds = d[6:-7]
    milliseconds = d[9:]
    

    Now you can use the int() command on your strings to convert them to Integers. For example:

    min = int(min)
    print min+1
    

    Will print the current minute plus one.