Python [snippet] : Date Format from String

I’m trying to scrap http://www.kaskus.co.id, It contains A challenging date format to scrape. They give some like this Today, 4 PM or Yesterday, 14:05 PM , or join date, They give Nov 2011. So, I create some function to handle that

import datetime
def mysql_date_format(str_date, code):
    from_date_format = {
        'kaskus_post_date' : '%d-%m-%Y, %I:%M %p',
        'kaskus_join_date' : '%b %Y',
    }

    return_date_format = {
        'kaskus_post_date' : '%Y-%m-%d %H:%M:%S',
        'kaskus_join_date' : '%Y-%m-%d %H:%M:%S'
    }
    if 'Today' in str_date:
        today = datetime.datetime.today()
        str_date = str_date.replace('Today',today.strftime('%d-%m-%Y'))
    elif 'Yesterday' in str_date:
        today = datetime.datetime.today()
        yesterday = today - datetime.timedelta(1)
        str_date = str_date.replace('Yesterday',yesterday.strftime('%d-%m-%Y'))

    return datetime.datetime.strptime(str_date, from_date_format).strftime(return_date_format)

Hope this simple snippet is useful for you 😀

Reference :

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s