2

I have a string field like this..

2011-09-04 23:44:30.801000

and now I need to convert it to a datetime object in python so that I can calculate the difference between two datetime objects.

0

4 Answers 4

7

You should use datetime.datetime.strptime(), which converts a string and date format into a datetime.datetime object.

The format fields (e.g., %Y denotes four-digit year) are specified in the Python documentation.

>>> import datetime
>>> s      = '2011-09-04 23:44:30.801000'
>>> format = '%Y-%m-%d %H:%M:%S.%f'
>>> date=datetime.datetime.strptime(s, format)
>>> date
datetime.datetime(2011, 9, 4, 23, 44, 30, 801000)
Sign up to request clarification or add additional context in comments.

2 Comments

thanx :) i am using datetime.strptime(s, '%Y-%m-%d %H:%M:%S.%f') this.. need to add another datetime...
@diamond In that case, it would have been very helpful to attach the command along with its error message.
4

An alternative to datetime.datetime.strptime would be the python-dateutil libray. dateutil will allow you to do the same thing without the explicit formatting step:

>>> from dateutil import parser
>>> date_obj = parser.parse('2011-09-04 23:44:30.801000')
>>> date
datetime.datetime(2011, 9, 4, 23, 44, 30, 801000)

It's not a standard library module, but it is very handy for parsing date and time strings, especially if you don't have control over the format they come in.

One caveat if you install this library: version 1.5 is for Python 2 and version 2.0 is for Python 3. easy_install and pip default to installing the 2.0 version, so you have to explicitly indicate python-dateutil==1.5 if you are using Python 2.

1 Comment

+1 Nice idea, especially when you can't predict the exact format used.
0

Use datetime.datetime.strptime.

1 Comment

I think it's datetime.datetime.strptime()
0
# date string to datetime object
date_str = "2008-11-10 17:53:59"
dt_obj = datetime.strptime(date_str, "%Y-%m-%d %H:%M:%S")
print repr(dt_obj)

1 Comment

I am running this exact code with version 3.3 and I keep getting an error that says "Does not match format" Any suggestions why?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.