0

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()
Rohit
  • 87
  • 1
  • 7
  • Don't mangle datetimeS yourself, use a library like `datetime` and its format specifiers. Trying to handle datetimeS yourself almost always results in bugs. https://stackoverflow.com/a/67778507/4583620 – Michael Ruth Jul 12 '22 at 16:54
  • To address your "incorrect" UNIX time, `.timestamp()` assumes local timezone is being converted but the returned timestamp is relative to the epoch 00:00:00 UTC on 1 January 1970. – Mark Tolonen Jul 12 '22 at 17:09

1 Answers1

0

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

Hussain Bohra
  • 985
  • 9
  • 15