0

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?

Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
James
  • 79
  • 1
  • 6

2 Answers2

1

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.

Community
  • 1
  • 1
Jinuk Kim
  • 765
  • 5
  • 5
1

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).

Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561