Search code examples
pythondatetimeconverters

How to convert string date (Jan 25, 2021) to y-m-d date (2021-01-01) in python


I have strings like Jan 25, 2021 (Jan,Feb,Mar,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec) how can I convert it to 2021-01-25?

I was defining a function like:

def to_datetime(datestring):  
    
    #date = datetime.strptime(datestring, '%m.%d.%Y')
    #return date.strftime("%Y-%m-%d")
    
    return datetime.strptime(datestring, '%Y-%m-%d')

The issue are the month words so maybe I can replace the string to month number and then convert it but I am stuck


Solution

  • As you can see in my comment, you just need to use the right matching mask to get it right.

    Your date strings are in the format %b %d, %Y, so you need to use the same mask in strptime(). With that in mind, a function like this will do the job:

    from datetime import datetime
    
    
    def mdy_to_ymd(d):
        return datetime.strptime(d, '%b %d, %Y').strftime('%Y-%m-%d')
    

    And here is a proof of concept:

    
    >>> from datetime import datetime
    >>> 
    >>> 
    >>> def mdy_to_ymd(d):
    ...     return datetime.strptime(d, '%b %d, %Y').strftime('%Y-%m-%d')
    ... 
    >>> mdy_to_ymd('Jan 25, 2021')
    '2021-01-25'
    >>> 
    

    Bear in mind that strptime() creates a datetime object from a string matching a date using masking characters format. Once you get the right mask and the right representation in a datetime object, you can convert it to the desired format using strftime().

    For more information, check strftime() and strptime() Format Codes.