I have data that comes in the following string format "dd Mmm YYYY, HH:mm" (eg "07 Aug 2008, 16:25")
What is the most efficient way to convert this in Python into the datetime string format "YYYY-MM-DD HH:MM:SS" for MySQL?
Do you mean do the covert in Python?
>>> from datetime import datetime
>>> t = datetime.strptime('07 Aug 2008, 16:25', '%d %b %Y, %H:%M')
>>> t.strftime('%Y-%m-%d %H:%M:%S')
'2008-08-07 16:25:00'
>>>
Check the document for more details.
import datetime
dt = datetime.datetime.strptime(my_date_str, '%d %b %Y, %H:%M')
print dt.isoformat(' ')
Should do it, although
a) when I tried, I got some AttributeError about day_abbr in strptime. Seems like some kind of localization problem on my system. Give it a try on yours?
b) isoformat also gives you subseconds, which you might not want :/
Anyway, the things you want to study in the datetime library are strptime/strftime and isoformat (<- ISO 8601, best date + time format evar; if possible, try to use this everywhere).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.