Reputation: 63299
I am storing a datetime
string in a database. Now I face a problem. When I fetch the string from the database, I need to convert it back to a datetime
object...
Any easy way to do that?
The string of datetime looks like:
2010-11-13 10:33:54.227806
Upvotes: 15
Views: 18802
Reputation: 31522
I sugggest you install python-dateutil with pip install python-dateutil
:
from dateutil import parser
d = parser.parse(yourstring)
This library gets a datetime
object from your date string in a 'smart' way...
Upvotes: 7
Reputation: 2246
# time tuple to datetime object
time_tuple = (2008, 11, 12, 13, 51, 18, 2, 317, 0)
dt_obj = datetime(*time_tuple[0:6])
print repr(dt_obj)
# 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)
# timestamp to datetime object in local time
timestamp = 1226527167.595983
dt_obj = datetime.fromtimestamp(timestamp)
print repr(dt_obj)
Upvotes: 3
Reputation: 16045
You want datetime.strptime(date_string, format).
from datetime import datetime
datetime.strptime("2010-11-13 10:33:54.227806", "%Y-%m-%d %H:%M:%S.%f")
For details on the format string, see http://docs.python.org/library/datetime.html#strftime-and-strptime-behavior
Upvotes: 29