Skip to content Skip to sidebar Skip to footer

Most Efficient Way In Python To Convert String With Whitespaces To Datetime For Mysql

I have data that comes in the following string format 'dd Mmm YYYY, HH:mm' (e.g. '07 Aug 2008, 16:25') What is the most efficient way to convert this in Python into the datetime st

Solution 1:

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.

Solution 2:

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

Post a Comment for "Most Efficient Way In Python To Convert String With Whitespaces To Datetime For Mysql"