Search code examples
pythondatetimeunix-timestamp

Converting Date and time to UNIX date format


I have been trying to convert the date and time given in following format "2021/12/04 11:10:00.000" to UNIX time.I have attached the sample of my program I tried. It does provide me the UNIX time but when I checked for the converted UNIX time it didn't gave me the correct UNIX time conversion.

for i in dx['date']:
year= i[0:4]
month = i[5:7]
day = i[8:10]
hr = i[11:13]
minute = i[14:16]
sec = i[17:19]
time = year+','+month+','+day+','+hr+','+minute+','+sec
print("Debug", time)
unixtime = datetime.datetime(int(year),int(month),int(day),int(hr),int(minute),int(sec)).timestamp()

Solution

  • Convert string datetime to datetime obj, and then retrieve timestamp.

    from datetime import datetime
    t = "2021/12/04 11:10:00.000"
    dt = datetime.strptime(t, "%Y/%m/%d %H:%M:%S.%f")
    dt.timestamp()
    

    Output:

    1638637800.0