15

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
FObersteiner
  • 22,500
  • 8
  • 42
  • 72
Bin Chen
  • 61,507
  • 53
  • 142
  • 183

3 Answers3

29

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

Nicholas Knight
  • 15,774
  • 5
  • 45
  • 57
6

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...

Michael M.
  • 10,486
  • 9
  • 18
  • 34
diegueus9
  • 29,351
  • 16
  • 62
  • 74
  • Depends on your definition of smart. It tries to guess the format of your date string, and its guess might be wrong. – Pieter May 09 '17 at 13:07
2
# 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)
Viral Shah
  • 2,263
  • 5
  • 21
  • 36