Reputation: 69
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.
Upvotes: 2
Views: 6592
Reputation: 2246
# 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)
Upvotes: 0
Reputation: 5949
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
.
Upvotes: 4
Reputation: 136441
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)
Upvotes: 7