Mittenchops
Mittenchops

Reputation: 19694

string datetime format to time() unix time format in python

I know this must be a well covered question elsewhere, but most questions I saw on SO looked like they were going in the opposite direction. I understand how to convert FROM time.time() TO human-readable datetime format as follows:

>>> import time, datetime
>>> thetime = time.time()
>>> thetime
1375289544.41976
>>> datetime.datetime.fromtimestamp(thetime).strftime("%Y-%m-%d %H:%M:%S")
'2013-07-31 12:51:08'

What's the function for going the inverse direction?

>>> thetime = '2013-07-30 21:23:14.744643'
>>> time.strptime(thetime, "%Y-%m-%d %H:%M:%S")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/_strptime.py", line 454, in _strptime_time
    return _strptime(data_string, format)[0]
  File "/usr/lib/python2.7/_strptime.py", line 328, in _strptime
    data_string[found.end():])
ValueError: unconverted data remains: .744643

I'd like to go from the string to the seconds since the epoch format.

UPDATE

This is what I'm using, but it seems inelegant---there must be a function that does this already, right?

def datetostamp(x):
    thetime = x.split('.')
    return(time.mktime(time.strptime(thetime[0], "%Y-%m-%d %H:%M:%S")) + float('.'+thetime[1]))

>>> thetime = '2013-07-30 21:23:14.744643'
>>> datetostamp(thetime)
1375233794.744643

UPDATE 2

Maybe more simply, I'm just missing the format code for fractions of seconds?

Upvotes: 3

Views: 2291

Answers (1)

Steve Barnes
Steve Barnes

Reputation: 28405

You were missing the format for fractions of a second.

time.strptime(thetime, "%Y-%m-%d %H:%M:%S.%f")

Upvotes: 3

Related Questions