Josh K
Josh K

Reputation: 28883

Converting Timestamps in Python to UNIX Timestamps

from time import time
time() # Gives me 1298046251.375916

I need to convert 01/01/2011 01:48:36.157 to a similar timestamp and am rather unfamiliar with Pythons date / time library. What is the easiest way to accomplish this? Is there a equivalent strtotime feature?

Considering MongoDB wants a datetime object it that would also be accepted instead of a unix style timestamp.

Upvotes: 1

Views: 2322

Answers (1)

Bite code
Bite code

Reputation: 596623

Short anwser:

>>> datetime.datetime.strptime ?
Type:       builtin_function_or_method
Base Class: <type 'builtin_function_or_method'>
String Form:    <built-in method strptime of type object at 0xb70b3520>
Namespace:  Interactive
Docstring:
    string, format -> new datetime parsed from a string (like time.strptime()).

Documentation reference.

The full parsing would look like:

>>> d = datetime.strptime("01/01/2011 01:48:36.157", "%m/%d/%Y %H:%M:%S.%f")

You can convert it to a timestamp:

import time
time.mktime(d.timetuple())

Upvotes: 3

Related Questions