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

6

6

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 
Chophouse answered 17/1, 2018 at 10:23 Comment(1)
I edited the question including the not so beautiful way that I am using now.Chophouse
S
6

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
Spiros answered 17/1, 2018 at 10:40 Comment(4)
Do you have any idea why it works: reldate = datetime.datetime.strptime(d, "%Y-%m-%d") print reldate.strftime("%Y-%m-%d") And it doesn't: day = reldate.strptime("%Y-%m-%d") Error: day = str(reldate.strptime("%Y-%m-%d")) TypeError: strptime() takes exactly 2 arguments (1 given)Chophouse
@F.Lira. 'strptime' method takes 2 arguments. string and datetime format. EX: datetime.datetime.strptime(date1, "%Y-%m-%d")Spiros
I solved doing this:reldate = (datetime.datetime.strptime(d, "%Y-%m-%d")).strftime("%Y-%m-%d") \ day = reldate.replace('-', '')Chophouse
Just an FYI: If you do not want '-' you can directly remove it in strftime like datetime_object.strftime("%Y%m%d").Spiros
L
2

Try the below code ! You have to import the date time file .

Input :

import datetime

date1 = datetime.datetime.strptime("2015-1-3", "%Y-%m-%d").strftime("%d-%m-%Y")
print(date1)

today = datetime.date.today().strftime("%d-%m-%Y")
print(today)

Output :

03-01-2015
17-01-2018
Luane answered 17/1, 2018 at 10:39 Comment(0)
S
1

You can try:

>>> d = "2018-1-1"
>>> d_list = d.split("-")
>>> d_list
['2018', '1', '1']
>>> if len(d_list[1]) < 2:
    d_list[1] = "0"+d_list[1]

>>> if len(d_list[2]) < 2:
    d_list[2] = "0"+d_list[2]

>>> d_list
['2018', '01', '01']
Shaped answered 17/1, 2018 at 10:27 Comment(0)
P
1

This helps

import datetime    
d = datetime.datetime.strptime('2014-5-28', '%Y-%m-%d')
d.strftime('%Y-%m-%d')
Piperine answered 17/1, 2018 at 10:39 Comment(0)
R
1

This should work as well:

from datetime import datetime

d1 = "2001-1-1"
d2 = "2001-01-01"

d1 = datetime.strptime(d1, '%Y-%m-%d')
d1 = d1.strftime('%Y-%m-%d')
print(d1)

d2 = datetime.strptime(d2, '%Y-%m-%d')
d2 = d2.strftime('%Y-%m-%d')
print(d2)

Results:

2001-01-01
2001-01-01
Rumor answered 17/1, 2018 at 10:44 Comment(0)
C
0

May be this will help:

Data:

de = ["2018-1-1", "2018-02-1", "2017-3-29"]

Function:

from datetime import datetime


def format_date(d):
    """Format string representing date to format YYYY-MM-DD"""
    dl = d.split("-")
    return '{:%Y-%m-%d}'.format(datetime(int(dl[0]),int(dl[1]),int(dl[2])))


print([format_date(i) for i in de])

Result:

['2018-1-1', '2018-02-1', '2017-3-29']
Cantankerous answered 17/1, 2018 at 10:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.