How to convert `ctime` to `datetime` in Python?
Try datetime.strptime()
.
See: http://docs.python.org/library/datetime.html#datetime.datetime.strptime
You should use strptime
: this function parses a string representing a time according to a format. The return value is a struct_time.
The format parameter defaults to %a %b %d %H:%M:%S %Y
which matches the formatting returned by ctime().
So in your case just try the following line, since the default format is the one from ctime:
import datetime
import time
datetime.datetime.strptime(time.ctime(), "%a %b %d %H:%M:%S %Y")
Returns: datetime.datetime(2012, 4, 21, 4, 22, 00)
Just use %c
:
datetime.datetime.strptime(time.ctime(), "%c")