how to convert a datetime string back to datetime object?
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?
开发者_JS百科The string of datetime looks like:
2010-11-13 10:33:54.227806
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
I sugggest you install python-dateutilt:
from dateutil import parser
d = parser.parse(yourstring)
This library gets a datetime object from your date-string in a 'smart' way...
# 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)
精彩评论