I want to convert a date-field (taken from a PostgreSQL string)
"2009-02-13 15:31:30.123000"
to a UNIX timestamp like
1234567890.123
Precision is at the millisecond level. How can I do this?
I want to convert a date-field (taken from a PostgreSQL string)
"2009-02-13 15:31:30.123000"
to a UNIX timestamp like
1234567890.123
Precision is at the millisecond level. How can I do this?
You can parse datetime string using datetime.datetime.strptime(some_datetime_string, '%Y-%m-%d %H:%M:%S.%f').
And then use this answer Python Create unix timestamp five minutes in the future to convert datetime.datetime to unix timestamp.
First, convert it to a datetime
object:
>>> import datetime
>>> date = datetime.datetime.strptime("2009-02-13 15:31:30.123000",
... "%Y-%m-%d %H:%M:%S.%f")
>>> date
datetime.datetime(2009, 2, 13, 15, 31, 30, 123000)
Then, convert it to a timestamp:
>>> import time
>>> t = time.mktime(date.timetuple())
>>> t
1234535490.0
Now, add the microseconds:
>>> t += date.microsecond/1000000.0
>>> t
1234535490.123
or, if you want to discard anything less than a millisecond:
>>> t += int(date.microsecond/1000)/1000.0
(int()
conversion is not necessary in Python 2, but left here for compatibility with Python 3).