Search code examples
python-3.xdatetimeunix-timestamp

date-time-string to UNIX time with milliseconds


I need to convert a date/time string to UNIX timestamp including the milliseconds. As the timetuple() does not include milli or microseconds I made a short workaround. But I was wondering, is there a better/nicer way to do this?

import datetime as dt
import time

timestamp = '2018-01-19 10:00:00.019'  # example of input time string 
tmp       = timestamp.split('.')
millisec  = tmp[-1]                    # extracting only milli-seconds
UX_time = time.mktime(dt.datetime.strptime(tmp[0], '%Y-%m-%d %H:%M:%S').timetuple()) + float(millisec)/1e3

print(UX_time)

1516352400.019

I realize my timezone is off by one hour, so you might be getting

print(UX_time)

1516356000.019


Solution

  • you can try this:

    timestamp = '2018-01-19 10:00:00.019' 
    tmp=np.datetime64(timestamp)
    print(tmp.view('<i8')/1e3)
    

    output:

    1516352400.019