Search code examples
pythondatedate-format

Convert date format yyyy-m-d into yyyy-mm-dd on Python


In my table, I have different types of dates just with numbers and in this two formats:

yyyy-m-d
yyyy-mm-dd

Some values, as the month for example, don't have the zero in the case of months under 10 and I need it to create a condition to chose elements by the latest date.

I want that all of them have the same format:

yyyy-mm-dd

Any pythonic way to solve that?

For the moment I am using this:

if line.startswith('# Date:           '):
    #date = 2014-5-28
    d = line.strip().split(':')[-1].split('-').replace(' ','') 
        if len(d[0]) == 4:
            year = str(d[0])
        elif len(d[1]) < 2:
            month = '0'+ str(d[1])
        elif len(d[2]< 2):
            day = '0'+ str(d[1])

                        date = year +  month + day 

Solution

  • You can use the python inbuilt datetime module

    import datetime
    
    date1 = "2018-1-1"
    date2 = "2018-01-01"
    
    datetime_object = datetime.datetime.strptime(date1, "%Y-%m-%d")
    datetime_object2 = datetime.datetime.strptime(date2, "%Y-%m-%d")
    
    print datetime_object.strftime("%Y-%m-%d")
    print datetime_object2.strftime("%Y-%m-%d")
    

    Result:

    2018-01-01
    2018-01-01